task_id
stringlengths
11
12
skeleton
stringlengths
929
4.57k
test
stringlengths
1.48k
20.1k
solution_code
stringlengths
496
3.91k
import_statement
sequencelengths
0
4
class_description
stringlengths
69
249
methods_info
listlengths
2
10
class_name
stringlengths
4
24
test_classes
sequencelengths
2
11
class_constructor
stringlengths
15
1.13k
fields
sequencelengths
0
9
ClassEval_0
import logging import datetime class AccessGatewayFilter: """ This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording. """ def __init__(self): pass def filter(self, request): """ Filter the incoming request based on certain rules and conditions. :param request: dict, the incoming request details :return: bool, True if the request is allowed, False otherwise >>> filter = AccessGatewayFilter() >>> filter.filter({'path': '/login', 'method': 'POST'}) True """ def is_start_with(self, request_uri): """ Check if the request URI starts with certain prefixes. Currently, the prefixes being checked are "/api" and "/login". :param request_uri: str, the URI of the request :return: bool, True if the URI starts with certain prefixes, False otherwise >>> filter = AccessGatewayFilter() >>> filter.is_start_with('/api/data') True """ def get_jwt_user(self, request): """ Get the user information from the JWT token in the request. :param request: dict, the incoming request details :return: dict or None, the user information if the token is valid, None otherwise >>> filter = AccessGatewayFilter() >>> filter.get_jwt_user({'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1'+str(datetime.date.today())}}}) {'user': {'name': 'user1'} """ def set_current_user_info_and_log(self, user): """ Set the current user information and log the access. :param user: dict, the user information :return: None >>> filter = AccessGatewayFilter() >>> user = {'name': 'user1', 'address': '127.0.0.1'} >>> filter.set_current_user_info_and_log(user) """
import unittest class AccessGatewayFilterTestFilter(unittest.TestCase): def test_filter_1(self): agf = AccessGatewayFilter() request = {'path': '/api/data', 'method': 'GET'} res = agf.filter(request) self.assertTrue(res) def test_filter_2(self): agf = AccessGatewayFilter() request = {'path': '/api/data', 'method': 'POST'} res = agf.filter(request) self.assertTrue(res) def test_filter_3(self): agf = AccessGatewayFilter() request = {'path': '/login/data', 'method': 'GET'} res = agf.filter(request) self.assertTrue(res) def test_filter_4(self): agf = AccessGatewayFilter() request = {'path': '/login/data', 'method': 'POST'} res = agf.filter(request) self.assertTrue(res) def test_filter_5(self): agf = AccessGatewayFilter() request = {'path': '/abc', 'method': 'POST', 'headers': { 'Authorization': {'user': {'name': 'user1', 'level': 5, 'address': 'address1'}, 'jwt': 'user1' + str(datetime.date.today())}}} res = agf.filter(request) self.assertTrue(res) def test_filter_6(self): agf = AccessGatewayFilter() request = {'path': '/abc', 'method': 'POST', 'headers': { 'Authorization': {'user': {'name': 'user1', 'level': 3, 'address': 'address1'}, 'jwt': 'user1' + str(datetime.date.today() - datetime.timedelta(days=365))}}} res = agf.filter(request) self.assertFalse(res) def test_filter_7(self): agf = AccessGatewayFilter() request = {'path': '/abc', 'method': 'POST', 'headers': { 'Authorization': {'user': {'name': 'user1', 'level': 1, 'address': 'address1'}, 'jwt': 'user1' + str(datetime.date.today())}}} res = agf.filter(request) self.assertIsNone(res) def test_filter_8(self): agf = AccessGatewayFilter() request = {'path': '/abc', 'method': 'POST', 'headers': { 'Authorization': {'user': {'name': 'user1', 'level': 3, 'address': 'address1'}, 'jwt': 'user2' + str(datetime.date.today() - datetime.timedelta(days=365))}}} res = agf.filter(request) self.assertTrue(res) class AccessGatewayFilterTestIsStartWith(unittest.TestCase): def test_is_start_with_1(self): agf = AccessGatewayFilter() request_uri = '/api/data' res = agf.is_start_with(request_uri) self.assertTrue(res) def test_is_start_with_2(self): agf = AccessGatewayFilter() request_uri = '/admin/settings' res = agf.is_start_with(request_uri) self.assertFalse(res) def test_is_start_with_3(self): agf = AccessGatewayFilter() request_uri = '/login/data' res = agf.is_start_with(request_uri) self.assertTrue(res) def test_is_start_with_4(self): agf = AccessGatewayFilter() request_uri = '/abc/data' res = agf.is_start_with(request_uri) self.assertFalse(res) def test_is_start_with_5(self): agf = AccessGatewayFilter() request_uri = '/def/data' res = agf.is_start_with(request_uri) self.assertFalse(res) class AccessGatewayFilterTestGetJwtUser(unittest.TestCase): def test_get_jwt_user_1(self): agf = AccessGatewayFilter() request = { 'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1' + str(datetime.date.today())}}} res = agf.get_jwt_user(request) self.assertIsNotNone(res) def test_get_jwt_user_2(self): agf = AccessGatewayFilter() request = { 'headers': {'Authorization': {'user': {'name': 'user2'}, 'jwt': 'user2' + str(datetime.date.today())}}} res = agf.get_jwt_user(request) self.assertIsNotNone(res) def test_get_jwt_user_3(self): agf = AccessGatewayFilter() request = { 'headers': {'Authorization': {'user': {'name': 'user3'}, 'jwt': 'user3' + str(datetime.date.today())}}} res = agf.get_jwt_user(request) self.assertIsNotNone(res) def test_get_jwt_user_4(self): agf = AccessGatewayFilter() request = { 'headers': {'Authorization': {'user': {'name': 'user4'}, 'jwt': 'user4' + str(datetime.date.today())}}} res = agf.get_jwt_user(request) self.assertIsNotNone(res) def test_get_jwt_user_5(self): agf = AccessGatewayFilter() request = {'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1' + str( datetime.date.today() - datetime.timedelta(days=5))}}} res = agf.get_jwt_user(request) self.assertIsNone(res) class AccessGatewayFilterTest(unittest.TestCase): def test_AccessGatewayFilter(self): agf = AccessGatewayFilter() request = {'path': '/api/data', 'method': 'GET'} res = agf.filter(request) self.assertTrue(res) request_uri = '/api/data' res = agf.is_start_with(request_uri) self.assertTrue(res) request = { 'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1' + str(datetime.date.today())}}} res = agf.get_jwt_user(request) self.assertIsNotNone(res)
import logging import datetime class AccessGatewayFilter: def __init__(self): pass def filter(self, request): request_uri = request['path'] method = request['method'] if self.is_start_with(request_uri): return True try: token = self.get_jwt_user(request) user = token['user'] if user['level'] > 2: self.set_current_user_info_and_log(user) return True except: return False def is_start_with(self, request_uri): start_with = ["/api", '/login'] for s in start_with: if request_uri.startswith(s): return True return False def get_jwt_user(self, request): token = request['headers']['Authorization'] user = token['user'] if token['jwt'].startswith(user['name']): jwt_str_date = token['jwt'].split(user['name'])[1] jwt_date = datetime.datetime.strptime(jwt_str_date, "%Y-%m-%d") if datetime.datetime.today() - jwt_date >= datetime.timedelta(days=3): return None return token def set_current_user_info_and_log(self, user): host = user['address'] logging.log(msg=user['name'] + host + str(datetime.datetime.now()), level=1)
[ "import logging", "import datetime" ]
""" This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording. """
[ { "method_name": "filter", "method_description": "def filter(self, request):\n \"\"\"\n Filter the incoming request based on certain rules and conditions.\n :param request: dict, the incoming request details\n :return: bool, True if the request is allowed, False otherwise\n >>> filter = AccessGatewayFilter()\n >>> filter.filter({'path': '/login', 'method': 'POST'})\n True\n\n \"\"\"", "test_class": "AccessGatewayFilterTestFilter", "test_code": "class AccessGatewayFilterTestFilter(unittest.TestCase):\n def test_filter_1(self):\n agf = AccessGatewayFilter()\n request = {'path': '/api/data', 'method': 'GET'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_2(self):\n agf = AccessGatewayFilter()\n request = {'path': '/api/data', 'method': 'POST'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_3(self):\n agf = AccessGatewayFilter()\n request = {'path': '/login/data', 'method': 'GET'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_4(self):\n agf = AccessGatewayFilter()\n request = {'path': '/login/data', 'method': 'POST'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_5(self):\n agf = AccessGatewayFilter()\n request = {'path': '/abc', 'method': 'POST',\n 'headers': {\n 'Authorization': {'user': {'name': 'user1', 'level': 5, 'address': 'address1'},\n 'jwt': 'user1' + str(datetime.date.today())}}}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_6(self):\n agf = AccessGatewayFilter()\n request = {'path': '/abc', 'method': 'POST',\n 'headers': {\n 'Authorization': {'user': {'name': 'user1', 'level': 3, 'address': 'address1'},\n 'jwt': 'user1' + str(datetime.date.today() - datetime.timedelta(days=365))}}}\n res = agf.filter(request)\n self.assertFalse(res)\n\n def test_filter_7(self):\n agf = AccessGatewayFilter()\n request = {'path': '/abc', 'method': 'POST',\n 'headers': {\n 'Authorization': {'user': {'name': 'user1', 'level': 1, 'address': 'address1'},\n 'jwt': 'user1' + str(datetime.date.today())}}}\n res = agf.filter(request)\n self.assertIsNone(res)\n\n def test_filter_8(self):\n agf = AccessGatewayFilter()\n request = {'path': '/abc', 'method': 'POST',\n 'headers': {\n 'Authorization': {'user': {'name': 'user1', 'level': 3, 'address': 'address1'},\n 'jwt': 'user2' + str(datetime.date.today() - datetime.timedelta(days=365))}}}\n res = agf.filter(request)\n self.assertTrue(res)", "solution_code": "def filter(self, request):\n request_uri = request['path']\n method = request['method']\n\n if self.is_start_with(request_uri):\n return True\n\n try:\n token = self.get_jwt_user(request)\n user = token['user']\n if user['level'] > 2:\n self.set_current_user_info_and_log(user)\n return True\n except:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "is_start_with", "get_jwt_user", "set_current_user_info_and_log" ] } }, { "method_name": "is_start_with", "method_description": "def is_start_with(self, request_uri):\n \"\"\"\n Check if the request URI starts with certain prefixes.\n Currently, the prefixes being checked are \"/api\" and \"/login\".\n :param request_uri: str, the URI of the request\n :return: bool, True if the URI starts with certain prefixes, False otherwise\n >>> filter = AccessGatewayFilter()\n >>> filter.is_start_with('/api/data')\n True\n\n \"\"\"", "test_class": "AccessGatewayFilterTestIsStartWith", "test_code": "class AccessGatewayFilterTestIsStartWith(unittest.TestCase):\n def test_is_start_with_1(self):\n agf = AccessGatewayFilter()\n request_uri = '/api/data'\n res = agf.is_start_with(request_uri)\n self.assertTrue(res)\n\n def test_is_start_with_2(self):\n agf = AccessGatewayFilter()\n request_uri = '/admin/settings'\n res = agf.is_start_with(request_uri)\n self.assertFalse(res)\n\n def test_is_start_with_3(self):\n agf = AccessGatewayFilter()\n request_uri = '/login/data'\n res = agf.is_start_with(request_uri)\n self.assertTrue(res)\n\n def test_is_start_with_4(self):\n agf = AccessGatewayFilter()\n request_uri = '/abc/data'\n res = agf.is_start_with(request_uri)\n self.assertFalse(res)\n\n def test_is_start_with_5(self):\n agf = AccessGatewayFilter()\n request_uri = '/def/data'\n res = agf.is_start_with(request_uri)\n self.assertFalse(res)", "solution_code": "def is_start_with(self, request_uri):\n start_with = [\"/api\", '/login']\n for s in start_with:\n if request_uri.startswith(s):\n return True\n return False", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "get_jwt_user", "method_description": "def get_jwt_user(self, request):\n \"\"\"\n Get the user information from the JWT token in the request.\n :param request: dict, the incoming request details\n :return: dict or None, the user information if the token is valid, None otherwise\n >>> filter = AccessGatewayFilter()\n >>> filter.get_jwt_user({'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1'+str(datetime.date.today())}}})\n {'user': {'name': 'user1'}\n\n \"\"\"", "test_class": "AccessGatewayFilterTestGetJwtUser", "test_code": "class AccessGatewayFilterTestGetJwtUser(unittest.TestCase):\n def test_get_jwt_user_1(self):\n agf = AccessGatewayFilter()\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)\n\n def test_get_jwt_user_2(self):\n agf = AccessGatewayFilter()\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user2'}, 'jwt': 'user2' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)\n\n def test_get_jwt_user_3(self):\n agf = AccessGatewayFilter()\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user3'}, 'jwt': 'user3' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)\n\n def test_get_jwt_user_4(self):\n agf = AccessGatewayFilter()\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user4'}, 'jwt': 'user4' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)\n\n def test_get_jwt_user_5(self):\n agf = AccessGatewayFilter()\n request = {'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1' + str(\n datetime.date.today() - datetime.timedelta(days=5))}}}\n res = agf.get_jwt_user(request)\n self.assertIsNone(res)", "solution_code": "def get_jwt_user(self, request):\n token = request['headers']['Authorization']\n user = token['user']\n if token['jwt'].startswith(user['name']):\n jwt_str_date = token['jwt'].split(user['name'])[1]\n jwt_date = datetime.datetime.strptime(jwt_str_date, \"%Y-%m-%d\")\n if datetime.datetime.today() - jwt_date >= datetime.timedelta(days=3):\n return None\n return token", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "set_current_user_info_and_log", "method_description": "def set_current_user_info_and_log(self, user):\n \"\"\"\n Set the current user information and log the access.\n :param user: dict, the user information\n :return: None\n >>> filter = AccessGatewayFilter()\n >>> user = {'name': 'user1', 'address': '127.0.0.1'}\n >>> filter.set_current_user_info_and_log(user)\n\n \"\"\"", "test_class": "AccessGatewayFilterTest", "test_code": "class AccessGatewayFilterTest(unittest.TestCase):\n def test_AccessGatewayFilter(self):\n agf = AccessGatewayFilter()\n request = {'path': '/api/data', 'method': 'GET'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n request_uri = '/api/data'\n res = agf.is_start_with(request_uri)\n self.assertTrue(res)\n\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)", "solution_code": "def set_current_user_info_and_log(self, user):\n host = user['address']\n logging.log(msg=user['name'] + host + str(datetime.datetime.now()), level=1)", "dependencies": { "Standalone": false, "lib_dependencies": [ "logging", "datetime" ], "field_dependencies": [], "method_dependencies": [] } } ]
AccessGatewayFilter
[ "AccessGatewayFilterTestFilter", "AccessGatewayFilterTestIsStartWith", "AccessGatewayFilterTestGetJwtUser", "AccessGatewayFilterTest" ]
class AccessGatewayFilter: def __init__(self): pass
[]
ClassEval_1
import math class AreaCalculator: """ This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus. """ def __init__(self, radius): """ Initialize the radius for shapes. :param radius: float """ self.radius = radius def calculate_circle_area(self): """ calculate the area of circle based on self.radius :return: area of circle, float >>> areaCalculator = AreaCalculator(2) >>> areaCalculator.calculate_circle_area() 12.566370614359172 """ def calculate_sphere_area(self): """ calculate the area of sphere based on self.radius :return: area of sphere, float >>> areaCalculator = AreaCalculator(2) >>> areaCalculator.calculate_sphere_area() 50.26548245743669 """ def calculate_cylinder_area(self, height): """ calculate the area of cylinder based on self.radius and height :param height: height of cylinder, float :return: area of cylinder, float >>> areaCalculator = AreaCalculator(2) >>> areaCalculator.calculate_cylinder_area(3) 62.83185307179586 """ def calculate_sector_area(self, angle): """ calculate the area of sector based on self.radius and angle :param angle: angle of sector, float :return: area of sector, float >>> areaCalculator = AreaCalculator(2) >>> areaCalculator.calculate_sector_area(math.pi) 6.283185307179586 """ def calculate_annulus_area(self, inner_radius, outer_radius): """ calculate the area of annulus based on inner_radius and out_radius :param inner_radius: inner radius of sector, float :param outer_radius: outer radius of sector, float :return: area of annulus, float >>> areaCalculator.calculate_annulus_area(2, 3) 15.707963267948966 """
import unittest class AreaCalculatorTestCalculateCircleArea(unittest.TestCase): def test_calculate_circle_area(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(12.56, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_circle_area_2(self): areaCalculator = AreaCalculator(2.5) self.assertAlmostEqual(19.63, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_circle_area_3(self): areaCalculator = AreaCalculator(2000) self.assertAlmostEqual(12566370.61, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_circle_area_4(self): areaCalculator = AreaCalculator(0) self.assertAlmostEqual(0, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_circle_area_5(self): areaCalculator = AreaCalculator(0.1) self.assertAlmostEqual(0.031, areaCalculator.calculate_circle_area(), delta=0.01) class AreaCalculatorTestCalculateSphereArea(unittest.TestCase): def test_calculate_sphere_area(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(50.27, areaCalculator.calculate_sphere_area(), delta=0.01) def test_calculate_sphere_area_2(self): areaCalculator = AreaCalculator(2.5) self.assertAlmostEqual(19.63, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_sphere_area_3(self): areaCalculator = AreaCalculator(2000) self.assertAlmostEqual(12566370.61, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_sphere_area_4(self): areaCalculator = AreaCalculator(0) self.assertAlmostEqual(0, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_sphere_area_5(self): areaCalculator = AreaCalculator(0.1) self.assertAlmostEqual(0.031, areaCalculator.calculate_circle_area(), delta=0.01) class AreaCalculatorTestCalculateCylinderArea(unittest.TestCase): def test_calculate_cylinder_area(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(50.27, areaCalculator.calculate_cylinder_area(2), delta=0.01) def test_calculate_cylinder_area_2(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(25.13, areaCalculator.calculate_cylinder_area(0), delta=0.01) def test_calculate_cylinder_area_3(self): areaCalculator = AreaCalculator(0) self.assertAlmostEqual(0, areaCalculator.calculate_cylinder_area(2000), delta=0.01) def test_calculate_cylinder_area_4(self): areaCalculator = AreaCalculator(2.5) self.assertAlmostEqual(70.68, areaCalculator.calculate_cylinder_area(2), delta=0.01) def test_calculate_cylinder_area_5(self): areaCalculator = AreaCalculator(2.5) self.assertAlmostEqual(62.83, areaCalculator.calculate_cylinder_area(1.5), delta=0.01) class AreaCalculatorTestCalculateSectorArea(unittest.TestCase): def test_calculate_sector_area(self): areaCalculator = AreaCalculator(1.5) self.assertAlmostEqual(3.53, areaCalculator.calculate_sector_area(math.pi), delta=0.01) def test_calculate_sector_area_2(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(3.14, areaCalculator.calculate_sector_area(math.pi/2), delta=0.01) def test_calculate_sector_area_3(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(0, areaCalculator.calculate_sector_area(0), delta=0.01) def test_calculate_sector_area_4(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(12.56, areaCalculator.calculate_sector_area(2*math.pi), delta=0.01) def test5_calculate_sector_area_5(self): areaCalculator = AreaCalculator(0) self.assertAlmostEqual(0, areaCalculator.calculate_sector_area(math.pi), delta=0.01) class AreaCalculatorTestCalculateAnnulusArea(unittest.TestCase): def test_calculate_annulus_area(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(25.128, areaCalculator.calculate_annulus_area(1, 3), delta=0.01) def test_calculate_annulus_area_2(self): areaCalculator = AreaCalculator(2.5) self.assertAlmostEqual(0, areaCalculator.calculate_annulus_area(3, 3), delta=0.01) def test_calculate_annulus_area_3(self): areaCalculator = AreaCalculator(2000) self.assertAlmostEqual(3.14, areaCalculator.calculate_annulus_area(0, 1), delta=0.01) def test_calculate_annulus_area_4(self): areaCalculator = AreaCalculator(0) self.assertAlmostEqual(25.13, areaCalculator.calculate_annulus_area(1, 3), delta=0.01) def test_calculate_annulus_area_5(self): areaCalculator = AreaCalculator(2.5) self.assertAlmostEqual(25.13, areaCalculator.calculate_annulus_area(1, 3), delta=0.01) class AreaCalculatorTestCalculateMain(unittest.TestCase): def test_main(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(12.56, areaCalculator.calculate_circle_area(), delta=0.01) self.assertAlmostEqual(50.27, areaCalculator.calculate_sphere_area(), delta=0.01) self.assertAlmostEqual(50.27, areaCalculator.calculate_cylinder_area(2), delta=0.01) self.assertAlmostEqual(6.28, areaCalculator.calculate_sector_area(math.pi), delta=0.01) self.assertAlmostEqual(25.128, areaCalculator.calculate_annulus_area(1, 3), delta=0.01)
import math class AreaCalculator: def __init__(self, radius): self.radius = radius def calculate_circle_area(self): return math.pi * self.radius ** 2 def calculate_sphere_area(self): return 4 * math.pi * self.radius ** 2 def calculate_cylinder_area(self, height): return 2 * math.pi * self.radius * (self.radius + height) def calculate_sector_area(self, angle): return self.radius ** 2 * angle / 2 def calculate_annulus_area(self, inner_radius, outer_radius): return math.pi * (outer_radius ** 2 - inner_radius ** 2)
[ "import math" ]
""" This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus. """
[ { "method_name": "calculate_circle_area", "method_description": "def calculate_circle_area(self):\n \"\"\"\n calculate the area of circle based on self.radius\n :return: area of circle, float\n >>> areaCalculator = AreaCalculator(2)\n >>> areaCalculator.calculate_circle_area()\n 12.566370614359172\n \"\"\"", "test_class": "AreaCalculatorTestCalculateCircleArea", "test_code": "class AreaCalculatorTestCalculateCircleArea(unittest.TestCase):\n def test_calculate_circle_area(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(12.56, areaCalculator.calculate_circle_area(), delta=0.01)\n def test_calculate_circle_area_2(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(19.63, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_circle_area_3(self):\n areaCalculator = AreaCalculator(2000)\n self.assertAlmostEqual(12566370.61, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_circle_area_4(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(0, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_circle_area_5(self):\n areaCalculator = AreaCalculator(0.1)\n self.assertAlmostEqual(0.031, areaCalculator.calculate_circle_area(), delta=0.01)", "solution_code": "def calculate_circle_area(self):\n return math.pi * self.radius ** 2", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [ "self.radius" ], "method_dependencies": [] } }, { "method_name": "calculate_sphere_area", "method_description": "def calculate_sphere_area(self):\n \"\"\"\n calculate the area of sphere based on self.radius\n :return: area of sphere, float\n >>> areaCalculator = AreaCalculator(2)\n >>> areaCalculator.calculate_sphere_area()\n 50.26548245743669\n \"\"\"", "test_class": "AreaCalculatorTestCalculateSphereArea", "test_code": "class AreaCalculatorTestCalculateSphereArea(unittest.TestCase):\n def test_calculate_sphere_area(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(50.27, areaCalculator.calculate_sphere_area(), delta=0.01)\n\n def test_calculate_sphere_area_2(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(19.63, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_sphere_area_3(self):\n areaCalculator = AreaCalculator(2000)\n self.assertAlmostEqual(12566370.61, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_sphere_area_4(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(0, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_sphere_area_5(self):\n areaCalculator = AreaCalculator(0.1)\n self.assertAlmostEqual(0.031, areaCalculator.calculate_circle_area(), delta=0.01)", "solution_code": "def calculate_sphere_area(self):\n return 4 * math.pi * self.radius ** 2", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [ "self.radius" ], "method_dependencies": [] } }, { "method_name": "calculate_cylinder_area", "method_description": "def calculate_cylinder_area(self, height):\n \"\"\"\n calculate the area of cylinder based on self.radius and height\n :param height: height of cylinder, float\n :return: area of cylinder, float\n >>> areaCalculator = AreaCalculator(2)\n >>> areaCalculator.calculate_cylinder_area(3)\n 62.83185307179586\n \"\"\"", "test_class": "AreaCalculatorTestCalculateCylinderArea", "test_code": "class AreaCalculatorTestCalculateCylinderArea(unittest.TestCase):\n def test_calculate_cylinder_area(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(50.27, areaCalculator.calculate_cylinder_area(2), delta=0.01)\n\n def test_calculate_cylinder_area_2(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(25.13, areaCalculator.calculate_cylinder_area(0), delta=0.01)\n\n def test_calculate_cylinder_area_3(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(0, areaCalculator.calculate_cylinder_area(2000), delta=0.01)\n\n def test_calculate_cylinder_area_4(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(70.68, areaCalculator.calculate_cylinder_area(2), delta=0.01)\n\n def test_calculate_cylinder_area_5(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(62.83, areaCalculator.calculate_cylinder_area(1.5), delta=0.01)", "solution_code": "def calculate_cylinder_area(self, height):\n return 2 * math.pi * self.radius * (self.radius + height)", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [ "self.radius" ], "method_dependencies": [] } }, { "method_name": "calculate_sector_area", "method_description": "def calculate_sector_area(self, angle):\n \"\"\"\n calculate the area of sector based on self.radius and angle\n :param angle: angle of sector, float\n :return: area of sector, float\n >>> areaCalculator = AreaCalculator(2)\n >>> areaCalculator.calculate_sector_area(math.pi)\n 6.283185307179586\n \"\"\"", "test_class": "AreaCalculatorTestCalculateSectorArea", "test_code": "class AreaCalculatorTestCalculateSectorArea(unittest.TestCase):\n def test_calculate_sector_area(self):\n areaCalculator = AreaCalculator(1.5)\n self.assertAlmostEqual(3.53, areaCalculator.calculate_sector_area(math.pi), delta=0.01)\n\n def test_calculate_sector_area_2(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(3.14, areaCalculator.calculate_sector_area(math.pi/2), delta=0.01)\n\n def test_calculate_sector_area_3(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(0, areaCalculator.calculate_sector_area(0), delta=0.01)\n\n def test_calculate_sector_area_4(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(12.56, areaCalculator.calculate_sector_area(2*math.pi), delta=0.01)\n\n def test5_calculate_sector_area_5(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(0, areaCalculator.calculate_sector_area(math.pi), delta=0.01)", "solution_code": "def calculate_sector_area(self, angle):\n return self.radius ** 2 * angle / 2", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.radius" ], "method_dependencies": [] } }, { "method_name": "calculate_annulus_area", "method_description": "def calculate_annulus_area(self, inner_radius, outer_radius):\n \"\"\"\n calculate the area of annulus based on inner_radius and out_radius\n :param inner_radius: inner radius of sector, float\n :param outer_radius: outer radius of sector, float\n :return: area of annulus, float\n >>> areaCalculator.calculate_annulus_area(2, 3)\n 15.707963267948966\n \"\"\"", "test_class": "AreaCalculatorTestCalculateAnnulusArea", "test_code": "class AreaCalculatorTestCalculateAnnulusArea(unittest.TestCase):\n def test_calculate_annulus_area(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(25.128, areaCalculator.calculate_annulus_area(1, 3), delta=0.01)\n\n def test_calculate_annulus_area_2(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(0, areaCalculator.calculate_annulus_area(3, 3), delta=0.01)\n\n def test_calculate_annulus_area_3(self):\n areaCalculator = AreaCalculator(2000)\n self.assertAlmostEqual(3.14, areaCalculator.calculate_annulus_area(0, 1), delta=0.01)\n\n def test_calculate_annulus_area_4(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(25.13, areaCalculator.calculate_annulus_area(1, 3), delta=0.01)\n\n def test_calculate_annulus_area_5(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(25.13, areaCalculator.calculate_annulus_area(1, 3), delta=0.01)", "solution_code": "def calculate_annulus_area(self, inner_radius, outer_radius):\n return math.pi * (outer_radius ** 2 - inner_radius ** 2)", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [], "method_dependencies": [] } } ]
AreaCalculator
[ "AreaCalculatorTestCalculateCircleArea", "AreaCalculatorTestCalculateSphereArea", "AreaCalculatorTestCalculateCylinderArea", "AreaCalculatorTestCalculateSectorArea", "AreaCalculatorTestCalculateAnnulusArea", "AreaCalculatorTestCalculateMain" ]
class AreaCalculator: def __init__(self, radius): """ Initialize the radius for shapes. :param radius: float """ self.radius = radius
[ "self.radius" ]
ClassEval_2
class ArgumentParser: """ This is a class for parsing command line arguments to a dictionary. """ def __init__(self): """ Initialize the fields. self.arguments is a dict that stores the args in a command line self.requried is a set that stores the required arguments self.types is a dict that stores type of every arguments. >>> parser.arguments {'key1': 'value1', 'option1': True} >>> parser.required {'arg1'} >>> parser.types {'arg1': 'type1'} """ self.arguments = {} self.required = set() self.types = {} def parse_arguments(self, command_string): """ Parses the given command line argument string and invoke _convert_type to stores the parsed result in specific type in the arguments dictionary. Checks for missing required arguments, if any, and returns False with the missing argument names, otherwise returns True. :param command_string: str, command line argument string, formatted like "python script.py --arg1=value1 -arg2 value2 --option1 -option2" :return tuple: (True, None) if parsing is successful, (False, missing_args) if parsing fails, where missing_args is a set of the missing argument names which are str. >>> parser.parse_arguments("python script.py --arg1=value1 -arg2 value2 --option1 -option2") (True, None) >>> parser.arguments {'arg1': 'value1', 'arg2': 'value2', 'option1': True, 'option2': True} """ def get_argument(self, key): """ Retrieves the value of the specified argument from the arguments dictionary and returns it. :param key: str, argument name :return: The value of the argument, or None if the argument does not exist. >>> parser.arguments {'arg1': 'value1', 'arg2': 'value2', 'option1': True, 'option2': True} >>> parser.get_argument('arg2') 'value2' """ def add_argument(self, arg, required=False, arg_type=str): """ Adds an argument to self.types and self.required. Check if it is a required argument and store the argument type. If the argument is set as required, it wull be added to the required set. The argument type and name are stored in the types dictionary as key-value pairs. :param arg: str, argument name :param required: bool, whether the argument is required, default is False :param arg_type:str, Argument type, default is str >>> parser.add_argument('arg1', True, 'int') >>> parser.required {'arg1'} >>> parser.types {'arg1': 'int'} """ def _convert_type(self, arg, value): """ Try to convert the type of input value by searching in self.types. :param value: str, the input value in command line :return: return corresponding value in self.types if convert successfully, or the input value oherwise >>> parser.types {'arg1': int} >>> parser._convert_type('arg1', '21') 21 """
import unittest class ArgumentParserTestParseArguments(unittest.TestCase): def setUp(self): self.parser = ArgumentParser() # key value arguments def test_parse_arguments_1(self): command_str = "script --name=John --age=25" self.parser.add_argument("name") self.parser.add_argument("age", arg_type=int) result, missing_args = self.parser.parse_arguments(command_str) self.assertTrue(result) self.assertIsNone(missing_args) self.assertEqual(self.parser.get_argument("name"), "John") self.assertEqual(self.parser.get_argument("age"), 25) # switches options def test_parse_arguments_2(self): command_str = "script --verbose -d" self.parser.add_argument("verbose", arg_type=bool) self.parser.add_argument("d", arg_type=bool) result, missing_args = self.parser.parse_arguments(command_str) self.assertTrue(result) self.assertIsNone(missing_args) self.assertEqual(self.parser.get_argument("verbose"), True) self.assertEqual(self.parser.get_argument("d"), True) # miss required def test_parse_arguments_3(self): command_str = "script --name=John" self.parser.add_argument("name") self.parser.add_argument("age", required=True, arg_type=int) result, missing_args = self.parser.parse_arguments(command_str) self.assertFalse(result) self.assertEqual(missing_args, {"age"}) def test_parse_arguments_4(self): command_str = "script --name=John" self.parser.add_argument("name") self.parser.add_argument("age", required=False, arg_type=int) result, missing_args = self.parser.parse_arguments(command_str) self.assertTrue(result) self.assertEqual(missing_args, None) def test_parse_arguments_5(self): command_str = "script --name=John" self.parser.add_argument("name") self.parser.add_argument("age", arg_type=int) result, missing_args = self.parser.parse_arguments(command_str) self.assertTrue(result) self.assertEqual(missing_args, None) class ArgumentParserTestGetArgument(unittest.TestCase): def setUp(self): self.parser = ArgumentParser() # key exists def test_get_argument_1(self): self.parser.arguments = {"name": "John"} result = self.parser.get_argument("name") self.assertEqual(result, "John") # key not exists def test_get_argument_2(self): self.parser.arguments = {"name": "John", "age": 25} result = self.parser.get_argument("age") self.assertEqual(result, 25) def test_get_argument_3(self): self.parser.arguments = {"name": "John", "age": "25", "verbose": True} result = self.parser.get_argument("verbose") self.assertEqual(result, True) def test_get_argument_4(self): self.parser.arguments = {"name": "Amy", "age": 25, "verbose": True, "d": True} result = self.parser.get_argument("d") self.assertEqual(result, True) def test_get_argument_5(self): self.parser.arguments = {"name": "John", "age": 25, "verbose": True, "d": True, "option": "value"} result = self.parser.get_argument("option") self.assertEqual(result, "value") class ArgumentParserTestAddArgument(unittest.TestCase): def setUp(self): self.parser = ArgumentParser() def test_add_argument(self): self.parser.add_argument("name") self.parser.add_argument("age", required=True, arg_type=int) self.assertEqual(self.parser.required, {"age"}) self.assertEqual(self.parser.types, {"name": str, "age": int}) def test_add_argument_2(self): self.parser.add_argument("name") self.parser.add_argument("age", required=False, arg_type=int) self.parser.add_argument("verbose", arg_type=bool) self.assertEqual(self.parser.required, set()) self.assertEqual(self.parser.types, {"name": str, "age": int, "verbose": bool}) def test_add_argument_3(self): self.parser.add_argument("name") self.parser.add_argument("age", required=False, arg_type=int) self.parser.add_argument("verbose", arg_type=bool) self.parser.add_argument("d") self.assertEqual(self.parser.required, set()) self.assertEqual(self.parser.types, {"name": str, "age": int, "verbose": bool, "d": str}) def test_add_argument_4(self): self.parser.add_argument("name") self.parser.add_argument("age", required=False, arg_type=int) self.parser.add_argument("verbose", arg_type=bool) self.parser.add_argument("d") self.parser.add_argument("option") self.assertEqual(self.parser.required, set()) self.assertEqual(self.parser.types, {"name": str, "age": int, "verbose": bool, "d": str, "option": str}) def test_add_argument_5(self): self.parser.add_argument("name") self.parser.add_argument("age", required=False, arg_type=int) self.parser.add_argument("verbose", arg_type=bool) self.parser.add_argument("d") self.parser.add_argument("option") self.parser.add_argument("option2", arg_type=bool) self.assertEqual(self.parser.required, set()) self.assertEqual(self.parser.types, {"name": str, "age": int, "verbose": bool, "d": str, "option": str, "option2": bool}) class ArgumentParserTestConvertType(unittest.TestCase): def setUp(self): self.parser = ArgumentParser() def test_convert_type_1(self): self.parser.types = {"age": int} result = self.parser._convert_type("age", "25") self.assertEqual(result, 25) # fail def test_convert_type_2(self): self.parser.types = {"age": int} result = self.parser._convert_type("age", "twenty-five") self.assertEqual(result, "twenty-five") def test_convert_type_3(self): self.parser.types = {"age": int} result = self.parser._convert_type("age", "25") self.assertEqual(result, 25) def test_convert_type_4(self): self.parser.types = {"age": int, "verbose": bool} result = self.parser._convert_type("verbose", "True") self.assertEqual(result, True) def test_convert_type_5(self): self.parser.types = {"age": int, "verbose": bool} result = self.parser._convert_type("verbose", "False") self.assertEqual(result, True) class ArgumentParserTestMain(unittest.TestCase): def test_main(self): parser = ArgumentParser() command = "script --arg1=21 --option1 -arg2 value -option2" parser.add_argument('arg1', required=True, arg_type=int) parser.add_argument('arg2') self.assertEqual(parser.required, {'arg1'}) self.assertEqual(parser.types, {'arg1': int, 'arg2': str}) self.assertEqual(parser.arguments, {}) parser.parse_arguments(command) arguments = {'arg1': 21, 'option1': True, 'arg2': 'value', 'option2': True} self.assertEqual(parser.arguments, arguments)
class ArgumentParser: def __init__(self): self.arguments = {} self.required = set() self.types = {} def parse_arguments(self, command_string): args = command_string.split()[1:] for i in range(len(args)): arg = args[i] if arg.startswith('--'): key_value = arg[2:].split('=') if len(key_value) == 2: self.arguments[key_value[0]] = self._convert_type(key_value[0], key_value[1]) else: self.arguments[key_value[0]] = True elif arg.startswith('-'): key = arg[1:] if i + 1 < len(args) and not args[i + 1].startswith('-'): self.arguments[key] = self._convert_type(key, args[i + 1]) else: self.arguments[key] = True missing_args = self.required - set(self.arguments.keys()) if missing_args: return False, missing_args return True, None def get_argument(self, key): return self.arguments.get(key) def add_argument(self, arg, required=False, arg_type=str): if required: self.required.add(arg) self.types[arg] = arg_type def _convert_type(self, arg, value): try: return self.types[arg](value) except (ValueError, KeyError): return value
[]
""" This is a class for parsing command line arguments to a dictionary. """
[ { "method_name": "parse_arguments", "method_description": "def parse_arguments(self, command_string):\n \"\"\"\n Parses the given command line argument string and invoke _convert_type to stores the parsed result in specific type in the arguments dictionary.\n Checks for missing required arguments, if any, and returns False with the missing argument names, otherwise returns True.\n :param command_string: str, command line argument string, formatted like \"python script.py --arg1=value1 -arg2 value2 --option1 -option2\"\n :return tuple: (True, None) if parsing is successful, (False, missing_args) if parsing fails,\n where missing_args is a set of the missing argument names which are str.\n >>> parser.parse_arguments(\"python script.py --arg1=value1 -arg2 value2 --option1 -option2\")\n (True, None)\n >>> parser.arguments\n {'arg1': 'value1', 'arg2': 'value2', 'option1': True, 'option2': True}\n \"\"\"", "test_class": "ArgumentParserTestParseArguments", "test_code": "class ArgumentParserTestParseArguments(unittest.TestCase):\n\n def setUp(self):\n self.parser = ArgumentParser()\n\n # key value arguments\n def test_parse_arguments_1(self):\n command_str = \"script --name=John --age=25\"\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", arg_type=int)\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertTrue(result)\n self.assertIsNone(missing_args)\n self.assertEqual(self.parser.get_argument(\"name\"), \"John\")\n self.assertEqual(self.parser.get_argument(\"age\"), 25)\n\n # switches options\n def test_parse_arguments_2(self):\n command_str = \"script --verbose -d\"\n self.parser.add_argument(\"verbose\", arg_type=bool)\n self.parser.add_argument(\"d\", arg_type=bool)\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertTrue(result)\n self.assertIsNone(missing_args)\n self.assertEqual(self.parser.get_argument(\"verbose\"), True)\n self.assertEqual(self.parser.get_argument(\"d\"), True)\n\n # miss required\n def test_parse_arguments_3(self):\n command_str = \"script --name=John\"\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=True, arg_type=int)\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertFalse(result)\n self.assertEqual(missing_args, {\"age\"})\n\n def test_parse_arguments_4(self):\n command_str = \"script --name=John\"\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertTrue(result)\n self.assertEqual(missing_args, None)\n\n def test_parse_arguments_5(self):\n command_str = \"script --name=John\"\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", arg_type=int)\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertTrue(result)\n self.assertEqual(missing_args, None)", "solution_code": "def parse_arguments(self, command_string):\n args = command_string.split()[1:]\n for i in range(len(args)):\n arg = args[i]\n if arg.startswith('--'):\n key_value = arg[2:].split('=')\n if len(key_value) == 2:\n self.arguments[key_value[0]] = self._convert_type(key_value[0], key_value[1])\n else:\n self.arguments[key_value[0]] = True\n elif arg.startswith('-'):\n key = arg[1:]\n if i + 1 < len(args) and not args[i + 1].startswith('-'):\n self.arguments[key] = self._convert_type(key, args[i + 1])\n else:\n self.arguments[key] = True\n missing_args = self.required - set(self.arguments.keys())\n if missing_args:\n return False, missing_args\n\n return True, None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.arguments", "self.required" ], "method_dependencies": [ "_convert_type" ] } }, { "method_name": "get_argument", "method_description": "def get_argument(self, key):\n \"\"\"\n Retrieves the value of the specified argument from the arguments dictionary and returns it.\n :param key: str, argument name\n :return: The value of the argument, or None if the argument does not exist.\n >>> parser.arguments\n {'arg1': 'value1', 'arg2': 'value2', 'option1': True, 'option2': True}\n >>> parser.get_argument('arg2')\n 'value2'\n \"\"\"", "test_class": "ArgumentParserTestGetArgument", "test_code": "class ArgumentParserTestGetArgument(unittest.TestCase):\n\n def setUp(self):\n self.parser = ArgumentParser()\n\n # key exists\n def test_get_argument_1(self):\n self.parser.arguments = {\"name\": \"John\"}\n result = self.parser.get_argument(\"name\")\n self.assertEqual(result, \"John\")\n\n # key not exists\n def test_get_argument_2(self):\n self.parser.arguments = {\"name\": \"John\", \"age\": 25}\n result = self.parser.get_argument(\"age\")\n self.assertEqual(result, 25)\n\n def test_get_argument_3(self):\n self.parser.arguments = {\"name\": \"John\", \"age\": \"25\", \"verbose\": True}\n result = self.parser.get_argument(\"verbose\")\n self.assertEqual(result, True)\n\n def test_get_argument_4(self):\n self.parser.arguments = {\"name\": \"Amy\", \"age\": 25, \"verbose\": True, \"d\": True}\n result = self.parser.get_argument(\"d\")\n self.assertEqual(result, True)\n\n def test_get_argument_5(self):\n self.parser.arguments = {\"name\": \"John\", \"age\": 25, \"verbose\": True, \"d\": True, \"option\": \"value\"}\n result = self.parser.get_argument(\"option\")\n self.assertEqual(result, \"value\")", "solution_code": "def get_argument(self, key):\n return self.arguments.get(key)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.arguments" ], "method_dependencies": [] } }, { "method_name": "add_argument", "method_description": "def add_argument(self, arg, required=False, arg_type=str):\n \"\"\"\n Adds an argument to self.types and self.required.\n Check if it is a required argument and store the argument type.\n If the argument is set as required, it wull be added to the required set.\n The argument type and name are stored in the types dictionary as key-value pairs.\n :param arg: str, argument name\n :param required: bool, whether the argument is required, default is False\n :param arg_type:str, Argument type, default is str\n >>> parser.add_argument('arg1', True, 'int')\n >>> parser.required\n {'arg1'}\n >>> parser.types\n {'arg1': 'int'}\n \"\"\"", "test_class": "ArgumentParserTestAddArgument", "test_code": "class ArgumentParserTestAddArgument(unittest.TestCase):\n\n def setUp(self):\n self.parser = ArgumentParser()\n\n def test_add_argument(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=True, arg_type=int)\n\n self.assertEqual(self.parser.required, {\"age\"})\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int})\n\n def test_add_argument_2(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n self.parser.add_argument(\"verbose\", arg_type=bool)\n\n self.assertEqual(self.parser.required, set())\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int, \"verbose\": bool})\n\n def test_add_argument_3(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n self.parser.add_argument(\"verbose\", arg_type=bool)\n self.parser.add_argument(\"d\")\n\n self.assertEqual(self.parser.required, set())\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int, \"verbose\": bool, \"d\": str})\n\n def test_add_argument_4(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n self.parser.add_argument(\"verbose\", arg_type=bool)\n self.parser.add_argument(\"d\")\n self.parser.add_argument(\"option\")\n\n self.assertEqual(self.parser.required, set())\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int, \"verbose\": bool, \"d\": str, \"option\": str})\n\n def test_add_argument_5(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n self.parser.add_argument(\"verbose\", arg_type=bool)\n self.parser.add_argument(\"d\")\n self.parser.add_argument(\"option\")\n self.parser.add_argument(\"option2\", arg_type=bool)\n\n self.assertEqual(self.parser.required, set())\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int, \"verbose\": bool, \"d\": str, \"option\": str, \"option2\": bool})", "solution_code": "def add_argument(self, arg, required=False, arg_type=str):\n if required:\n self.required.add(arg)\n self.types[arg] = arg_type", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.required", "self.types" ], "method_dependencies": [] } }, { "method_name": "_convert_type", "method_description": "def _convert_type(self, arg, value):\n \"\"\"\n Try to convert the type of input value by searching in self.types.\n :param value: str, the input value in command line\n :return: return corresponding value in self.types if convert successfully, or the input value oherwise\n >>> parser.types\n {'arg1': int}\n >>> parser._convert_type('arg1', '21')\n 21\n \"\"\"", "test_class": "ArgumentParserTestConvertType", "test_code": "class ArgumentParserTestConvertType(unittest.TestCase):\n\n def setUp(self):\n self.parser = ArgumentParser()\n\n def test_convert_type_1(self):\n self.parser.types = {\"age\": int}\n result = self.parser._convert_type(\"age\", \"25\")\n self.assertEqual(result, 25)\n\n # fail\n def test_convert_type_2(self):\n self.parser.types = {\"age\": int}\n result = self.parser._convert_type(\"age\", \"twenty-five\")\n self.assertEqual(result, \"twenty-five\")\n\n def test_convert_type_3(self):\n self.parser.types = {\"age\": int}\n result = self.parser._convert_type(\"age\", \"25\")\n self.assertEqual(result, 25)\n\n def test_convert_type_4(self):\n self.parser.types = {\"age\": int, \"verbose\": bool}\n result = self.parser._convert_type(\"verbose\", \"True\")\n self.assertEqual(result, True)\n \n def test_convert_type_5(self):\n self.parser.types = {\"age\": int, \"verbose\": bool}\n result = self.parser._convert_type(\"verbose\", \"False\")\n self.assertEqual(result, True)", "solution_code": "def _convert_type(self, arg, value):\n try:\n return self.types[arg](value)\n except (ValueError, KeyError):\n return value", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.types" ], "method_dependencies": [] } } ]
ArgumentParser
[ "ArgumentParserTestParseArguments", "ArgumentParserTestGetArgument", "ArgumentParserTestAddArgument", "ArgumentParserTestConvertType", "ArgumentParserTestMain" ]
class ArgumentParser: def __init__(self): """ Initialize the fields. self.arguments is a dict that stores the args in a command line self.requried is a set that stores the required arguments self.types is a dict that stores type of every arguments. >>> parser.arguments {'key1': 'value1', 'option1': True} >>> parser.required {'arg1'} >>> parser.types {'arg1': 'type1'} """ self.arguments = {} self.required = set() self.types = {}
[ "self.arguments", "self.required", "self.types" ]
ClassEval_3
import itertools class ArrangementCalculator: """ The Arrangement class provides permutation calculations and selection operations for a given set of data elements. """ def __init__(self, datas): """ Initializes the ArrangementCalculator object with a list of datas. :param datas: List, the data elements to be used for arrangements. """ self.datas = datas @staticmethod def count(n, m=None): """ Counts the number of arrangements by choosing m items from n items (permutations). If m is not provided or n equals m, returns factorial(n). :param n: int, the total number of items. :param m: int, the number of items to be chosen (default=None). :return: int, the count of arrangements. >>> ArrangementCalculator.count(5, 3) 60 """ @staticmethod def count_all(n): """ Counts the total number of all possible arrangements by choosing at least 1 item and at most n items from n items. :param n: int, the total number of items. :return: int, the count of all arrangements. >>> ArrangementCalculator.count_all(4) 64 """ def select(self, m=None): """ Generates a list of arrangements by selecting m items from the internal datas. If m is not provided, selects all items. :param m: int, the number of items to be chosen (default=None). :return: List, a list of arrangements. >>> ac = ArrangementCalculator([1, 2, 3, 4]) >>> ac.select(2) [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]] """ def select_all(self): """ Generates a list of all arrangements by selecting at least 1 item and at most the number of internal datas. :return: List, a list of all arrangements. >>> ac = ArrangementCalculator([1, 2, 3]) >>> ac.select_all() [[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] """ @staticmethod def factorial(n): """ Calculates the factorial of a given number. :param n: int, the number to calculate the factorial. :return: int, the factorial of the given number. >>> ArrangementCalculator.factorial(4) 24 """
import unittest class ArrangementCalculatorTestCount(unittest.TestCase): def test_count_1(self): res = ArrangementCalculator.count(5, 3) self.assertEqual(res, 60) def test_count_2(self): res = ArrangementCalculator.count(4, 3) self.assertEqual(res, 24) def test_count_3(self): res = ArrangementCalculator.count(6, 3) self.assertEqual(res, 120) def test_count_4(self): res = ArrangementCalculator.count(7, 3) self.assertEqual(res, 210) def test_count_5(self): res = ArrangementCalculator.count(4, 4) self.assertEqual(res, 24) class ArrangementCalculatorTestCountAll(unittest.TestCase): def test_count_all_1(self): res = ArrangementCalculator.count_all(4) self.assertEqual(res, 64) def test_count_all_2(self): res = ArrangementCalculator.count_all(1) self.assertEqual(res, 1) def test_count_all_3(self): res = ArrangementCalculator.count_all(2) self.assertEqual(res, 4) def test_count_all_4(self): res = ArrangementCalculator.count_all(3) self.assertEqual(res, 15) def test_count_all_5(self): res = ArrangementCalculator.count_all(5) self.assertEqual(res, 325) class ArrangementCalculatorTestSelect(unittest.TestCase): def test_select_1(self): ac = ArrangementCalculator([1, 2, 3, 4]) res = ac.select(2) expected = [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]] self.assertEqual(res, expected) def test_select_2(self): ac = ArrangementCalculator([1, 2, 3]) res = ac.select(2) expected = [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] self.assertEqual(res, expected) def test_select_3(self): ac = ArrangementCalculator([2, 3, 4]) res = ac.select(2) expected = [[2, 3], [2, 4], [3, 2], [3, 4], [4, 2], [4, 3]] self.assertEqual(res, expected) def test_select_4(self): ac = ArrangementCalculator([1, 2]) res = ac.select(2) expected = [[1, 2], [2, 1]] self.assertEqual(res, expected) def test_select_5(self): ac = ArrangementCalculator([1, 2, 3, 4]) res = ac.select(1) expected = [[1], [2], [3], [4]] self.assertEqual(res, expected) def test_select_6(self): ac = ArrangementCalculator([1, 2]) res = ac.select() expected = [[1, 2], [2, 1]] self.assertEqual(res, expected) class ArrangementCalculatorTestSelectAll(unittest.TestCase): def test_select_all_1(self): ac = ArrangementCalculator([1, 2, 3]) res = ac.select_all() expected = [[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] self.assertEqual(res, expected) def test_select_all_2(self): ac = ArrangementCalculator([1, 2, 4]) res = ac.select_all() expected = [[1], [2], [4], [1, 2], [1, 4], [2, 1], [2, 4], [4, 1], [4, 2], [1, 2, 4], [1, 4, 2], [2, 1, 4], [2, 4, 1], [4, 1, 2], [4, 2, 1]] self.assertEqual(res, expected) def test_select_all_3(self): ac = ArrangementCalculator([1, 2]) res = ac.select_all() expected = [[1], [2], [1, 2], [2, 1]] self.assertEqual(res, expected) def test_select_all_4(self): ac = ArrangementCalculator([1, 3]) res = ac.select_all() expected = [[1], [3], [1, 3], [3, 1]] self.assertEqual(res, expected) def test_select_all_5(self): ac = ArrangementCalculator([1]) res = ac.select_all() expected = [[1]] self.assertEqual(res, expected) class ArrangementCalculatorTestFactorial(unittest.TestCase): def test_factorial_1(self): res = ArrangementCalculator.factorial(4) self.assertEqual(res, 24) def test_factorial_2(self): res = ArrangementCalculator.factorial(5) self.assertEqual(res, 120) def test_factorial_3(self): res = ArrangementCalculator.factorial(3) self.assertEqual(res, 6) def test_factorial_4(self): res = ArrangementCalculator.factorial(2) self.assertEqual(res, 2) def test_factorial_5(self): res = ArrangementCalculator.factorial(1) self.assertEqual(res, 1) class ArrangementCalculatorTest(unittest.TestCase): def test_arrangementcalculator(self): res = ArrangementCalculator.count(5, 3) self.assertEqual(res, 60) res = ArrangementCalculator.count_all(4) self.assertEqual(res, 64) ac = ArrangementCalculator([1, 2, 3, 4]) res = ac.select(2) expected = [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]] self.assertEqual(res, expected) ac = ArrangementCalculator([1, 2, 3]) res = ac.select_all() expected = [[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] self.assertEqual(res, expected) res = ArrangementCalculator.factorial(4) self.assertEqual(res, 24)
import itertools class ArrangementCalculator: def __init__(self, datas): self.datas = datas @staticmethod def count(n, m=None): if m is None or n == m: return ArrangementCalculator.factorial(n) else: return ArrangementCalculator.factorial(n) // ArrangementCalculator.factorial(n - m) @staticmethod def count_all(n): total = 0 for i in range(1, n + 1): total += ArrangementCalculator.count(n, i) return total def select(self, m=None): if m is None: m = len(self.datas) result = [] for permutation in itertools.permutations(self.datas, m): result.append(list(permutation)) return result def select_all(self): result = [] for i in range(1, len(self.datas) + 1): result.extend(self.select(i)) return result @staticmethod def factorial(n): result = 1 for i in range(2, n + 1): result *= i return result
[ "import itertools" ]
""" The Arrangement class provides permutation calculations and selection operations for a given set of data elements. """
[ { "method_name": "count", "method_description": "def count(n, m=None):\n \"\"\"\n Counts the number of arrangements by choosing m items from n items (permutations).\n If m is not provided or n equals m, returns factorial(n).\n :param n: int, the total number of items.\n :param m: int, the number of items to be chosen (default=None).\n :return: int, the count of arrangements.\n >>> ArrangementCalculator.count(5, 3)\n 60\n\n \"\"\"", "test_class": "ArrangementCalculatorTestCount", "test_code": "class ArrangementCalculatorTestCount(unittest.TestCase):\n def test_count_1(self):\n res = ArrangementCalculator.count(5, 3)\n self.assertEqual(res, 60)\n\n def test_count_2(self):\n res = ArrangementCalculator.count(4, 3)\n self.assertEqual(res, 24)\n\n def test_count_3(self):\n res = ArrangementCalculator.count(6, 3)\n self.assertEqual(res, 120)\n\n def test_count_4(self):\n res = ArrangementCalculator.count(7, 3)\n self.assertEqual(res, 210)\n\n def test_count_5(self):\n res = ArrangementCalculator.count(4, 4)\n self.assertEqual(res, 24)", "solution_code": "def count(n, m=None):\n if m is None or n == m:\n return ArrangementCalculator.factorial(n)\n else:\n return ArrangementCalculator.factorial(n) // ArrangementCalculator.factorial(n - m)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "factorial" ] } }, { "method_name": "count_all", "method_description": "@staticmethod\n def count_all(n):\n \"\"\"\n Counts the total number of all possible arrangements by choosing at least 1 item and at most n items from n items.\n :param n: int, the total number of items.\n :return: int, the count of all arrangements.\n >>> ArrangementCalculator.count_all(4)\n 64\n\n \"\"\"", "test_class": "ArrangementCalculatorTestCountAll", "test_code": "class ArrangementCalculatorTestCountAll(unittest.TestCase):\n def test_count_all_1(self):\n res = ArrangementCalculator.count_all(4)\n self.assertEqual(res, 64)\n\n def test_count_all_2(self):\n res = ArrangementCalculator.count_all(1)\n self.assertEqual(res, 1)\n\n def test_count_all_3(self):\n res = ArrangementCalculator.count_all(2)\n self.assertEqual(res, 4)\n\n def test_count_all_4(self):\n res = ArrangementCalculator.count_all(3)\n self.assertEqual(res, 15)\n\n def test_count_all_5(self):\n res = ArrangementCalculator.count_all(5)\n self.assertEqual(res, 325)", "solution_code": "@staticmethod\n def count_all(n):\n total = 0\n for i in range(1, n + 1):\n total += ArrangementCalculator.count(n, i)\n return total", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "count" ] } }, { "method_name": "select", "method_description": "def select(self, m=None):\n \"\"\"\n Generates a list of arrangements by selecting m items from the internal datas.\n If m is not provided, selects all items.\n :param m: int, the number of items to be chosen (default=None).\n :return: List, a list of arrangements.\n >>> ac = ArrangementCalculator([1, 2, 3, 4])\n >>> ac.select(2)\n [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]]\n\n \"\"\"", "test_class": "ArrangementCalculatorTestSelect", "test_code": "class ArrangementCalculatorTestSelect(unittest.TestCase):\n def test_select_1(self):\n ac = ArrangementCalculator([1, 2, 3, 4])\n res = ac.select(2)\n expected = [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]]\n self.assertEqual(res, expected)\n\n def test_select_2(self):\n ac = ArrangementCalculator([1, 2, 3])\n res = ac.select(2)\n expected = [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]\n self.assertEqual(res, expected)\n\n def test_select_3(self):\n ac = ArrangementCalculator([2, 3, 4])\n res = ac.select(2)\n expected = [[2, 3], [2, 4], [3, 2], [3, 4], [4, 2], [4, 3]]\n self.assertEqual(res, expected)\n\n def test_select_4(self):\n ac = ArrangementCalculator([1, 2])\n res = ac.select(2)\n expected = [[1, 2], [2, 1]]\n self.assertEqual(res, expected)\n\n def test_select_5(self):\n ac = ArrangementCalculator([1, 2, 3, 4])\n res = ac.select(1)\n expected = [[1], [2], [3], [4]]\n self.assertEqual(res, expected)\n\n def test_select_6(self):\n ac = ArrangementCalculator([1, 2])\n res = ac.select()\n expected = [[1, 2], [2, 1]]\n self.assertEqual(res, expected)", "solution_code": "def select(self, m=None):\n if m is None:\n m = len(self.datas)\n result = []\n for permutation in itertools.permutations(self.datas, m):\n result.append(list(permutation))\n return result", "dependencies": { "Standalone": false, "lib_dependencies": [ "itertools" ], "field_dependencies": [ "self.datas" ], "method_dependencies": [] } }, { "method_name": "select_all", "method_description": "def select_all(self):\n \"\"\"\n Generates a list of all arrangements by selecting at least 1 item and at most the number of internal datas.\n :return: List, a list of all arrangements.\n >>> ac = ArrangementCalculator([1, 2, 3])\n >>> ac.select_all()\n [[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n\n \"\"\"", "test_class": "ArrangementCalculatorTestSelectAll", "test_code": "class ArrangementCalculatorTestSelectAll(unittest.TestCase):\n def test_select_all_1(self):\n ac = ArrangementCalculator([1, 2, 3])\n res = ac.select_all()\n expected = [[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 3], [1, 3, 2], [2, 1, 3],\n [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n self.assertEqual(res, expected)\n\n def test_select_all_2(self):\n ac = ArrangementCalculator([1, 2, 4])\n res = ac.select_all()\n expected = [[1], [2], [4], [1, 2], [1, 4], [2, 1], [2, 4], [4, 1], [4, 2], [1, 2, 4], [1, 4, 2], [2, 1, 4],\n [2, 4, 1], [4, 1, 2], [4, 2, 1]]\n self.assertEqual(res, expected)\n\n def test_select_all_3(self):\n ac = ArrangementCalculator([1, 2])\n res = ac.select_all()\n expected = [[1], [2], [1, 2], [2, 1]]\n self.assertEqual(res, expected)\n\n def test_select_all_4(self):\n ac = ArrangementCalculator([1, 3])\n res = ac.select_all()\n expected = [[1], [3], [1, 3], [3, 1]]\n self.assertEqual(res, expected)\n\n def test_select_all_5(self):\n ac = ArrangementCalculator([1])\n res = ac.select_all()\n expected = [[1]]\n self.assertEqual(res, expected)", "solution_code": "def select_all(self):\n result = []\n for i in range(1, len(self.datas) + 1):\n result.extend(self.select(i))\n return result", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.datas" ], "method_dependencies": [ "select" ] } }, { "method_name": "factorial", "method_description": "@staticmethod\n def factorial(n):\n \"\"\"\n Calculates the factorial of a given number.\n :param n: int, the number to calculate the factorial.\n :return: int, the factorial of the given number.\n >>> ArrangementCalculator.factorial(4)\n 24\n\n \"\"\"", "test_class": "ArrangementCalculatorTestFactorial", "test_code": "class ArrangementCalculatorTestFactorial(unittest.TestCase):\n def test_factorial_1(self):\n res = ArrangementCalculator.factorial(4)\n self.assertEqual(res, 24)\n\n def test_factorial_2(self):\n res = ArrangementCalculator.factorial(5)\n self.assertEqual(res, 120)\n\n def test_factorial_3(self):\n res = ArrangementCalculator.factorial(3)\n self.assertEqual(res, 6)\n\n def test_factorial_4(self):\n res = ArrangementCalculator.factorial(2)\n self.assertEqual(res, 2)\n\n def test_factorial_5(self):\n res = ArrangementCalculator.factorial(1)\n self.assertEqual(res, 1)", "solution_code": "@staticmethod\n def factorial(n):\n result = 1\n for i in range(2, n + 1):\n result *= i\n return result", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ]
ArrangementCalculator
[ "ArrangementCalculatorTestCount", "ArrangementCalculatorTestCountAll", "ArrangementCalculatorTestSelect", "ArrangementCalculatorTestSelectAll", "ArrangementCalculatorTestFactorial", "ArrangementCalculatorTest" ]
class ArrangementCalculator: def __init__(self, datas): """ Initializes the ArrangementCalculator object with a list of datas. :param datas: List, the data elements to be used for arrangements. """ self.datas = datas
[ "self.datas" ]
ClassEval_4
class AssessmentSystem: """ This is a class as an student assessment system, which supports add student, add course score, calculate GPA, and other functions for students and courses. """ def __init__(self): """ Initialize the students dict in assessment system. """ self.students = {} def add_student(self, name, grade, major): """ Add a new student into self.students dict :param name: str, student name :param grade: int, student grade :param major: str, student major >>> system.add_student('student 1', 3, 'SE') >>> system.students {'student 1': {'name': 'student 1', 'grade': 3, 'major': 'SE', 'courses': {}}} """ def add_course_score(self, name, course, score): """ Add score of specific course for student in self.students :param name: str, student name :param cource: str, cource name :param score: int, cource score >>> system.add_student('student 1', 3, 'SE') >>> system.add_course_score('student 1', 'math', 94) >>> system.students {'student 1': {'name': 'student 1', 'grade': 3, 'major': 'SE', 'courses': {'math': 94}}} """ def get_gpa(self, name): """ Get average grade of one student. :param name: str, student name :return: if name is in students and this students have courses grade, return average grade(float) or None otherwise >>> system.add_student('student 1', 3, 'SE') >>> system.add_course_score('student 1', 'math', 94) >>> system.add_course_score('student 1', 'Computer Network', 92) >>> system.get_gpa('student 1') 93.0 """ def get_all_students_with_fail_course(self): """ Get all students who have any score blow 60 :return: list of str ,student name >>> system.add_course_score('student 1', 'Society', 59) >>> system.get_all_students_with_fail_course() ['student 1'] """ def get_course_average(self, course): """ Get the average score of a specific course. :param course: str, course name :return: float, average scores of this course if anyone have score of this course, or None if nobody have records. """ def get_top_student(self): """ Calculate every student's gpa with get_gpa method, and find the student with highest gpa :return: str, name of student whose gpa is highest >>> system.add_student('student 1', 3, 'SE') >>> system.add_student('student 2', 2, 'SE') >>> system.add_course_score('student 1', 'Computer Network', 92) >>> system.add_course_score('student 2', 'Computer Network', 97) >>> system.get_top_student() 'student 2' """
import unittest class AssessmentSystemTestAddStudent(unittest.TestCase): def test_add_student(self): assessment_system = AssessmentSystem() assessment_system.add_student("Alice", 3, "Mathematics") self.assertEqual(assessment_system.students["Alice"], {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}) def test_add_student_2(self): assessment_system = AssessmentSystem() assessment_system.add_student("Alice", 3, "Mathematics") assessment_system.add_student("Bob", 2, "Science") self.assertEqual(assessment_system.students, {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}, 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}}}) def test_add_student_3(self): assessment_system = AssessmentSystem() assessment_system.add_student("Alice", 3, "Mathematics") assessment_system.add_student("Bob", 2, "Science") assessment_system.add_student("Charlie", 4, "Chemistry") self.assertEqual(assessment_system.students, {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}, 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}}, 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}}}) def test_add_student_4(self): assessment_system = AssessmentSystem() assessment_system.add_student("Alice", 3, "Mathematics") assessment_system.add_student("Bob", 2, "Science") assessment_system.add_student("Charlie", 4, "Chemistry") assessment_system.add_student("David", 1, "Physics") self.assertEqual(assessment_system.students, {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}, 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}}, 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}}, 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {}}}) def test_add_student_5(self): assessment_system = AssessmentSystem() assessment_system.add_student("Alice", 3, "Mathematics") assessment_system.add_student("Bob", 2, "Science") assessment_system.add_student("Charlie", 4, "Chemistry") assessment_system.add_student("David", 1, "Physics") assessment_system.add_student("Eve", 3, "Mathematics") self.assertEqual(assessment_system.students, {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}, 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}}, 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}}, 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {}}, 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {}}}) class AssessmentSystemTestAddCourseScore(unittest.TestCase): def test_add_course_score(self): assessment_system = AssessmentSystem() assessment_system.students = {"Alice": {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}} assessment_system.add_course_score("Alice", "Math", 90) self.assertEqual(assessment_system.students["Alice"]["courses"]["Math"], 90) def test_add_course_score_2(self): assessment_system = AssessmentSystem() assessment_system.students["Alice"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}} assessment_system.add_course_score("Alice", "Math", 90) self.assertEqual(assessment_system.students["Alice"]["courses"]["Math"], 90) def test_add_course_score_3(self): assessment_system = AssessmentSystem() assessment_system.students["Alice"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}} assessment_system.add_course_score("Alice", "Math", 90) assessment_system.add_course_score("Alice", "Science", 80) assessment_system.add_course_score("Alice", "Math", 95) self.assertEqual(assessment_system.students["Alice"]["courses"]["Math"], 95) self.assertEqual(assessment_system.students["Alice"]["courses"]["Science"], 80) def test_add_course_score_4(self): assessment_system = AssessmentSystem() assessment_system.students["Alice"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}} assessment_system.add_course_score("Alice", "Math", 90) assessment_system.add_course_score("Alice", "Science", 80) assessment_system.add_course_score("Alice", "Math", 95) assessment_system.add_course_score("Alice", "Science", 85) self.assertEqual(assessment_system.students["Alice"]["courses"]["Math"], 95) self.assertEqual(assessment_system.students["Alice"]["courses"]["Science"], 85) def test_add_course_score_5(self): assessment_system = AssessmentSystem() assessment_system.students["Alice"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}} assessment_system.add_course_score("Bob", "Math", 90) self.assertEqual(assessment_system.students["Alice"]["courses"], {}) class AssessmentSystemTestGetGPA(unittest.TestCase): def test_get_gpa_1(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}} self.assertEqual(assessment_system.get_gpa("Alice"), 85.0) # No such student def test_get_gpa_2(self): assessment_system = AssessmentSystem() self.assertEqual(assessment_system.get_gpa('Alice'), None) # student don't have any scores def test_get_gpa_3(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}} self.assertEqual(assessment_system.get_gpa('Alice'), None) def test_get_gpa_4(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}} self.assertEqual(assessment_system.get_gpa('Bob'), None) def test_get_gpa_5(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}} self.assertEqual(assessment_system.get_gpa('Alice'), 90.0) class AssessmentSystemTestGetAllStudentsWithFailCourse(unittest.TestCase): def test_get_all_students_with_fail_course(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 50}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}}, 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 60}}, 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}} self.assertEqual(assessment_system.get_all_students_with_fail_course(), ['Bob']) def test_get_all_students_with_fail_course_2(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 70}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}}, 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 70}}, 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}} self.assertEqual(assessment_system.get_all_students_with_fail_course(), []) def test_get_all_students_with_fail_course_3(self): assessment_system = AssessmentSystem() assessment_system.students = {} self.assertEqual(assessment_system.get_all_students_with_fail_course(), []) def test_get_all_students_with_fail_course_4(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}} self.assertEqual(assessment_system.get_all_students_with_fail_course(), []) def test_get_all_students_with_fail_course_5(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 50}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 50}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}}, 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 70}}, 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}} self.assertEqual(assessment_system.get_all_students_with_fail_course(), ['Alice', 'Bob']) class AssessmentSystemTestGetCourseAverage(unittest.TestCase): def test_get_course_average_1(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 90}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70,'Physics': 80}} } self.assertEqual(assessment_system.get_course_average("Physics"), 85.0) def test_get_course_average_2(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70,'Physics': None }} } self.assertEqual(assessment_system.get_course_average('Physics'), 85) def test_get_course_average_3(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70, 'Physics': 80}} } self.assertEqual(assessment_system.get_course_average('Computer'), None) def test_get_course_average_4(self): assessment_system = AssessmentSystem() assessment_system.students = {} self.assertEqual(assessment_system.get_course_average('Computer'), None) def test_get_course_average_5(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70, 'Physics': 80}} } self.assertEqual(assessment_system.get_course_average('Mathematics'), 90) class AssessmentSystemTestGetTopStudent(unittest.TestCase): def test_get_top_student(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}} } self.assertEqual(assessment_system.get_top_student(), "Alice") def test_get_top_student_2(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': { }}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70, 'Physics': 80}} } self.assertEqual(assessment_system.get_top_student(), "Bob") def test_get_top_student_3(self): assessment_system = AssessmentSystem() assessment_system.students = {} self.assertEqual(assessment_system.get_top_student(), None) def test_get_top_student_4(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 60}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70, 'Physics': 80}} } self.assertEqual(assessment_system.get_top_student(), "Bob") def test_get_top_student_5(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 60}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70, 'Physics': 80}}, 'David': {'name': 'David', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70, 'Physics': 80}} } self.assertEqual(assessment_system.get_top_student(), "Bob") class AssessmentSystemTestMain(unittest.TestCase): def test_main(self): system = AssessmentSystem() system.add_student('student 1', 3, 'SE') system.add_student('student 2', 2, 'SE') self.assertEqual({'student 1': {'name': 'student 1', 'grade': 3, 'major': 'SE', 'courses': {}}, 'student 2': {'name': 'student 2', 'grade': 2, 'major': 'SE', 'courses': {}}}, system.students) system.add_course_score('student 1', 'course 1', 86) system.add_course_score('student 2', 'course 1', 59) system.add_course_score('student 1', 'course 2', 78) system.add_course_score('student 2', 'course 2', 90) self.assertEqual(system.students['student 1']['courses']['course 1'], 86) self.assertEqual(system.students['student 1']['courses']['course 2'], 78) self.assertEqual(system.students['student 2']['courses']['course 1'], 59) self.assertEqual(system.students['student 2']['courses']['course 2'], 90) self.assertEqual(system.get_all_students_with_fail_course(), ['student 2']) self.assertEqual(system.get_course_average('course 1'), 72.5) self.assertEqual(system.get_course_average('course 2'), 84) self.assertEqual(system.get_gpa('student 1'), 82.0) self.assertEqual(system.get_gpa('student 2'), 74.5) self.assertEqual(system.get_top_student(), 'student 1')
class AssessmentSystem: def __init__(self): self.students = {} def add_student(self, name, grade, major): self.students[name] = {'name': name, 'grade': grade, 'major': major, 'courses': {}} def add_course_score(self, name, course, score): if name in self.students: self.students[name]['courses'][course] = score def get_gpa(self, name): if name in self.students and self.students[name]['courses']: return sum(self.students[name]['courses'].values()) / len(self.students[name]['courses']) else: return None def get_all_students_with_fail_course(self): students = [] for name, student in self.students.items(): for course, score in student['courses'].items(): if score < 60: students.append(name) break return students def get_course_average(self, course): total = 0 count = 0 for student in self.students.values(): if course in student['courses']: score = student['courses'][course] if score is not None: total += score count += 1 return total / count if count > 0 else None def get_top_student(self): top_student = None top_gpa = 0 for name, student in self.students.items(): gpa = self.get_gpa(name) if gpa is not None and gpa > top_gpa: top_gpa = gpa top_student = name return top_student
[]
""" This is a class as an student assessment system, which supports add student, add course score, calculate GPA, and other functions for students and courses. """
[ { "method_name": "add_student", "method_description": "def add_student(self, name, grade, major):\n \"\"\"\n Add a new student into self.students dict\n :param name: str, student name\n :param grade: int, student grade\n :param major: str, student major\n >>> system.add_student('student 1', 3, 'SE')\n >>> system.students\n {'student 1': {'name': 'student 1', 'grade': 3, 'major': 'SE', 'courses': {}}}\n \"\"\"", "test_class": "AssessmentSystemTestAddStudent", "test_code": "class AssessmentSystemTestAddStudent(unittest.TestCase):\n def test_add_student(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n self.assertEqual(assessment_system.students[\"Alice\"],\n {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}})\n\n def test_add_student_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n assessment_system.add_student(\"Bob\", 2, \"Science\")\n self.assertEqual(assessment_system.students,\n {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}},\n 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}}})\n\n def test_add_student_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n assessment_system.add_student(\"Bob\", 2, \"Science\")\n assessment_system.add_student(\"Charlie\", 4, \"Chemistry\")\n self.assertEqual(assessment_system.students,\n {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}},\n 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}},\n 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}}})\n\n def test_add_student_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n assessment_system.add_student(\"Bob\", 2, \"Science\")\n assessment_system.add_student(\"Charlie\", 4, \"Chemistry\")\n assessment_system.add_student(\"David\", 1, \"Physics\")\n self.assertEqual(assessment_system.students,\n {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}},\n 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}},\n 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {}}})\n\n def test_add_student_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n assessment_system.add_student(\"Bob\", 2, \"Science\")\n assessment_system.add_student(\"Charlie\", 4, \"Chemistry\")\n assessment_system.add_student(\"David\", 1, \"Physics\")\n assessment_system.add_student(\"Eve\", 3, \"Mathematics\")\n self.assertEqual(assessment_system.students,\n {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}},\n 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}},\n 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {}},\n 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {}}})", "solution_code": "def add_student(self, name, grade, major):\n self.students[name] = {'name': name, 'grade': grade, 'major': major, 'courses': {}}", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [] } }, { "method_name": "add_course_score", "method_description": "def add_course_score(self, name, course, score):\n \"\"\"\n Add score of specific course for student in self.students\n :param name: str, student name\n :param cource: str, cource name\n :param score: int, cource score\n >>> system.add_student('student 1', 3, 'SE')\n >>> system.add_course_score('student 1', 'math', 94)\n >>> system.students\n {'student 1': {'name': 'student 1', 'grade': 3, 'major': 'SE', 'courses': {'math': 94}}}\n \"\"\"", "test_class": "AssessmentSystemTestAddCourseScore", "test_code": "class AssessmentSystemTestAddCourseScore(unittest.TestCase):\n def test_add_course_score(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {\"Alice\": {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}}\n assessment_system.add_course_score(\"Alice\", \"Math\", 90)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Math\"], 90)\n\n def test_add_course_score_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.students[\"Alice\"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}\n assessment_system.add_course_score(\"Alice\", \"Math\", 90)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Math\"], 90)\n\n def test_add_course_score_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students[\"Alice\"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}\n assessment_system.add_course_score(\"Alice\", \"Math\", 90)\n assessment_system.add_course_score(\"Alice\", \"Science\", 80)\n assessment_system.add_course_score(\"Alice\", \"Math\", 95)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Math\"], 95)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Science\"], 80)\n\n def test_add_course_score_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students[\"Alice\"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}\n assessment_system.add_course_score(\"Alice\", \"Math\", 90)\n assessment_system.add_course_score(\"Alice\", \"Science\", 80)\n assessment_system.add_course_score(\"Alice\", \"Math\", 95)\n assessment_system.add_course_score(\"Alice\", \"Science\", 85)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Math\"], 95)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Science\"], 85)\n\n def test_add_course_score_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students[\"Alice\"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}\n assessment_system.add_course_score(\"Bob\", \"Math\", 90)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"], {})", "solution_code": "def add_course_score(self, name, course, score):\n if name in self.students:\n self.students[name]['courses'][course] = score", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [] } }, { "method_name": "get_gpa", "method_description": "def get_gpa(self, name):\n \"\"\"\n Get average grade of one student.\n :param name: str, student name\n :return: if name is in students and this students have courses grade, return average grade(float)\n or None otherwise\n >>> system.add_student('student 1', 3, 'SE')\n >>> system.add_course_score('student 1', 'math', 94)\n >>> system.add_course_score('student 1', 'Computer Network', 92)\n >>> system.get_gpa('student 1')\n 93.0\n\n \"\"\"", "test_class": "AssessmentSystemTestGetGPA", "test_code": "class AssessmentSystemTestGetGPA(unittest.TestCase):\n def test_get_gpa_1(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}}\n self.assertEqual(assessment_system.get_gpa(\"Alice\"), 85.0)\n\n\n # No such student\n def test_get_gpa_2(self):\n assessment_system = AssessmentSystem()\n self.assertEqual(assessment_system.get_gpa('Alice'), None)\n\n # student don't have any scores\n def test_get_gpa_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}}\n self.assertEqual(assessment_system.get_gpa('Alice'), None)\n\n def test_get_gpa_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_gpa('Bob'), None)\n\n def test_get_gpa_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_gpa('Alice'), 90.0)", "solution_code": "def get_gpa(self, name):\n if name in self.students and self.students[name]['courses']:\n return sum(self.students[name]['courses'].values()) / len(self.students[name]['courses'])\n else:\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [] } }, { "method_name": "get_all_students_with_fail_course", "method_description": "def get_all_students_with_fail_course(self):\n \"\"\"\n Get all students who have any score blow 60\n :return: list of str ,student name\n >>> system.add_course_score('student 1', 'Society', 59)\n >>> system.get_all_students_with_fail_course()\n ['student 1']\n \"\"\"", "test_class": "AssessmentSystemTestGetAllStudentsWithFailCourse", "test_code": "class AssessmentSystemTestGetAllStudentsWithFailCourse(unittest.TestCase):\n def test_get_all_students_with_fail_course(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 50}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 60}},\n 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), ['Bob'])\n\n def test_get_all_students_with_fail_course_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 70}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 70}},\n 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), [])\n\n def test_get_all_students_with_fail_course_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), [])\n\n def test_get_all_students_with_fail_course_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), [])\n\n def test_get_all_students_with_fail_course_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 50}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 50}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 70}},\n 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), ['Alice', 'Bob'])", "solution_code": "def get_all_students_with_fail_course(self):\n students = []\n for name, student in self.students.items():\n for course, score in student['courses'].items():\n if score < 60:\n students.append(name)\n break\n return students", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [] } }, { "method_name": "get_course_average", "method_description": "def get_course_average(self, course):\n \"\"\"\n Get the average score of a specific course.\n :param course: str, course name\n :return: float, average scores of this course if anyone have score of this course, or None if nobody have records.\n \"\"\"", "test_class": "AssessmentSystemTestGetCourseAverage", "test_code": "class AssessmentSystemTestGetCourseAverage(unittest.TestCase):\n\n def test_get_course_average_1(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 90}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70,'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_course_average(\"Physics\"), 85.0)\n\n def test_get_course_average_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70,'Physics': None }}\n }\n self.assertEqual(assessment_system.get_course_average('Physics'), 85)\n\n def test_get_course_average_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_course_average('Computer'), None)\n\n def test_get_course_average_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {}\n self.assertEqual(assessment_system.get_course_average('Computer'), None)\n\n def test_get_course_average_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_course_average('Mathematics'), 90)", "solution_code": "def get_course_average(self, course):\n total = 0\n count = 0\n for student in self.students.values():\n if course in student['courses']:\n score = student['courses'][course]\n if score is not None:\n total += score\n count += 1\n return total / count if count > 0 else None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [] } }, { "method_name": "get_top_student", "method_description": "def get_top_student(self):\n \"\"\"\n Calculate every student's gpa with get_gpa method, and find the student with highest gpa\n :return: str, name of student whose gpa is highest\n >>> system.add_student('student 1', 3, 'SE')\n >>> system.add_student('student 2', 2, 'SE')\n >>> system.add_course_score('student 1', 'Computer Network', 92)\n >>> system.add_course_score('student 2', 'Computer Network', 97)\n >>> system.get_top_student()\n 'student 2'\n \"\"\"", "test_class": "AssessmentSystemTestGetTopStudent", "test_code": "class AssessmentSystemTestGetTopStudent(unittest.TestCase):\n def test_get_top_student(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}}\n }\n self.assertEqual(assessment_system.get_top_student(), \"Alice\")\n\n def test_get_top_student_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': { }},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_top_student(), \"Bob\")\n\n def test_get_top_student_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {}\n self.assertEqual(assessment_system.get_top_student(), None)\n\n def test_get_top_student_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 60}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_top_student(), \"Bob\")\n\n def test_get_top_student_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 60}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}},\n 'David': {'name': 'David', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_top_student(), \"Bob\")", "solution_code": "def get_top_student(self):\n top_student = None\n top_gpa = 0\n for name, student in self.students.items():\n gpa = self.get_gpa(name)\n if gpa is not None and gpa > top_gpa:\n top_gpa = gpa\n top_student = name\n return top_student", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [ "get_gpa" ] } } ]
AssessmentSystem
[ "AssessmentSystemTestAddStudent", "AssessmentSystemTestAddCourseScore", "AssessmentSystemTestGetGPA", "AssessmentSystemTestGetAllStudentsWithFailCourse", "AssessmentSystemTestGetCourseAverage", "AssessmentSystemTestGetTopStudent", "AssessmentSystemTestMain" ]
class AssessmentSystem: def __init__(self): """ Initialize the students dict in assessment system. """ self.students = {}
[ "self.students" ]
ClassEval_5
''' # This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music. class AutomaticGuitarSimulator: def __init__(self, text) -> None: """ Initialize the score to be played :param text:str, score to be played """ self.play_text = text def interpret(self, display=False): """ Interpret the music score to be played :param display:Bool, representing whether to print the interpreted score :return: list of dict, The dict includes two fields, Chord and Tune, which are letters and numbers, respectively. If the input is empty or contains only whitespace, an empty list is returned. >>> context = AutomaticGuitarSimulator("C53231323 Em43231323 F43231323 G63231323") >>> play_list = context.interpret(display = False) [{'Chord': 'C', 'Tune': '53231323'}, {'Chord': 'Em', 'Tune': '43231323'}, {'Chord': 'F', 'Tune': '43231323'}, {'Chord': 'G', 'Tune': '63231323'}] """ def display(self, key, value): """ Print out chord and play tune with following format: Normal Guitar Playing -- Chord: %s, Play Tune: %s :param key:str, chord :param value:str, play tune :return: str >>> context = AutomaticGuitarSimulator("C53231323 Em43231323 F43231323 G63231323") >>> context.display("C", "53231323") Normal Guitar Playing -- Chord: C, Play Tune: 53231323 """ '''
import unittest class AutomaticGuitarSimulatorTestInterpret(unittest.TestCase): def test_interpret_1(self): context = AutomaticGuitarSimulator("C53231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}]) def test_interpret_2(self): context = AutomaticGuitarSimulator("F43231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'F', 'Tune': '43231323'}]) def test_interpret_3(self): context = AutomaticGuitarSimulator("Em43231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'Em', 'Tune': '43231323'}]) def test_interpret_4(self): context = AutomaticGuitarSimulator("G63231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'G', 'Tune': '63231323'}]) def test_interpret_5(self): context = AutomaticGuitarSimulator("F43231323 G63231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'F', 'Tune': '43231323'}, {'Chord': 'G', 'Tune': '63231323'}]) def test_interpret_6(self): context = AutomaticGuitarSimulator(" ") play_list = context.interpret() self.assertEqual(play_list, []) def test_interpret_7(self): context = AutomaticGuitarSimulator("ABC43231323 DEF63231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'ABC', 'Tune': '43231323'}, {'Chord': 'DEF', 'Tune': '63231323'}]) def test_interpret_8(self): context = AutomaticGuitarSimulator("C53231323") play_list = context.interpret(display=True) self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}]) def test_interpret_9(self): context = AutomaticGuitarSimulator("") play_list = context.interpret() self.assertEqual(play_list, []) class AutomaticGuitarSimulatorTestDisplay(unittest.TestCase): def test_display_1(self): context = AutomaticGuitarSimulator("C53231323 Em43231323") play_list = context.interpret() str = context.display(play_list[0]['Chord'], play_list[0]['Tune']) self.assertEqual(str, "Normal Guitar Playing -- Chord: C, Play Tune: 53231323") def test_display_2(self): context = AutomaticGuitarSimulator("C53231323 Em43231323") play_list = context.interpret() str = context.display(play_list[1]['Chord'], play_list[1]['Tune']) self.assertEqual(str, "Normal Guitar Playing -- Chord: Em, Play Tune: 43231323") def test_display_3(self): context = AutomaticGuitarSimulator("F43231323 G63231323") play_list = context.interpret() str = context.display(play_list[0]['Chord'], play_list[0]['Tune']) self.assertEqual(str, "Normal Guitar Playing -- Chord: F, Play Tune: 43231323") def test_display_4(self): context = AutomaticGuitarSimulator("F43231323 G63231323") play_list = context.interpret() str = context.display(play_list[1]['Chord'], play_list[1]['Tune']) self.assertEqual(str, "Normal Guitar Playing -- Chord: G, Play Tune: 63231323") def test_display_5(self): context = AutomaticGuitarSimulator("") str = context.display('', '') self.assertEqual(str, "Normal Guitar Playing -- Chord: , Play Tune: ") class AutomaticGuitarSimulatorTest(unittest.TestCase): def test_AutomaticGuitarSimulator(self): context = AutomaticGuitarSimulator("C53231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}]) context = AutomaticGuitarSimulator("C53231323 Em43231323") play_list = context.interpret() str = context.display(play_list[0]['Chord'], play_list[0]['Tune']) self.assertEqual(str, "Normal Guitar Playing -- Chord: C, Play Tune: 53231323")
class AutomaticGuitarSimulator: def __init__(self, text) -> None: self.play_text = text def interpret(self, display=False): if not self.play_text.strip(): return [] else: play_list = [] play_segs = self.play_text.split(" ") for play_seg in play_segs: pos = 0 for ele in play_seg: if ele.isalpha(): pos += 1 continue break play_chord = play_seg[0:pos] play_value = play_seg[pos:] play_list.append({'Chord': play_chord, 'Tune': play_value}) if display: self.display(play_chord, play_value) return play_list def display(self, key, value): return "Normal Guitar Playing -- Chord: %s, Play Tune: %s" % (key, value)
[]
""" This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music. """
[ { "method_name": "interpret", "method_description": "def interpret(self, display=False):\n \"\"\"\n Interpret the music score to be played\n :param display:Bool, representing whether to print the interpreted score\n :return: list of dict, The dict includes two fields, Chord and Tune, which are letters and numbers, respectively. If the input is empty or contains only whitespace, an empty list is returned.\n >>> context = AutomaticGuitarSimulator(\"C53231323 Em43231323 F43231323 G63231323\")\n >>> play_list = context.interpret(display = False)\n [{'Chord': 'C', 'Tune': '53231323'}, {'Chord': 'Em', 'Tune': '43231323'}, {'Chord': 'F', 'Tune': '43231323'}, {'Chord': 'G', 'Tune': '63231323'}]\n\n \"\"\"", "test_class": "AutomaticGuitarSimulatorTestInterpret", "test_code": "class AutomaticGuitarSimulatorTestInterpret(unittest.TestCase):\n def test_interpret_1(self):\n context = AutomaticGuitarSimulator(\"C53231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}])\n\n def test_interpret_2(self):\n context = AutomaticGuitarSimulator(\"F43231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'F', 'Tune': '43231323'}])\n\n def test_interpret_3(self):\n context = AutomaticGuitarSimulator(\"Em43231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'Em', 'Tune': '43231323'}])\n\n def test_interpret_4(self):\n context = AutomaticGuitarSimulator(\"G63231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'G', 'Tune': '63231323'}])\n\n def test_interpret_5(self):\n context = AutomaticGuitarSimulator(\"F43231323 G63231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'F', 'Tune': '43231323'}, {'Chord': 'G', 'Tune': '63231323'}])\n\n def test_interpret_6(self):\n context = AutomaticGuitarSimulator(\" \")\n play_list = context.interpret()\n self.assertEqual(play_list, [])\n\n def test_interpret_7(self):\n context = AutomaticGuitarSimulator(\"ABC43231323 DEF63231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'ABC', 'Tune': '43231323'}, {'Chord': 'DEF', 'Tune': '63231323'}])\n\n def test_interpret_8(self):\n context = AutomaticGuitarSimulator(\"C53231323\")\n play_list = context.interpret(display=True)\n self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}])\n\n def test_interpret_9(self):\n context = AutomaticGuitarSimulator(\"\")\n play_list = context.interpret()\n self.assertEqual(play_list, [])\n", "solution_code": "def interpret(self, display=False):\n if not self.play_text.strip():\n return []\n else:\n play_list = []\n play_segs = self.play_text.split(\" \")\n for play_seg in play_segs:\n pos = 0\n for ele in play_seg:\n if ele.isalpha():\n pos += 1\n continue\n break\n play_chord = play_seg[0:pos]\n play_value = play_seg[pos:]\n play_list.append({'Chord': play_chord, 'Tune': play_value})\n if display:\n self.display(play_chord, play_value)\n return play_list", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.play_text" ], "method_dependencies": [ "display" ] } }, { "method_name": "display", "method_description": "def display(self, key, value):\n \"\"\"\n Print out chord and play tune with following format: Normal Guitar Playing -- Chord: %s, Play Tune: %s\n :param key:str, chord\n :param value:str, play tune\n :return: str\n >>> context = AutomaticGuitarSimulator(\"C53231323 Em43231323 F43231323 G63231323\")\n >>> context.display(\"C\", \"53231323\")\n Normal Guitar Playing -- Chord: C, Play Tune: 53231323\n\n \"\"\"", "test_class": "AutomaticGuitarSimulatorTestDisplay", "test_code": "class AutomaticGuitarSimulatorTestDisplay(unittest.TestCase):\n def test_display_1(self):\n context = AutomaticGuitarSimulator(\"C53231323 Em43231323\")\n play_list = context.interpret()\n str = context.display(play_list[0]['Chord'], play_list[0]['Tune'])\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: C, Play Tune: 53231323\")\n\n def test_display_2(self):\n context = AutomaticGuitarSimulator(\"C53231323 Em43231323\")\n play_list = context.interpret()\n str = context.display(play_list[1]['Chord'], play_list[1]['Tune'])\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: Em, Play Tune: 43231323\")\n\n def test_display_3(self):\n context = AutomaticGuitarSimulator(\"F43231323 G63231323\")\n play_list = context.interpret()\n str = context.display(play_list[0]['Chord'], play_list[0]['Tune'])\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: F, Play Tune: 43231323\")\n\n def test_display_4(self):\n context = AutomaticGuitarSimulator(\"F43231323 G63231323\")\n play_list = context.interpret()\n str = context.display(play_list[1]['Chord'], play_list[1]['Tune'])\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: G, Play Tune: 63231323\")\n\n def test_display_5(self):\n context = AutomaticGuitarSimulator(\"\")\n str = context.display('', '')\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: , Play Tune: \")", "solution_code": "def display(self, key, value):\n return \"Normal Guitar Playing -- Chord: %s, Play Tune: %s\" % (key, value)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ]
AutomaticGuitarSimulator
[ "AutomaticGuitarSimulatorTestInterpret", "AutomaticGuitarSimulatorTestDisplay", "AutomaticGuitarSimulatorTest" ]
class AutomaticGuitarSimulator: def __init__(self, text) -> None: """ Initialize the score to be played :param text:str, score to be played """ self.play_text = text
[ "self.play_text" ]
ClassEval_6
class AvgPartition: """ This is a class that partitions the given list into different blocks by specifying the number of partitions, with each block having a uniformly distributed length. """ def __init__(self, lst, limit): """ Initialize the class with the given list and the number of partitions, and check if the number of partitions is greater than 0. """ self.lst = lst self.limit = limit def setNum(self): """ Calculate the size of each block and the remainder of the division. :return: the size of each block and the remainder of the division, tuple. >>> a = AvgPartition([1, 2, 3, 4], 2) >>> a.setNum() (2, 0) """ def get(self, index): """ calculate the size of each block and the remainder of the division, and calculate the corresponding start and end positions based on the index of the partition. :param index: the index of the partition,int. :return: the corresponding block, list. >>> a = AvgPartition([1, 2, 3, 4], 2) >>> a.get(0) [1, 2] """
import unittest class AvgPartitionTestSetNum(unittest.TestCase): def test_setNum(self): a = AvgPartition([1, 2, 3, 4], 2) self.assertEqual(a.setNum(), (2, 0)) def test_setNum_2(self): a = AvgPartition([1, 2, 3, 4, 5], 2) self.assertEqual(a.setNum(), (2, 1)) def test_setNum_3(self): a = AvgPartition([1, 2, 3, 4, 5], 3) self.assertEqual(a.setNum(), (1, 2)) def test_setNum_4(self): a = AvgPartition([1, 2, 3, 4, 5], 4) self.assertEqual(a.setNum(), (1, 1)) def test_setNum_5(self): a = AvgPartition([1, 2, 3, 4, 5], 5) self.assertEqual(a.setNum(), (1, 0)) class AvgPartitionTestGet(unittest.TestCase): def test_get(self): a = AvgPartition([1, 2, 3, 4], 2) self.assertEqual(a.get(0), [1, 2]) def test_get_2(self): a = AvgPartition([1, 2, 3, 4], 2) self.assertEqual(a.get(1), [3, 4]) def test_get_3(self): a = AvgPartition([1, 2, 3, 4, 5], 2) self.assertEqual(a.get(0), [1, 2, 3]) def test_get_4(self): a = AvgPartition([1, 2, 3, 4, 5], 2) self.assertEqual(a.get(1), [4, 5]) def test_get_5(self): a = AvgPartition([1, 2, 3, 4, 5], 3) self.assertEqual(a.get(0), [1, 2]) class AvgPartitionTestMain(unittest.TestCase): def test_main(self): a = AvgPartition([1, 2, 3, 4], 2) self.assertEqual(a.setNum(), (2, 0)) self.assertEqual(a.get(0), [1, 2])
class AvgPartition: def __init__(self, lst, limit): self.lst = lst self.limit = limit def setNum(self): size = len(self.lst) // self.limit remainder = len(self.lst) % self.limit return size, remainder def get(self, index): size, remainder = self.setNum() start = index * size + min(index, remainder) end = start + size if index + 1 <= remainder: end += 1 return self.lst[start:end]
[]
""" This is a class that partitions the given list into different blocks by specifying the number of partitions, with each block having a uniformly distributed length. """
[ { "method_name": "setNum", "method_description": "def setNum(self):\n \"\"\"\n Calculate the size of each block and the remainder of the division.\n :return: the size of each block and the remainder of the division, tuple.\n >>> a = AvgPartition([1, 2, 3, 4], 2)\n >>> a.setNum()\n (2, 0)\n\n \"\"\"", "test_class": "AvgPartitionTestSetNum", "test_code": "class AvgPartitionTestSetNum(unittest.TestCase):\n def test_setNum(self):\n a = AvgPartition([1, 2, 3, 4], 2)\n self.assertEqual(a.setNum(), (2, 0))\n\n def test_setNum_2(self):\n a = AvgPartition([1, 2, 3, 4, 5], 2)\n self.assertEqual(a.setNum(), (2, 1))\n\n def test_setNum_3(self):\n a = AvgPartition([1, 2, 3, 4, 5], 3)\n self.assertEqual(a.setNum(), (1, 2))\n\n def test_setNum_4(self):\n a = AvgPartition([1, 2, 3, 4, 5], 4)\n self.assertEqual(a.setNum(), (1, 1))\n\n def test_setNum_5(self):\n a = AvgPartition([1, 2, 3, 4, 5], 5)\n self.assertEqual(a.setNum(), (1, 0))", "solution_code": "def setNum(self):\n size = len(self.lst) // self.limit\n remainder = len(self.lst) % self.limit\n return size, remainder", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.limit", "self.lst" ], "method_dependencies": [] } }, { "method_name": "get", "method_description": "def get(self, index):\n \"\"\"\n calculate the size of each block and the remainder of the division, and calculate the corresponding start and end positions based on the index of the partition.\n :param index: the index of the partition,int.\n :return: the corresponding block, list.\n >>> a = AvgPartition([1, 2, 3, 4], 2)\n >>> a.get(0)\n [1, 2]\n\n \"\"\"", "test_class": "AvgPartitionTestGet", "test_code": "class AvgPartitionTestGet(unittest.TestCase):\n\n def test_get(self):\n a = AvgPartition([1, 2, 3, 4], 2)\n self.assertEqual(a.get(0), [1, 2])\n\n def test_get_2(self):\n a = AvgPartition([1, 2, 3, 4], 2)\n self.assertEqual(a.get(1), [3, 4])\n\n def test_get_3(self):\n a = AvgPartition([1, 2, 3, 4, 5], 2)\n self.assertEqual(a.get(0), [1, 2, 3])\n\n def test_get_4(self):\n a = AvgPartition([1, 2, 3, 4, 5], 2)\n self.assertEqual(a.get(1), [4, 5])\n\n def test_get_5(self):\n a = AvgPartition([1, 2, 3, 4, 5], 3)\n self.assertEqual(a.get(0), [1, 2])", "solution_code": "def get(self, index):\n size, remainder = self.setNum()\n start = index * size + min(index, remainder)\n end = start + size\n if index + 1 <= remainder:\n end += 1\n return self.lst[start:end]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.lst" ], "method_dependencies": [ "setNum" ] } } ]
AvgPartition
[ "AvgPartitionTestSetNum", "AvgPartitionTestGet", "AvgPartitionTestMain" ]
class AvgPartition: def __init__(self, lst, limit): """ Initialize the class with the given list and the number of partitions, and check if the number of partitions is greater than 0. """ self.lst = lst self.limit = limit
[ "self.limit", "self.lst" ]
ClassEval_7
class BalancedBrackets: """ This is a class that checks for bracket matching """ def __init__(self, expr): """ Initializes the class with an expression. :param expr: The expression to check for balanced brackets,str. """ self.stack = [] self.left_brackets = ["(", "{", "["] self.right_brackets = [")", "}", "]"] self.expr = expr def clear_expr(self): """ Clears the expression of all characters that are not brackets. >>> b = BalancedBrackets("a(b)c") >>> b.clear_expr() >>> b.expr '()' """ def check_balanced_brackets(self): """ Checks if the expression has balanced brackets. :return: True if the expression has balanced brackets, False otherwise. >>> b = BalancedBrackets("a(b)c") >>> b.check_balanced_brackets() True """
import unittest class BalancedBracketsTestClearExpr(unittest.TestCase): def test_clear_expr(self): b = BalancedBrackets("a(b)c") b.clear_expr() self.assertEqual(b.expr, "()") def test_clear_expr_2(self): b = BalancedBrackets("a(b){c}") b.clear_expr() self.assertEqual(b.expr, "(){}") def test_clear_expr_3(self): b = BalancedBrackets("[a](b){c}") b.clear_expr() self.assertEqual(b.expr, "[](){}") def test_clear_expr_4(self): b = BalancedBrackets("[a(b){c}") b.clear_expr() self.assertEqual(b.expr, "[(){}") def test_clear_expr_5(self): b = BalancedBrackets("a(b){c}]") b.clear_expr() self.assertEqual(b.expr, "(){}]") class BalancedBracketsTestCheckBalancedBrackets(unittest.TestCase): def test_check_balanced_brackets(self): b = BalancedBrackets("a(b)c") self.assertEqual(b.check_balanced_brackets(), True) def test_check_balanced_brackets_2(self): b = BalancedBrackets("a(b){c}") self.assertEqual(b.check_balanced_brackets(), True) def test_check_balanced_brackets_3(self): b = BalancedBrackets("[a](b){c}") self.assertEqual(b.check_balanced_brackets(), True) def test_check_balanced_brackets_4(self): b = BalancedBrackets("[a(b){c}") self.assertEqual(b.check_balanced_brackets(), False) def test_check_balanced_brackets_5(self): b = BalancedBrackets("a(b{c}]") self.assertEqual(b.check_balanced_brackets(), False) def test_check_balanced_brackets_6(self): b = BalancedBrackets("a(b{c]]") self.assertEqual(b.check_balanced_brackets(), False) def test_check_balanced_brackets_7(self): b = BalancedBrackets("[a)(b){c}") self.assertEqual(b.check_balanced_brackets(), False) class BalancedBracketsTestMain(unittest.TestCase): def test_main(self): b = BalancedBrackets("a(b)c") b.clear_expr() self.assertEqual(b.expr, "()") self.assertEqual(b.check_balanced_brackets(), True) def test_main_2(self): b = BalancedBrackets("[a(b){c}") b.clear_expr() self.assertEqual(b.expr, "[(){}") self.assertEqual(b.check_balanced_brackets(), False) def test_main_3(self): b = BalancedBrackets("a(b{c}]") b.clear_expr() self.assertEqual(b.expr, "({}]") self.assertEqual(b.check_balanced_brackets(), False)
class BalancedBrackets: def __init__(self, expr): self.stack = [] self.left_brackets = ["(", "{", "["] self.right_brackets = [")", "}", "]"] self.expr = expr def clear_expr(self): self.expr = ''.join(c for c in self.expr if (c in self.left_brackets or c in self.right_brackets)) def check_balanced_brackets(self): self.clear_expr() for Brkt in self.expr: if Brkt in self.left_brackets: self.stack.append(Brkt) else: Current_Brkt = self.stack.pop() if Current_Brkt == "(": if Brkt != ")": return False if Current_Brkt == "{": if Brkt != "}": return False if Current_Brkt == "[": if Brkt != "]": return False if self.stack: return False return True
[]
""" This is a class that checks for bracket matching """
[ { "method_name": "clear_expr", "method_description": "def clear_expr(self):\n \"\"\"\n Clears the expression of all characters that are not brackets.\n >>> b = BalancedBrackets(\"a(b)c\")\n >>> b.clear_expr()\n >>> b.expr\n '()'\n\n \"\"\"", "test_class": "BalancedBracketsTestClearExpr", "test_code": "class BalancedBracketsTestClearExpr(unittest.TestCase):\n def test_clear_expr(self):\n b = BalancedBrackets(\"a(b)c\")\n b.clear_expr()\n self.assertEqual(b.expr, \"()\")\n\n def test_clear_expr_2(self):\n b = BalancedBrackets(\"a(b){c}\")\n b.clear_expr()\n self.assertEqual(b.expr, \"(){}\")\n\n def test_clear_expr_3(self):\n b = BalancedBrackets(\"[a](b){c}\")\n b.clear_expr()\n self.assertEqual(b.expr, \"[](){}\")\n\n def test_clear_expr_4(self):\n b = BalancedBrackets(\"[a(b){c}\")\n b.clear_expr()\n self.assertEqual(b.expr, \"[(){}\")\n\n def test_clear_expr_5(self):\n b = BalancedBrackets(\"a(b){c}]\")\n b.clear_expr()\n self.assertEqual(b.expr, \"(){}]\")", "solution_code": "def clear_expr(self):\n self.expr = ''.join(c for c in self.expr if (c in self.left_brackets or c in self.right_brackets))", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.expr", "self.left_brackets", "self.right_brackets" ], "method_dependencies": [] } }, { "method_name": "check_balanced_brackets", "method_description": "def check_balanced_brackets(self):\n \"\"\"\n Checks if the expression has balanced brackets.\n :return: True if the expression has balanced brackets, False otherwise.\n >>> b = BalancedBrackets(\"a(b)c\")\n >>> b.check_balanced_brackets()\n True\n\n \"\"\"", "test_class": "BalancedBracketsTestCheckBalancedBrackets", "test_code": "class BalancedBracketsTestCheckBalancedBrackets(unittest.TestCase):\n def test_check_balanced_brackets(self):\n b = BalancedBrackets(\"a(b)c\")\n self.assertEqual(b.check_balanced_brackets(), True)\n\n def test_check_balanced_brackets_2(self):\n b = BalancedBrackets(\"a(b){c}\")\n self.assertEqual(b.check_balanced_brackets(), True)\n\n def test_check_balanced_brackets_3(self):\n b = BalancedBrackets(\"[a](b){c}\")\n self.assertEqual(b.check_balanced_brackets(), True)\n\n def test_check_balanced_brackets_4(self):\n b = BalancedBrackets(\"[a(b){c}\")\n self.assertEqual(b.check_balanced_brackets(), False)\n\n def test_check_balanced_brackets_5(self):\n b = BalancedBrackets(\"a(b{c}]\")\n self.assertEqual(b.check_balanced_brackets(), False)\n\n def test_check_balanced_brackets_6(self):\n b = BalancedBrackets(\"a(b{c]]\")\n self.assertEqual(b.check_balanced_brackets(), False)\n\n def test_check_balanced_brackets_7(self):\n b = BalancedBrackets(\"[a)(b){c}\")\n self.assertEqual(b.check_balanced_brackets(), False)", "solution_code": "def check_balanced_brackets(self):\n self.clear_expr()\n for Brkt in self.expr:\n if Brkt in self.left_brackets:\n self.stack.append(Brkt)\n else:\n Current_Brkt = self.stack.pop()\n if Current_Brkt == \"(\":\n if Brkt != \")\":\n return False\n if Current_Brkt == \"{\":\n if Brkt != \"}\":\n return False\n if Current_Brkt == \"[\":\n if Brkt != \"]\":\n return False\n if self.stack:\n return False\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.expr", "self.left_brackets", "self.stack" ], "method_dependencies": [ "clear_expr" ] } } ]
BalancedBrackets
[ "BalancedBracketsTestClearExpr", "BalancedBracketsTestCheckBalancedBrackets", "BalancedBracketsTestMain" ]
class BalancedBrackets: def __init__(self, expr): """ Initializes the class with an expression. :param expr: The expression to check for balanced brackets,str. """ self.stack = [] self.left_brackets = ["(", "{", "["] self.right_brackets = [")", "}", "]"] self.expr = expr
[ "self.expr", "self.left_brackets", "self.right_brackets", "self.stack" ]
ClassEval_8
class BankAccount: """ This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money. """ def __init__(self, balance=0): """ Initializes a bank account object with an attribute balance, default value is 0. """ self.balance = balance def deposit(self, amount): """ Deposits a certain amount into the account, increasing the account balance, return the current account balance. If amount is negative, raise a ValueError("Invalid amount"). :param amount: int """ def withdraw(self, amount): """ Withdraws a certain amount from the account, decreasing the account balance, return the current account balance. If amount is negative, raise a ValueError("Invalid amount"). If the withdrawal amount is greater than the account balance, raise a ValueError("Insufficient balance."). :param amount: int """ def view_balance(self): """ Return the account balance. """ def transfer(self, other_account, amount): """ Transfers a certain amount from the current account to another account. :param other_account: BankAccount :param amount: int >>> account1 = BankAccount() >>> account2 = BankAccount() >>> account1.deposit(1000) >>> account1.transfer(account2, 300) account1.balance = 700 account2.balance = 300 """
import unittest class BankAccountTestDeposit(unittest.TestCase): def test_deposit(self): account1 = BankAccount() ret = account1.deposit(1000) self.assertEqual(ret, 1000) def test_deposit_2(self): account1 = BankAccount() account1.deposit(1000) ret = account1.deposit(2000) self.assertEqual(ret, 3000) def test_deposit_3(self): account1 = BankAccount() with self.assertRaises(ValueError) as context: account1.deposit(-1000) self.assertEqual(str(context.exception), "Invalid amount") def test_deposit_4(self): account1 = BankAccount() ret = account1.deposit(0) self.assertEqual(ret, 0) def test_deposit_5(self): account1 = BankAccount() account1.deposit(1000) ret = account1.deposit(1000) self.assertEqual(ret, 2000) class BankAccountTestWithdraw(unittest.TestCase): def test_withdraw(self): account1 = BankAccount() account1.balance = 1000 ret = account1.withdraw(200) self.assertEqual(ret, 800) def test_withdraw_2(self): account1 = BankAccount() account1.balance = 500 with self.assertRaises(ValueError) as context: account1.withdraw(1000) self.assertEqual(str(context.exception), "Insufficient balance.") def test_withdraw_3(self): account1 = BankAccount() with self.assertRaises(ValueError) as context: account1.withdraw(-1000) self.assertEqual(str(context.exception), "Invalid amount") def test_withdraw_4(self): account1 = BankAccount() account1.balance = 1000 ret = account1.withdraw(500) self.assertEqual(ret, 500) def test_withdraw_5(self): account1 = BankAccount() account1.balance = 1000 ret = account1.withdraw(1000) self.assertEqual(ret, 0) class BankAccountTestViewBalance(unittest.TestCase): def test_view_balance(self): account1 = BankAccount() self.assertEqual(account1.view_balance(), 0) def test_view_balance_2(self): account1 = BankAccount() account1.balance = 1000 self.assertEqual(account1.view_balance(), 1000) def test_view_balance_3(self): account1 = BankAccount() account1.balance = 500 self.assertEqual(account1.view_balance(), 500) def test_view_balance_4(self): account1 = BankAccount() account1.balance = 1500 self.assertEqual(account1.view_balance(), 1500) def test_view_balance_5(self): account1 = BankAccount() account1.balance = 2000 self.assertEqual(account1.view_balance(), 2000) class BankAccountTestTransfer(unittest.TestCase): def test_transfer(self): account1 = BankAccount() account2 = BankAccount() account1.balance = 800 account2.balance = 1000 account1.transfer(account2, 300) self.assertEqual(account1.view_balance(), 500) self.assertEqual(account2.view_balance(), 1300) def test_transfer_2(self): account1 = BankAccount() account2 = BankAccount() account1.balance = 500 with self.assertRaises(ValueError) as context: account1.transfer(account2, 600) self.assertEqual(str(context.exception), "Insufficient balance.") def test_transfer_3(self): account1 = BankAccount() account2 = BankAccount() account1.balance = 500 account2.balance = 1000 with self.assertRaises(ValueError) as context: account1.transfer(account2, -600) self.assertEqual(str(context.exception), "Invalid amount") def test_transfer_4(self): account1 = BankAccount() account2 = BankAccount() account1.balance = 500 account2.balance = 1000 account1.transfer(account2, 500) self.assertEqual(account1.view_balance(), 0) self.assertEqual(account2.view_balance(), 1500) def test_transfer_5(self): account1 = BankAccount() account2 = BankAccount() account1.balance = 500 account2.balance = 1000 account1.transfer(account2, 200) self.assertEqual(account1.view_balance(), 300) self.assertEqual(account2.view_balance(), 1200) class BankAccountTest(unittest.TestCase): def test_all(self): account1 = BankAccount() account2 = BankAccount() account1.deposit(1000) account1.withdraw(200) account1.transfer(account2, 300) self.assertEqual(account1.view_balance(), 500) self.assertEqual(account2.view_balance(), 300) def test_all2(self): account1 = BankAccount() account2 = BankAccount() account1.deposit(1000) account1.withdraw(200) account1.transfer(account2, 300) account2.withdraw(100) self.assertEqual(account1.view_balance(), 500) self.assertEqual(account2.view_balance(), 200)
class BankAccount: def __init__(self, balance=0): self.balance = balance def deposit(self, amount): if amount < 0: raise ValueError("Invalid amount") self.balance += amount return self.balance def withdraw(self, amount): if amount < 0: raise ValueError("Invalid amount") if amount > self.balance: raise ValueError("Insufficient balance.") self.balance -= amount return self.balance def view_balance(self): return self.balance def transfer(self, other_account, amount): self.withdraw(amount) other_account.deposit(amount)
[]
""" This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money. """
[ { "method_name": "deposit", "method_description": "def deposit(self, amount):\n \"\"\"\n Deposits a certain amount into the account, increasing the account balance, return the current account balance.\n If amount is negative, raise a ValueError(\"Invalid amount\").\n :param amount: int\n \"\"\"", "test_class": "BankAccountTestDeposit", "test_code": "class BankAccountTestDeposit(unittest.TestCase):\n\n def test_deposit(self):\n account1 = BankAccount()\n ret = account1.deposit(1000)\n self.assertEqual(ret, 1000)\n\n def test_deposit_2(self):\n account1 = BankAccount()\n account1.deposit(1000)\n ret = account1.deposit(2000)\n self.assertEqual(ret, 3000)\n\n\n def test_deposit_3(self):\n account1 = BankAccount()\n with self.assertRaises(ValueError) as context:\n account1.deposit(-1000)\n self.assertEqual(str(context.exception), \"Invalid amount\")\n\n def test_deposit_4(self):\n account1 = BankAccount()\n ret = account1.deposit(0)\n self.assertEqual(ret, 0)\n\n def test_deposit_5(self):\n account1 = BankAccount()\n account1.deposit(1000)\n ret = account1.deposit(1000)\n self.assertEqual(ret, 2000)", "solution_code": "def deposit(self, amount):\n if amount < 0:\n raise ValueError(\"Invalid amount\")\n self.balance += amount\n return self.balance", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.balance" ], "method_dependencies": [] } }, { "method_name": "withdraw", "method_description": "def withdraw(self, amount):\n \"\"\"\n Withdraws a certain amount from the account, decreasing the account balance, return the current account balance.\n If amount is negative, raise a ValueError(\"Invalid amount\").\n If the withdrawal amount is greater than the account balance, raise a ValueError(\"Insufficient balance.\").\n :param amount: int\n \"\"\"", "test_class": "BankAccountTestWithdraw", "test_code": "class BankAccountTestWithdraw(unittest.TestCase):\n\n def test_withdraw(self):\n account1 = BankAccount()\n account1.balance = 1000\n ret = account1.withdraw(200)\n self.assertEqual(ret, 800)\n\n def test_withdraw_2(self):\n account1 = BankAccount()\n account1.balance = 500\n with self.assertRaises(ValueError) as context:\n account1.withdraw(1000)\n self.assertEqual(str(context.exception), \"Insufficient balance.\")\n\n def test_withdraw_3(self):\n account1 = BankAccount()\n with self.assertRaises(ValueError) as context:\n account1.withdraw(-1000)\n self.assertEqual(str(context.exception), \"Invalid amount\")\n\n def test_withdraw_4(self):\n account1 = BankAccount()\n account1.balance = 1000\n ret = account1.withdraw(500)\n self.assertEqual(ret, 500)\n\n def test_withdraw_5(self):\n account1 = BankAccount()\n account1.balance = 1000\n ret = account1.withdraw(1000)\n self.assertEqual(ret, 0)", "solution_code": "def withdraw(self, amount):\n if amount < 0:\n raise ValueError(\"Invalid amount\")\n if amount > self.balance:\n raise ValueError(\"Insufficient balance.\")\n self.balance -= amount\n return self.balance", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.balance" ], "method_dependencies": [] } }, { "method_name": "view_balance", "method_description": "def view_balance(self):\n \"\"\"\n Return the account balance.\n \"\"\"", "test_class": "BankAccountTestViewBalance", "test_code": "class BankAccountTestViewBalance(unittest.TestCase):\n\n def test_view_balance(self):\n account1 = BankAccount()\n self.assertEqual(account1.view_balance(), 0)\n\n def test_view_balance_2(self):\n account1 = BankAccount()\n account1.balance = 1000\n self.assertEqual(account1.view_balance(), 1000)\n\n def test_view_balance_3(self):\n account1 = BankAccount()\n account1.balance = 500\n self.assertEqual(account1.view_balance(), 500)\n\n def test_view_balance_4(self):\n account1 = BankAccount()\n account1.balance = 1500\n self.assertEqual(account1.view_balance(), 1500)\n\n def test_view_balance_5(self):\n account1 = BankAccount()\n account1.balance = 2000\n self.assertEqual(account1.view_balance(), 2000)", "solution_code": "def view_balance(self):\n return self.balance", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.balance" ], "method_dependencies": [] } }, { "method_name": "transfer", "method_description": "def transfer(self, other_account, amount):\n \"\"\"\n Transfers a certain amount from the current account to another account.\n :param other_account: BankAccount\n :param amount: int\n >>> account1 = BankAccount()\n >>> account2 = BankAccount()\n >>> account1.deposit(1000)\n >>> account1.transfer(account2, 300)\n account1.balance = 700 account2.balance = 300\n \"\"\"", "test_class": "BankAccountTestTransfer", "test_code": "class BankAccountTestTransfer(unittest.TestCase):\n\n def test_transfer(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 800\n account2.balance = 1000\n account1.transfer(account2, 300)\n self.assertEqual(account1.view_balance(), 500)\n self.assertEqual(account2.view_balance(), 1300)\n\n def test_transfer_2(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 500\n with self.assertRaises(ValueError) as context:\n account1.transfer(account2, 600)\n self.assertEqual(str(context.exception), \"Insufficient balance.\")\n\n def test_transfer_3(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 500\n account2.balance = 1000\n with self.assertRaises(ValueError) as context:\n account1.transfer(account2, -600)\n self.assertEqual(str(context.exception), \"Invalid amount\")\n\n def test_transfer_4(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 500\n account2.balance = 1000\n account1.transfer(account2, 500)\n self.assertEqual(account1.view_balance(), 0)\n self.assertEqual(account2.view_balance(), 1500)\n\n def test_transfer_5(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 500\n account2.balance = 1000\n account1.transfer(account2, 200)\n self.assertEqual(account1.view_balance(), 300)\n self.assertEqual(account2.view_balance(), 1200)", "solution_code": "def transfer(self, other_account, amount):\n self.withdraw(amount)\n other_account.deposit(amount)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "deposit", "withdraw" ] } } ]
BankAccount
[ "BankAccountTestDeposit", "BankAccountTestWithdraw", "BankAccountTestViewBalance", "BankAccountTestTransfer", "BankAccountTest" ]
class BankAccount: def __init__(self, balance=0): """ Initializes a bank account object with an attribute balance, default value is 0. """ self.balance = balance
[ "self.balance" ]
ClassEval_9
class BigNumCalculator: """ This is a class that implements big number calculations, including adding, subtracting and multiplying. """ @staticmethod def add(num1, num2): """ Adds two big numbers. :param num1: The first number to add,str. :param num2: The second number to add,str. :return: The sum of the two numbers,str. >>> bigNum = BigNumCalculator() >>> bigNum.add("12345678901234567890", "98765432109876543210") '111111111011111111100' """ @staticmethod def subtract(num1, num2): """ Subtracts two big numbers. :param num1: The first number to subtract,str. :param num2: The second number to subtract,str. :return: The difference of the two numbers,str. >>> bigNum = BigNumCalculator() >>> bigNum.subtract("12345678901234567890", "98765432109876543210") '-86419753208641975320' """ @staticmethod def multiply(num1, num2): """ Multiplies two big numbers. :param num1: The first number to multiply,str. :param num2: The second number to multiply,str. :return: The product of the two numbers,str. >>> bigNum = BigNumCalculator() >>> bigNum.multiply("12345678901234567890", "98765432109876543210") '1219326311370217952237463801111263526900' """
import unittest class BigNumCalculatorTestAdd(unittest.TestCase): def test_add(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.add("12345678901234567890", "98765432109876543210"), "111111111011111111100") def test_add_2(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.add("123456789012345678922", "98765432109876543210"), "222222221122222222132") def test_add_3(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.add("123456789012345678934", "98765432109876543210"), "222222221122222222144") def test_add_4(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.add("123456789012345678946", "98765432109876543210"), "222222221122222222156") def test_add_5(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.add("123456789012345678958", "98765432109876543210"), "222222221122222222168") class BigNumCalculatorTestSubtract(unittest.TestCase): def test_subtract(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.subtract("12345678901234567890", "98765432109876543210"), "-86419753208641975320") def test_subtract_2(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.subtract("123456789012345678922", "98765432109876543210"), "24691356902469135712") def test_subtract_3(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.subtract("123456789012345678934", "98765432109876543"), "123358023580235802391") def test_subtract_4(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.subtract("12345678901234567", "98765432109876543210"), "-98753086430975308643") def test_subtract_5(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.subtract("923456789", "187654321"), "735802468") class BigNumCalculatorTestMultiply(unittest.TestCase): def test_multiply(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.multiply("12345678901234567890", "98765432109876543210"), "1219326311370217952237463801111263526900") def test_multiply_2(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.multiply("123456789012345678922", "98765432109876543210"), "12193263113702179524547477517529919219620") def test_multiply_3(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.multiply("123456789012345678934", "98765432109876543"), "12193263113702179499806737010255845162") def test_multiply_4(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.multiply("12345678901234567", "98765432109876543210"), "1219326311370217864336229223321140070") def test_multiply_5(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.multiply("923456789", "187654321"), "173290656712635269") def test_multiply_6(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.multiply("000000001", "000000001"), "1") class BigNumCalculatorTestMain(unittest.TestCase): def test_main(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.add("12345678901234567890", "98765432109876543210"), "111111111011111111100") self.assertEqual(bigNum.subtract("12345678901234567890", "98765432109876543210"), "-86419753208641975320") self.assertEqual(bigNum.multiply("12345678901234567890", "98765432109876543210"), "1219326311370217952237463801111263526900")
class BigNumCalculator: @staticmethod def add(num1, num2): max_length = max(len(num1), len(num2)) num1 = num1.zfill(max_length) num2 = num2.zfill(max_length) carry = 0 result = [] for i in range(max_length - 1, -1, -1): digit_sum = int(num1[i]) + int(num2[i]) + carry carry = digit_sum // 10 digit = digit_sum % 10 result.insert(0, str(digit)) if carry > 0: result.insert(0, str(carry)) return ''.join(result) @staticmethod def subtract(num1, num2): if len(num1) < len(num2): num1, num2 = num2, num1 negative = True elif len(num1) > len(num2): negative = False else: if num1 < num2: num1, num2 = num2, num1 negative = True else: negative = False max_length = max(len(num1), len(num2)) num1 = num1.zfill(max_length) num2 = num2.zfill(max_length) borrow = 0 result = [] for i in range(max_length - 1, -1, -1): digit_diff = int(num1[i]) - int(num2[i]) - borrow if digit_diff < 0: digit_diff += 10 borrow = 1 else: borrow = 0 result.insert(0, str(digit_diff)) while len(result) > 1 and result[0] == '0': result.pop(0) if negative: result.insert(0, '-') return ''.join(result) @staticmethod def multiply(num1, num2): len1, len2 = len(num1), len(num2) result = [0] * (len1 + len2) for i in range(len1 - 1, -1, -1): for j in range(len2 - 1, -1, -1): mul = int(num1[i]) * int(num2[j]) p1, p2 = i + j, i + j + 1 total = mul + result[p2] result[p1] += total // 10 result[p2] = total % 10 start = 0 while start < len(result) - 1 and result[start] == 0: start += 1 return ''.join(map(str, result[start:]))
[]
""" This is a class that implements big number calculations, including adding, subtracting and multiplying. """
[ { "method_name": "add", "method_description": "def add(num1, num2):\n \"\"\"\n Adds two big numbers.\n :param num1: The first number to add,str.\n :param num2: The second number to add,str.\n :return: The sum of the two numbers,str.\n >>> bigNum = BigNumCalculator()\n >>> bigNum.add(\"12345678901234567890\", \"98765432109876543210\")\n '111111111011111111100'\n\n \"\"\"", "test_class": "BigNumCalculatorTestAdd", "test_code": "class BigNumCalculatorTestAdd(unittest.TestCase):\n def test_add(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"12345678901234567890\", \"98765432109876543210\"), \"111111111011111111100\")\n\n def test_add_2(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"123456789012345678922\", \"98765432109876543210\"), \"222222221122222222132\")\n\n def test_add_3(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"123456789012345678934\", \"98765432109876543210\"), \"222222221122222222144\")\n\n def test_add_4(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"123456789012345678946\", \"98765432109876543210\"), \"222222221122222222156\")\n\n def test_add_5(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"123456789012345678958\", \"98765432109876543210\"), \"222222221122222222168\")", "solution_code": "def add(num1, num2):\n max_length = max(len(num1), len(num2))\n num1 = num1.zfill(max_length)\n num2 = num2.zfill(max_length)\n\n carry = 0\n result = []\n for i in range(max_length - 1, -1, -1):\n digit_sum = int(num1[i]) + int(num2[i]) + carry\n carry = digit_sum // 10\n digit = digit_sum % 10\n result.insert(0, str(digit))\n\n if carry > 0:\n result.insert(0, str(carry))\n\n return ''.join(result)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "subtract", "method_description": "@staticmethod\n def subtract(num1, num2):\n \"\"\"\n Subtracts two big numbers.\n :param num1: The first number to subtract,str.\n :param num2: The second number to subtract,str.\n :return: The difference of the two numbers,str.\n >>> bigNum = BigNumCalculator()\n >>> bigNum.subtract(\"12345678901234567890\", \"98765432109876543210\")\n '-86419753208641975320'\n\n \"\"\"", "test_class": "BigNumCalculatorTestSubtract", "test_code": "class BigNumCalculatorTestSubtract(unittest.TestCase):\n def test_subtract(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"12345678901234567890\", \"98765432109876543210\"), \"-86419753208641975320\")\n\n def test_subtract_2(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"123456789012345678922\", \"98765432109876543210\"), \"24691356902469135712\")\n\n def test_subtract_3(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"123456789012345678934\", \"98765432109876543\"), \"123358023580235802391\")\n\n def test_subtract_4(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"12345678901234567\", \"98765432109876543210\"), \"-98753086430975308643\")\n\n def test_subtract_5(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"923456789\", \"187654321\"), \"735802468\")", "solution_code": "@staticmethod\n def subtract(num1, num2):\n\n if len(num1) < len(num2):\n num1, num2 = num2, num1\n negative = True\n elif len(num1) > len(num2):\n negative = False\n else:\n if num1 < num2:\n num1, num2 = num2, num1\n negative = True\n else:\n negative = False\n\n max_length = max(len(num1), len(num2))\n num1 = num1.zfill(max_length)\n num2 = num2.zfill(max_length)\n\n borrow = 0\n result = []\n for i in range(max_length - 1, -1, -1):\n digit_diff = int(num1[i]) - int(num2[i]) - borrow\n\n if digit_diff < 0:\n digit_diff += 10\n borrow = 1\n else:\n borrow = 0\n\n result.insert(0, str(digit_diff))\n\n while len(result) > 1 and result[0] == '0':\n result.pop(0)\n\n if negative:\n result.insert(0, '-')\n\n return ''.join(result)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "multiply", "method_description": "@staticmethod\n def multiply(num1, num2):\n \"\"\"\n Multiplies two big numbers.\n :param num1: The first number to multiply,str.\n :param num2: The second number to multiply,str.\n :return: The product of the two numbers,str.\n >>> bigNum = BigNumCalculator()\n >>> bigNum.multiply(\"12345678901234567890\", \"98765432109876543210\")\n '1219326311370217952237463801111263526900'\n\n \"\"\"", "test_class": "BigNumCalculatorTestMultiply", "test_code": "class BigNumCalculatorTestMultiply(unittest.TestCase):\n def test_multiply(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"12345678901234567890\", \"98765432109876543210\"), \"1219326311370217952237463801111263526900\")\n\n def test_multiply_2(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"123456789012345678922\", \"98765432109876543210\"), \"12193263113702179524547477517529919219620\")\n\n def test_multiply_3(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"123456789012345678934\", \"98765432109876543\"), \"12193263113702179499806737010255845162\")\n\n def test_multiply_4(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"12345678901234567\", \"98765432109876543210\"), \"1219326311370217864336229223321140070\")\n\n def test_multiply_5(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"923456789\", \"187654321\"), \"173290656712635269\")\n\n def test_multiply_6(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"000000001\", \"000000001\"), \"1\")", "solution_code": "@staticmethod\n def multiply(num1, num2):\n len1, len2 = len(num1), len(num2)\n result = [0] * (len1 + len2)\n\n for i in range(len1 - 1, -1, -1):\n for j in range(len2 - 1, -1, -1):\n mul = int(num1[i]) * int(num2[j])\n p1, p2 = i + j, i + j + 1\n total = mul + result[p2]\n\n result[p1] += total // 10\n result[p2] = total % 10\n\n start = 0\n while start < len(result) - 1 and result[start] == 0:\n start += 1\n\n return ''.join(map(str, result[start:]))", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ]
BigNumCalculator
[ "BigNumCalculatorTestAdd", "BigNumCalculatorTestSubtract", "BigNumCalculatorTestMultiply", "BigNumCalculatorTestMain" ]
class BigNumCalculator:
[]

Dataset Card for FudanSELab ClassEval

Dataset Summary

We manually build ClassEval of 100 class-level Python coding tasks, consists of 100 classes and 412 methods, and average 33.1 test cases per class.

For 100 class-level tasks, diversity is maintained by encompassing these tasks over a wide spectrum of topics, including Management Systems, Data Formatting, Mathematical Operations, Game Development, File Handing, Database Operations and Natural Language Processing.

For 412 methods, they have been constructed with diverse dependencies, including (i) Library Dependency, where the methods rely on specific external libraries; (ii) Field Dependency, in which the methods are contingent on class instance variables, or fields; (iii) Method Dependency, where the methods are dependent on other methods within the same class; and (iv) Standalone, wherein the methods operate independently without reliance on fields, other methods, or external libraries.

Languages

The programming language is Python. The natural language used in the comments and docstrings is English.

Dataset Structure

from datasets import load_dataset
dataset = load_dataset("FudanSELab/ClassEval")

DatasetDict({
    test: Dataset({
        features: ['task_id', 'skeleton', 'test', 'solution_code', 'import_statement', 'class_description', 'methods_info', 
'class_name', 'test_classes', 'class_constructor', 'fields'],
        num_rows: 100
    })
})

Data Fields

The specific data fields for each task are delineated as follows:

  • task_id: the unique identifier for each task.

  • skeleton: the class skeleton, including all input descriptions in our class-level coding tasks.

  • test: all test cases for the whole class.

  • solution_code: the ground-truth class-level code for each task.

More fine-grained class-level information from the class skeleton, including:

  • import_statement: the import statements for each task.

  • class_name: the name of the class.

  • class_description: a concise description of the purpose and functionality of the class.

  • class_constructor: the whole constructor of the class.

  • fields: the fields defined in the class_constructor.

Detailed information for each method in the "methods_info" field, including:

  • method_name: the method signature.

  • method_input: the method contract design, including all input descriptions in the method.

  • test_code: the test cases for the method.

  • solution_code: the ground-truth method-level code.

  • dependencies: the dependency information of the method.

Data Splits

The dataset only consists of a test split with 100 samples.

Dataset Creation

Source Data

Manually-crafted

Additional Information

Licensing Information

This repository is under MIT license. But the data is distributes through CC BY-NC 4.0 license.

Citation Information

@misc{du2023classeval,
      title={ClassEval: A Manually-Crafted Benchmark for Evaluating LLMs on Class-level Code Generation}, 
      author={Xueying Du and Mingwei Liu and Kaixin Wang and Hanlin Wang and Junwei Liu and Yixuan Chen and Jiayi Feng and Chaofeng Sha and Xin Peng and Yiling Lou},
      year={2023},
      eprint={2308.01861},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}

Contributions

Xueying Du [email protected]

Mingwei Liu [email protected]

Kaixin Wang [email protected]

Hanlin Wang [email protected]

Junwei Liu [email protected]

Yixuan Chen [email protected]

Jiayi Feng [email protected]

Chaofeng Sha [email protected]

Xin Peng [email protected]

Yiling Lou [email protected]

Downloads last month
145
Edit dataset card