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:
| [] |
ClassEval_10 | class BinaryDataProcessor:
"""
This is a class used to process binary data, which includes functions such as clearing non 0 or 1 characters, counting binary string information, and converting to corresponding strings based on different encoding methods.
"""
def __init__(self, binary_string):
"""
Initialize the class with a binary string and clean it by removing all non 0 or 1 characters.
"""
self.binary_string = binary_string
self.clean_non_binary_chars()
def clean_non_binary_chars(self):
"""
Clean the binary string by removing all non 0 or 1 characters.
>>> bdp = BinaryDataProcessor("01101000daf3e4r01100101011011000110110001101111")
>>> bdp.clean_non_binary_chars()
>>> bdp.binary_string
'0110100001100101011011000110110001101111'
"""
def calculate_binary_info(self):
"""
Calculate the binary string information, including the percentage of 0 and 1, and the total length of the binary string.
>>> bdp = BinaryDataProcessor("0110100001100101011011000110110001101111")
>>> bdp.calculate_binary_info()
{'Zeroes': 0.475, 'Ones': 0.525, 'Bit length': 40}
"""
def convert_to_ascii(self):
"""
Convert the binary string to ascii string.
>>> bdp = BinaryDataProcessor("0110100001100101011011000110110001101111")
>>> bdp.convert_to_ascii()
'hello'
"""
def convert_to_utf8(self):
"""
Convert the binary string to utf-8 string.
>>> bdp = BinaryDataProcessor("0110100001100101011011000110110001101111")
>>> bdp.convert_to_utf8()
'hello'
""" | import unittest
class BinaryDataProcessorTestCleanNonBinaryChars(unittest.TestCase):
def test_clean_non_binary_chars(self):
bdp = BinaryDataProcessor("01101000daf3e4r01100101011011000110110001101111")
self.assertEqual(bdp.binary_string, "0110100001100101011011000110110001101111")
def test_clean_non_binary_chars_2(self):
bdp = BinaryDataProcessor("01101000daf3e4r01100101011011addf0110001d1111")
self.assertEqual(bdp.binary_string, "011010000110010101101101100011111")
def test_clean_non_binary_chars_3(self):
bdp = BinaryDataProcessor("0sd1000daf3e4r01100101011011addf0110001d1111")
self.assertEqual(bdp.binary_string, "010000110010101101101100011111")
def test_clean_non_binary_chars_4(self):
bdp = BinaryDataProcessor("sdsdf")
self.assertEqual(bdp.binary_string, "")
def test_clean_non_binary_chars_5(self):
bdp = BinaryDataProcessor("0")
self.assertEqual(bdp.binary_string, "0")
class BinaryDataProcessorTestCalculateBinaryInfo(unittest.TestCase):
def test_calculate_binary_info(self):
bdp = BinaryDataProcessor("0110100001100101011011000110110001101111")
self.assertEqual(bdp.calculate_binary_info(), {'Zeroes': 0.475, 'Ones': 0.525, 'Bit length': 40})
def test_calculate_binary_info_2(self):
bdp = BinaryDataProcessor("0110100001100101011010011111")
self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 28, 'Ones': 0.5357142857142857, 'Zeroes': 0.4642857142857143})
def test_calculate_binary_info_3(self):
bdp = BinaryDataProcessor("01101001111100101011010011111")
self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 29, 'Ones': 0.6206896551724138, 'Zeroes': 0.3793103448275862})
def test_calculate_binary_info_4(self):
bdp = BinaryDataProcessor("011010011111001")
self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 15, 'Ones': 0.6, 'Zeroes': 0.4})
def test_calculate_binary_info_5(self):
bdp = BinaryDataProcessor("0110100111110010")
self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 16, 'Ones': 0.5625, 'Zeroes': 0.4375})
class BinaryDataProcessorTestConvertToAscii(unittest.TestCase):
def test_convert_to_ascii(self):
bdp = BinaryDataProcessor("0110100001100101011011000110110001101111")
self.assertEqual(bdp.convert_to_ascii(), "hello")
def test_convert_to_ascii_2(self):
bdp = BinaryDataProcessor("0110100000100101011011000110110001101111")
self.assertEqual(bdp.convert_to_ascii(), "h%llo")
def test_convert_to_ascii_3(self):
bdp = BinaryDataProcessor("01101000011011010110001001101111")
self.assertEqual(bdp.convert_to_ascii(), "hmbo")
def test_convert_to_ascii_4(self):
bdp = BinaryDataProcessor("01101000011001010110001001101111")
self.assertEqual(bdp.convert_to_ascii(), "hebo")
def test_convert_to_ascii_5(self):
bdp = BinaryDataProcessor("0110100001100101011011000110110001101111")
self.assertEqual(bdp.convert_to_ascii(), "hello")
class BinaryDataProcessorTestConvertToUtf8(unittest.TestCase):
def test_convert_to_utf8(self):
bdp = BinaryDataProcessor("0110100001100101011011000110110001101111")
self.assertEqual(bdp.convert_to_utf8(), "hello")
def test_convert_to_utf8_2(self):
bdp = BinaryDataProcessor("0110100001100101011011000110110001101001")
self.assertEqual(bdp.convert_to_utf8(), "helli")
def test_convert_to_utf8_3(self):
bdp = BinaryDataProcessor("0110000001100101011011000110110001101111")
self.assertEqual(bdp.convert_to_utf8(), "`ello")
def test_convert_to_utf8_4(self):
bdp = BinaryDataProcessor("0110101101100101011011000110110001101111")
self.assertEqual(bdp.convert_to_utf8(), "kello")
def test_convert_to_utf8_5(self):
bdp = BinaryDataProcessor("0110101101100100011011000110110001101111")
self.assertEqual(bdp.convert_to_utf8(), "kdllo")
class BinaryDataProcessorTestMain(unittest.TestCase):
def test_main(self):
bdp = BinaryDataProcessor("01101000daf3e4r01100101011011000110110001101111")
self.assertEqual(bdp.binary_string, "0110100001100101011011000110110001101111")
self.assertEqual(bdp.calculate_binary_info(), {'Zeroes': 0.475, 'Ones': 0.525, 'Bit length': 40})
self.assertEqual(bdp.convert_to_ascii(), "hello")
self.assertEqual(bdp.convert_to_utf8(), "hello") | class BinaryDataProcessor:
def __init__(self, binary_string):
self.binary_string = binary_string
self.clean_non_binary_chars()
def clean_non_binary_chars(self):
self.binary_string = ''.join(filter(lambda x: x in '01', self.binary_string))
def calculate_binary_info(self):
zeroes_count = self.binary_string.count('0')
ones_count = self.binary_string.count('1')
total_length = len(self.binary_string)
zeroes_percentage = (zeroes_count / total_length)
ones_percentage = (ones_count / total_length)
return {
'Zeroes': zeroes_percentage,
'Ones': ones_percentage,
'Bit length': total_length
}
def convert_to_ascii(self):
byte_array = bytearray()
for i in range(0, len(self.binary_string), 8):
byte = self.binary_string[i:i+8]
decimal = int(byte, 2)
byte_array.append(decimal)
return byte_array.decode('ascii')
def convert_to_utf8(self):
byte_array = bytearray()
for i in range(0, len(self.binary_string), 8):
byte = self.binary_string[i:i+8]
decimal = int(byte, 2)
byte_array.append(decimal)
return byte_array.decode('utf-8') | [] | """
This is a class used to process binary data, which includes functions such as clearing non 0 or 1 characters, counting binary string information, and converting to corresponding strings based on different encoding methods.
"""
| [
{
"method_name": "clean_non_binary_chars",
"method_description": "def clean_non_binary_chars(self):\n \"\"\"\n Clean the binary string by removing all non 0 or 1 characters.\n >>> bdp = BinaryDataProcessor(\"01101000daf3e4r01100101011011000110110001101111\")\n >>> bdp.clean_non_binary_chars()\n >>> bdp.binary_string\n '0110100001100101011011000110110001101111'\n\n \"\"\"",
"test_class": "BinaryDataProcessorTestCleanNonBinaryChars",
"test_code": "class BinaryDataProcessorTestCleanNonBinaryChars(unittest.TestCase):\n def test_clean_non_binary_chars(self):\n bdp = BinaryDataProcessor(\"01101000daf3e4r01100101011011000110110001101111\")\n self.assertEqual(bdp.binary_string, \"0110100001100101011011000110110001101111\")\n\n def test_clean_non_binary_chars_2(self):\n bdp = BinaryDataProcessor(\"01101000daf3e4r01100101011011addf0110001d1111\")\n self.assertEqual(bdp.binary_string, \"011010000110010101101101100011111\")\n\n def test_clean_non_binary_chars_3(self):\n bdp = BinaryDataProcessor(\"0sd1000daf3e4r01100101011011addf0110001d1111\")\n self.assertEqual(bdp.binary_string, \"010000110010101101101100011111\")\n\n def test_clean_non_binary_chars_4(self):\n bdp = BinaryDataProcessor(\"sdsdf\")\n self.assertEqual(bdp.binary_string, \"\")\n\n def test_clean_non_binary_chars_5(self):\n bdp = BinaryDataProcessor(\"0\")\n self.assertEqual(bdp.binary_string, \"0\")",
"solution_code": "def clean_non_binary_chars(self):\n self.binary_string = ''.join(filter(lambda x: x in '01', self.binary_string))",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.binary_string"
],
"method_dependencies": []
}
},
{
"method_name": "calculate_binary_info",
"method_description": "def calculate_binary_info(self):\n \"\"\"\n Calculate the binary string information, including the percentage of 0 and 1, and the total length of the binary string.\n >>> bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n >>> bdp.calculate_binary_info()\n {'Zeroes': 0.475, 'Ones': 0.525, 'Bit length': 40}\n\n \"\"\"",
"test_class": "BinaryDataProcessorTestCalculateBinaryInfo",
"test_code": "class BinaryDataProcessorTestCalculateBinaryInfo(unittest.TestCase):\n def test_calculate_binary_info(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n self.assertEqual(bdp.calculate_binary_info(), {'Zeroes': 0.475, 'Ones': 0.525, 'Bit length': 40})\n\n def test_calculate_binary_info_2(self):\n bdp = BinaryDataProcessor(\"0110100001100101011010011111\")\n self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 28, 'Ones': 0.5357142857142857, 'Zeroes': 0.4642857142857143})\n\n def test_calculate_binary_info_3(self):\n bdp = BinaryDataProcessor(\"01101001111100101011010011111\")\n self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 29, 'Ones': 0.6206896551724138, 'Zeroes': 0.3793103448275862})\n\n def test_calculate_binary_info_4(self):\n bdp = BinaryDataProcessor(\"011010011111001\")\n self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 15, 'Ones': 0.6, 'Zeroes': 0.4})\n\n def test_calculate_binary_info_5(self):\n bdp = BinaryDataProcessor(\"0110100111110010\")\n self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 16, 'Ones': 0.5625, 'Zeroes': 0.4375})",
"solution_code": "def calculate_binary_info(self):\n zeroes_count = self.binary_string.count('0')\n ones_count = self.binary_string.count('1')\n total_length = len(self.binary_string)\n\n zeroes_percentage = (zeroes_count / total_length)\n ones_percentage = (ones_count / total_length)\n\n return {\n 'Zeroes': zeroes_percentage,\n 'Ones': ones_percentage,\n 'Bit length': total_length\n }",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.binary_string"
],
"method_dependencies": []
}
},
{
"method_name": "convert_to_ascii",
"method_description": "def convert_to_ascii(self):\n \"\"\"\n Convert the binary string to ascii string.\n >>> bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n >>> bdp.convert_to_ascii()\n 'hello'\n\n \"\"\"",
"test_class": "BinaryDataProcessorTestConvertToAscii",
"test_code": "class BinaryDataProcessorTestConvertToAscii(unittest.TestCase):\n def test_convert_to_ascii(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"hello\")\n\n def test_convert_to_ascii_2(self):\n bdp = BinaryDataProcessor(\"0110100000100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"h%llo\")\n\n def test_convert_to_ascii_3(self):\n bdp = BinaryDataProcessor(\"01101000011011010110001001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"hmbo\")\n\n def test_convert_to_ascii_4(self):\n bdp = BinaryDataProcessor(\"01101000011001010110001001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"hebo\")\n\n def test_convert_to_ascii_5(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"hello\")",
"solution_code": "def convert_to_ascii(self):\n byte_array = bytearray()\n for i in range(0, len(self.binary_string), 8):\n byte = self.binary_string[i:i+8]\n decimal = int(byte, 2)\n byte_array.append(decimal)\n\n return byte_array.decode('ascii')",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.binary_string"
],
"method_dependencies": []
}
},
{
"method_name": "convert_to_utf8",
"method_description": "def convert_to_utf8(self):\n \"\"\"\n Convert the binary string to utf-8 string.\n >>> bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n >>> bdp.convert_to_utf8()\n 'hello'\n\n \"\"\"",
"test_class": "BinaryDataProcessorTestConvertToUtf8",
"test_code": "class BinaryDataProcessorTestConvertToUtf8(unittest.TestCase):\n def test_convert_to_utf8(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_utf8(), \"hello\")\n\n def test_convert_to_utf8_2(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101001\")\n self.assertEqual(bdp.convert_to_utf8(), \"helli\")\n\n def test_convert_to_utf8_3(self):\n bdp = BinaryDataProcessor(\"0110000001100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_utf8(), \"`ello\")\n\n def test_convert_to_utf8_4(self):\n bdp = BinaryDataProcessor(\"0110101101100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_utf8(), \"kello\")\n\n def test_convert_to_utf8_5(self):\n bdp = BinaryDataProcessor(\"0110101101100100011011000110110001101111\")\n self.assertEqual(bdp.convert_to_utf8(), \"kdllo\")",
"solution_code": "def convert_to_utf8(self):\n byte_array = bytearray()\n for i in range(0, len(self.binary_string), 8):\n byte = self.binary_string[i:i+8]\n decimal = int(byte, 2)\n byte_array.append(decimal)\n\n return byte_array.decode('utf-8')",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.binary_string"
],
"method_dependencies": []
}
}
] | BinaryDataProcessor | [
"BinaryDataProcessorTestCleanNonBinaryChars",
"BinaryDataProcessorTestCalculateBinaryInfo",
"BinaryDataProcessorTestConvertToAscii",
"BinaryDataProcessorTestConvertToUtf8",
"BinaryDataProcessorTestMain"
] | class BinaryDataProcessor:
def __init__(self, binary_string):
"""
Initialize the class with a binary string and clean it by removing all non 0 or 1 characters.
"""
self.binary_string = binary_string
self.clean_non_binary_chars()
| [
"self.binary_string"
] |
ClassEval_11 | class BitStatusUtil:
"""
This is a utility class that provides methods for manipulating and checking status using bitwise operations.
"""
@staticmethod
def add(states, stat):
"""
Add a status to the current status,and check the parameters wheather they are legal.
:param states: Current status,int.
:param stat: Status to be added,int.
:return: The status after adding the status,int.
>>> bit_status_util = BitStatusUtil()
>>> bit_status_util.add(2,4)
6
"""
@staticmethod
def has(states, stat):
"""
Check if the current status contains the specified status,and check the parameters wheather they are legal.
:param states: Current status,int.
:param stat: Specified status,int.
:return: True if the current status contains the specified status,otherwise False,bool.
>>> bit_status_util = BitStatusUtil()
>>> bit_status_util.has(6,2)
True
"""
@staticmethod
def remove(states, stat):
"""
Remove the specified status from the current status,and check the parameters wheather they are legal.
:param states: Current status,int.
:param stat: Specified status,int.
:return: The status after removing the specified status,int.
>>> bit_status_util = BitStatusUtil()
>>> bit_status_util.remove(6,2)
4
"""
@staticmethod
def check(args):
"""
Check if the parameters are legal, args must be greater than or equal to 0 and must be even,if not,raise ValueError.
:param args: Parameters to be checked,list.
:return: None.
>>> bit_status_util = BitStatusUtil()
>>> bit_status_util.check([2,3,4])
Traceback (most recent call last):
...
ValueError: 3 not even
""" | import unittest
class BitStatusUtilTestAdd(unittest.TestCase):
def test_add(self):
bit_status_util = BitStatusUtil()
self.assertEqual(bit_status_util.add(2, 4), 6)
def test_add_2(self):
bit_status_util = BitStatusUtil()
self.assertEqual(bit_status_util.add(2, 0), 2)
def test_add_3(self):
bit_status_util = BitStatusUtil()
self.assertEqual(bit_status_util.add(0, 0), 0)
def test_add_4(self):
bit_status_util = BitStatusUtil()
self.assertEqual(bit_status_util.add(0, 2), 2)
def test_add_5(self):
bit_status_util = BitStatusUtil()
self.assertEqual(bit_status_util.add(2, 2), 2)
class BitStatusUtilTestHas(unittest.TestCase):
def test_has(self):
bit_status_util = BitStatusUtil()
self.assertTrue(bit_status_util.has(6, 2))
def test_has_2(self):
bit_status_util = BitStatusUtil()
self.assertFalse(bit_status_util.has(8, 2))
def test_has_3(self):
bit_status_util = BitStatusUtil()
self.assertTrue(bit_status_util.has(6, 4))
def test_has_4(self):
bit_status_util = BitStatusUtil()
self.assertFalse(bit_status_util.has(8, 6))
def test_has_5(self):
bit_status_util = BitStatusUtil()
self.assertTrue(bit_status_util.has(6, 6))
class BitStatusUtilTestRemove(unittest.TestCase):
def test_remove(self):
bit_status_util = BitStatusUtil()
self.assertEqual(bit_status_util.remove(6, 2), 4)
def test_remove_2(self):
bit_status_util = BitStatusUtil()
self.assertEqual(bit_status_util.remove(8, 2), 8)
def test_remove_3(self):
bit_status_util = BitStatusUtil()
self.assertEqual(bit_status_util.remove(6, 4), 2)
def test_remove_4(self):
bit_status_util = BitStatusUtil()
self.assertEqual(bit_status_util.remove(8, 6), 8)
def test_remove_5(self):
bit_status_util = BitStatusUtil()
self.assertEqual(bit_status_util.remove(6, 6), 0)
class BitStatusUtilTestCheck(unittest.TestCase):
def test_check(self):
bit_status_util = BitStatusUtil()
bit_status_util.check([2])
def test_check_2(self):
bit_status_util = BitStatusUtil()
with self.assertRaises(ValueError):
bit_status_util.check([3])
def test_check_3(self):
bit_status_util = BitStatusUtil()
with self.assertRaises(ValueError):
bit_status_util.check([-1])
def test_check_4(self):
bit_status_util = BitStatusUtil()
with self.assertRaises(ValueError):
bit_status_util.check([2, 3, 4])
def test_check_5(self):
bit_status_util = BitStatusUtil()
with self.assertRaises(ValueError):
bit_status_util.check([2, 3, 4, 5])
class BitStatusUtilTestMain(unittest.TestCase):
def test_main(self):
bit_status_util = BitStatusUtil()
self.assertEqual(bit_status_util.add(2, 4), 6)
self.assertTrue(bit_status_util.has(6, 2))
self.assertEqual(bit_status_util.remove(6, 2), 4)
with self.assertRaises(ValueError):
bit_status_util.check([2, 3, 4]) | class BitStatusUtil:
@staticmethod
def add(states, stat):
BitStatusUtil.check([states, stat])
return states | stat
@staticmethod
def has(states, stat):
BitStatusUtil.check([states, stat])
return (states & stat) == stat
@staticmethod
def remove(states, stat):
BitStatusUtil.check([states, stat])
if BitStatusUtil.has(states, stat):
return states ^ stat
return states
@staticmethod
def check(args):
for arg in args:
if arg < 0:
raise ValueError(f"{arg} must be greater than or equal to 0")
if arg % 2 != 0:
raise ValueError(f"{arg} not even") | [] | """
This is a utility class that provides methods for manipulating and checking status using bitwise operations.
"""
| [
{
"method_name": "add",
"method_description": "def add(states, stat):\n \"\"\"\n Add a status to the current status,and check the parameters wheather they are legal.\n :param states: Current status,int.\n :param stat: Status to be added,int.\n :return: The status after adding the status,int.\n >>> bit_status_util = BitStatusUtil()\n >>> bit_status_util.add(2,4)\n 6\n\n \"\"\"",
"test_class": "BitStatusUtilTestAdd",
"test_code": "class BitStatusUtilTestAdd(unittest.TestCase):\n def test_add(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(2, 4), 6)\n\n def test_add_2(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(2, 0), 2)\n\n def test_add_3(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(0, 0), 0)\n\n def test_add_4(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(0, 2), 2)\n\n def test_add_5(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(2, 2), 2)",
"solution_code": "def add(states, stat):\n BitStatusUtil.check([states, stat])\n return states | stat",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"check"
]
}
},
{
"method_name": "has",
"method_description": "@staticmethod\n def has(states, stat):\n \"\"\"\n Check if the current status contains the specified status,and check the parameters wheather they are legal.\n :param states: Current status,int.\n :param stat: Specified status,int.\n :return: True if the current status contains the specified status,otherwise False,bool.\n >>> bit_status_util = BitStatusUtil()\n >>> bit_status_util.has(6,2)\n True\n\n \"\"\"",
"test_class": "BitStatusUtilTestHas",
"test_code": "class BitStatusUtilTestHas(unittest.TestCase):\n def test_has(self):\n bit_status_util = BitStatusUtil()\n self.assertTrue(bit_status_util.has(6, 2))\n\n def test_has_2(self):\n bit_status_util = BitStatusUtil()\n self.assertFalse(bit_status_util.has(8, 2))\n\n def test_has_3(self):\n bit_status_util = BitStatusUtil()\n self.assertTrue(bit_status_util.has(6, 4))\n\n def test_has_4(self):\n bit_status_util = BitStatusUtil()\n self.assertFalse(bit_status_util.has(8, 6))\n\n def test_has_5(self):\n bit_status_util = BitStatusUtil()\n self.assertTrue(bit_status_util.has(6, 6))",
"solution_code": "@staticmethod\n def has(states, stat):\n BitStatusUtil.check([states, stat])\n return (states & stat) == stat",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"check"
]
}
},
{
"method_name": "remove",
"method_description": "@staticmethod\n def remove(states, stat):\n \"\"\"\n Remove the specified status from the current status,and check the parameters wheather they are legal.\n :param states: Current status,int.\n :param stat: Specified status,int.\n :return: The status after removing the specified status,int.\n >>> bit_status_util = BitStatusUtil()\n >>> bit_status_util.remove(6,2)\n 4\n\n \"\"\"",
"test_class": "BitStatusUtilTestRemove",
"test_code": "class BitStatusUtilTestRemove(unittest.TestCase):\n def test_remove(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(6, 2), 4)\n\n def test_remove_2(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(8, 2), 8)\n\n def test_remove_3(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(6, 4), 2)\n\n def test_remove_4(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(8, 6), 8)\n\n def test_remove_5(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(6, 6), 0)",
"solution_code": "@staticmethod\n def remove(states, stat):\n BitStatusUtil.check([states, stat])\n if BitStatusUtil.has(states, stat):\n return states ^ stat\n return states",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"has",
"check"
]
}
},
{
"method_name": "check",
"method_description": "@staticmethod\n def check(args):\n \"\"\"\n Check if the parameters are legal, args must be greater than or equal to 0 and must be even,if not,raise ValueError.\n :param args: Parameters to be checked,list.\n :return: None.\n >>> bit_status_util = BitStatusUtil()\n >>> bit_status_util.check([2,3,4])\n Traceback (most recent call last):\n ...\n ValueError: 3 not even\n \"\"\"",
"test_class": "BitStatusUtilTestCheck",
"test_code": "class BitStatusUtilTestCheck(unittest.TestCase):\n def test_check(self):\n bit_status_util = BitStatusUtil()\n bit_status_util.check([2])\n\n def test_check_2(self):\n bit_status_util = BitStatusUtil()\n with self.assertRaises(ValueError):\n bit_status_util.check([3])\n\n def test_check_3(self):\n bit_status_util = BitStatusUtil()\n with self.assertRaises(ValueError):\n bit_status_util.check([-1])\n\n def test_check_4(self):\n bit_status_util = BitStatusUtil()\n with self.assertRaises(ValueError):\n bit_status_util.check([2, 3, 4])\n\n def test_check_5(self):\n bit_status_util = BitStatusUtil()\n with self.assertRaises(ValueError):\n bit_status_util.check([2, 3, 4, 5])",
"solution_code": "@staticmethod\n def check(args):\n for arg in args:\n if arg < 0:\n raise ValueError(f\"{arg} must be greater than or equal to 0\")\n if arg % 2 != 0:\n raise ValueError(f\"{arg} not even\")",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | BitStatusUtil | [
"BitStatusUtilTestAdd",
"BitStatusUtilTestHas",
"BitStatusUtilTestRemove",
"BitStatusUtilTestCheck",
"BitStatusUtilTestMain"
] | class BitStatusUtil:
| [] |
ClassEval_12 | import random
class BlackjackGame:
"""
This is a class representing a game of blackjack, which includes creating a deck, calculating the value of a hand, and determine the winner based on the hand values of the player and dealer.
"""
def __init__(self):
"""
Initialize the Blackjack Game with the attribute deck, player_hand and dealer_hand.
While initializing deck attribute, call the create_deck method to generate.
The deck stores 52 rondom order poker with the Jokers removed, format is ['AS', '2S', ...].
player_hand is a list which stores player's hand cards.
dealer_hand is is a list which stores dealer's hand cards.
"""
self.deck = self.create_deck()
self.player_hand = []
self.dealer_hand = []
def create_deck(self):
"""
Create a deck of 52 cards, which stores 52 rondom order poker with the Jokers removed.
:return: a list of 52 rondom order poker with the Jokers removed, format is ['AS', '2S', ...].
>>> black_jack_game = BlackjackGame()
>>> black_jack_game.create_deck()
['QD', '9D', 'JC', 'QH', '2S', 'JH', '7D', '6H', '9S', '5C', '7H', 'QS', '5H',
'6C', '7C', '3D', '10C', 'AD', '4C', '5D', 'AH', '2D', 'QC', 'KH', '9C', '9H',
'4H', 'JS', '6S', '8H', '8C', '4S', '3H', '10H', '7S', '6D', '3C', 'KC', '3S',
'2H', '10D', 'KS', '4D', 'AC', '10S', '2C', 'KD', '5S', 'JD', '8S', 'AS', '8D']
"""
def calculate_hand_value(self, hand):
"""
Calculate the value of the poker cards stored in hand list according to the rules of the Blackjack Game.
If the card is a digit, its value is added to the total hand value.
Value of J, Q, or K is 10, while Aces are worth 11.
If the total hand value exceeds 21 and there are Aces present, one Ace is treated as having a value of 1 instead of 11,
until the hand value is less than or equal to 21, or all Aces have been counted as value of 1.
:param hand: list
:return: the value of the poker cards stored in hand list, a number.
>>> black_jack_game.calculate_hand_value(['QD', '9D', 'JC', 'QH', 'AS'])
40
"""
def check_winner(self, player_hand, dealer_hand):
"""
Determines the winner of a game by comparing the hand values of the player and dealer.
rule:
If both players have hand values that are equal to or less than 21, the winner is the one whose hand value is closer to 21.
Otherwise, the winner is the one with the lower hand value.
:param player_hand: list
:param dealer_hand: list
:return: the result of the game, only two certain str: 'Dealer wins' or 'Player wins'
>>> black_jack_game.check_winner(['QD', '9D', 'JC', 'QH', 'AS'], ['QD', '9D', 'JC', 'QH', '2S'])
'Player wins'
""" | import unittest
class BlackjackGameTestCreateDeck(unittest.TestCase):
def setUp(self):
self.blackjackGame = BlackjackGame()
self.deck = self.blackjackGame.deck
def test_create_deck_1(self):
self.assertEqual(len(self.deck), 52)
def test_create_deck_2(self):
suits = ['S', 'C', 'D', 'H']
ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
for suit in suits:
for rank in ranks:
self.assertIn(rank + suit, self.deck)
def test_create_deck_3(self):
suits = ['S', 'C', 'D', 'H']
ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9']
for suit in suits:
for rank in ranks:
self.assertIn(rank + suit, self.deck)
def test_create_deck_4(self):
suits = ['S', 'C', 'D', 'H']
ranks = ['10', 'J', 'Q', 'K']
for suit in suits:
for rank in ranks:
self.assertIn(rank + suit, self.deck)
def test_create_deck_5(self):
suits = ['S', 'C', 'D', 'H']
ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9']
for suit in suits:
for rank in ranks:
self.assertIn(rank + suit, self.deck)
class BlackjackGameTestCalculateHandValue(unittest.TestCase):
def test_calculate_hand_value_1(self):
blackjackGame = BlackjackGame()
hand = ['2S', '3S', '4S', '5S']
self.assertEqual(blackjackGame.calculate_hand_value(hand), 14)
def test_calculate_hand_value_2(self):
blackjackGame = BlackjackGame()
hand = ['2S', '3S', 'JS', 'QS']
self.assertEqual(blackjackGame.calculate_hand_value(hand), 25)
def test_calculate_hand_value_3(self):
blackjackGame = BlackjackGame()
hand = ['2S', '3S', '4S', 'AS']
self.assertEqual(blackjackGame.calculate_hand_value(hand), 20)
def test_calculate_hand_value_4(self):
blackjackGame = BlackjackGame()
hand = ['JS', 'QS', '4S', 'AS']
self.assertEqual(blackjackGame.calculate_hand_value(hand), 25)
def test_calculate_hand_value_5(self):
blackjackGame = BlackjackGame()
hand = ['JS', 'QS', 'AS', 'AS', 'AS']
self.assertEqual(blackjackGame.calculate_hand_value(hand), 23)
def test_calculate_hand_value_6(self):
blackjackGame = BlackjackGame()
hand = ['JS', 'QS', 'BS', 'CS']
self.assertEqual(blackjackGame.calculate_hand_value(hand), 20)
class BlackjackGameTestCheckWinner(unittest.TestCase):
def setUp(self):
self.blackjackGame = BlackjackGame()
# player > 21 but dealer not, dealer wins.
def test_check_winner_1(self):
player_hand = ['2S', 'JS', 'QS']
dealer_hand = ['7S', '9S']
self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins')
# dealer > 21 but player not, player wins.
def test_check_winner_2(self):
player_hand = ['2S', '4S', '5S']
dealer_hand = ['2S', 'JS', 'QS']
self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Player wins')
# both > 21 but dealer smaller, dealer wins.
def test_check_winner_3(self):
player_hand = ['3S', 'JS', 'QS']
dealer_hand = ['2S', 'JS', 'QS']
self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins')
# both > 21 but player smaller, player wins.
def test_check_winner_4(self):
player_hand = ['2S', 'JS', 'QS']
dealer_hand = ['3S', 'JS', 'QS']
self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Player wins')
# both < 21 but dealer is bigger, dealer wins.
def test_check_winner_5(self):
player_hand = ['2S', '3S', '5S']
dealer_hand = ['AS', 'JS']
self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins')
# both < 21 but player is bigger, player wins.
def test_check_winner_6(self):
player_hand = ['AS', 'JS']
dealer_hand = ['2S', '3S', '5S']
self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Player wins')
class BlackjackGameTestMain(unittest.TestCase):
# calculate_hand_value method will be invoked in check_winner
def test_main_1(self):
blackjackGame = BlackjackGame()
deck = blackjackGame.deck
suits = ['S', 'C', 'D', 'H']
ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
for suit in suits:
for rank in ranks:
self.assertIn(rank + suit, deck)
player_hand = ['2S', 'JS', 'QS']
dealer_hand = ['7S', '9S']
self.assertEqual(blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins') | import random
class BlackjackGame:
def __init__(self):
self.deck = self.create_deck()
self.player_hand = []
self.dealer_hand = []
def create_deck(self):
deck = []
suits = ['S', 'C', 'D', 'H']
ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
for suit in suits:
for rank in ranks:
deck.append(rank + suit)
random.shuffle(deck)
return deck
def calculate_hand_value(self, hand):
value = 0
num_aces = 0
for card in hand:
rank = card[:-1]
if rank.isdigit():
value += int(rank)
elif rank in ['J', 'Q', 'K']:
value += 10
elif rank == 'A':
value += 11
num_aces += 1
while value > 21 and num_aces > 0:
value -= 10
num_aces -= 1
return value
def check_winner(self, player_hand, dealer_hand):
player_value = self.calculate_hand_value(player_hand)
dealer_value = self.calculate_hand_value(dealer_hand)
if player_value > 21 and dealer_value > 21:
if player_value <= dealer_value:
return 'Player wins'
else:
return 'Dealer wins'
elif player_value > 21:
return 'Dealer wins'
elif dealer_value > 21:
return 'Player wins'
else:
if player_value <= dealer_value:
return 'Dealer wins'
else:
return 'Player wins' | [
"import random"
] | """
This is a class representing a game of blackjack, which includes creating a deck, calculating the value of a hand, and determine the winner based on the hand values of the player and dealer.
"""
| [
{
"method_name": "create_deck",
"method_description": "def create_deck(self):\n \"\"\"\n Create a deck of 52 cards, which stores 52 rondom order poker with the Jokers removed.\n :return: a list of 52 rondom order poker with the Jokers removed, format is ['AS', '2S', ...].\n >>> black_jack_game = BlackjackGame()\n >>> black_jack_game.create_deck()\n ['QD', '9D', 'JC', 'QH', '2S', 'JH', '7D', '6H', '9S', '5C', '7H', 'QS', '5H',\n '6C', '7C', '3D', '10C', 'AD', '4C', '5D', 'AH', '2D', 'QC', 'KH', '9C', '9H',\n '4H', 'JS', '6S', '8H', '8C', '4S', '3H', '10H', '7S', '6D', '3C', 'KC', '3S',\n '2H', '10D', 'KS', '4D', 'AC', '10S', '2C', 'KD', '5S', 'JD', '8S', 'AS', '8D']\n \"\"\"",
"test_class": "BlackjackGameTestCreateDeck",
"test_code": "class BlackjackGameTestCreateDeck(unittest.TestCase):\n def setUp(self):\n self.blackjackGame = BlackjackGame()\n self.deck = self.blackjackGame.deck\n\n def test_create_deck_1(self):\n self.assertEqual(len(self.deck), 52)\n\n def test_create_deck_2(self):\n suits = ['S', 'C', 'D', 'H']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']\n for suit in suits:\n for rank in ranks:\n self.assertIn(rank + suit, self.deck)\n\n def test_create_deck_3(self):\n suits = ['S', 'C', 'D', 'H']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9']\n for suit in suits:\n for rank in ranks:\n self.assertIn(rank + suit, self.deck)\n\n def test_create_deck_4(self):\n suits = ['S', 'C', 'D', 'H']\n ranks = ['10', 'J', 'Q', 'K']\n for suit in suits:\n for rank in ranks:\n self.assertIn(rank + suit, self.deck)\n\n def test_create_deck_5(self):\n suits = ['S', 'C', 'D', 'H']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9']\n for suit in suits:\n for rank in ranks:\n self.assertIn(rank + suit, self.deck)",
"solution_code": "def create_deck(self):\n deck = []\n suits = ['S', 'C', 'D', 'H']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']\n for suit in suits:\n for rank in ranks:\n deck.append(rank + suit)\n random.shuffle(deck)\n return deck",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"random"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "calculate_hand_value",
"method_description": "def calculate_hand_value(self, hand):\n \"\"\"\n Calculate the value of the poker cards stored in hand list according to the rules of the Blackjack Game.\n If the card is a digit, its value is added to the total hand value.\n Value of J, Q, or K is 10, while Aces are worth 11.\n If the total hand value exceeds 21 and there are Aces present, one Ace is treated as having a value of 1 instead of 11,\n until the hand value is less than or equal to 21, or all Aces have been counted as value of 1.\n :param hand: list\n :return: the value of the poker cards stored in hand list, a number.\n >>> black_jack_game.calculate_hand_value(['QD', '9D', 'JC', 'QH', 'AS'])\n 40\n \"\"\"",
"test_class": "BlackjackGameTestCalculateHandValue",
"test_code": "class BlackjackGameTestCalculateHandValue(unittest.TestCase):\n def test_calculate_hand_value_1(self):\n blackjackGame = BlackjackGame()\n hand = ['2S', '3S', '4S', '5S']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 14)\n\n def test_calculate_hand_value_2(self):\n blackjackGame = BlackjackGame()\n hand = ['2S', '3S', 'JS', 'QS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 25)\n\n def test_calculate_hand_value_3(self):\n blackjackGame = BlackjackGame()\n hand = ['2S', '3S', '4S', 'AS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 20)\n\n def test_calculate_hand_value_4(self):\n blackjackGame = BlackjackGame()\n hand = ['JS', 'QS', '4S', 'AS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 25)\n\n def test_calculate_hand_value_5(self):\n blackjackGame = BlackjackGame()\n hand = ['JS', 'QS', 'AS', 'AS', 'AS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 23)\n\n def test_calculate_hand_value_6(self):\n blackjackGame = BlackjackGame()\n hand = ['JS', 'QS', 'BS', 'CS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 20)",
"solution_code": "def calculate_hand_value(self, hand):\n value = 0\n num_aces = 0\n for card in hand:\n rank = card[:-1]\n if rank.isdigit():\n value += int(rank)\n elif rank in ['J', 'Q', 'K']:\n value += 10\n elif rank == 'A':\n value += 11\n num_aces += 1\n while value > 21 and num_aces > 0:\n value -= 10\n num_aces -= 1\n return value",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "check_winner",
"method_description": "def check_winner(self, player_hand, dealer_hand):\n \"\"\"\n Determines the winner of a game by comparing the hand values of the player and dealer.\n rule:\n If both players have hand values that are equal to or less than 21, the winner is the one whose hand value is closer to 21.\n Otherwise, the winner is the one with the lower hand value.\n :param player_hand: list\n :param dealer_hand: list\n :return: the result of the game, only two certain str: 'Dealer wins' or 'Player wins'\n >>> black_jack_game.check_winner(['QD', '9D', 'JC', 'QH', 'AS'], ['QD', '9D', 'JC', 'QH', '2S'])\n 'Player wins'\n \"\"\"",
"test_class": "BlackjackGameTestCheckWinner",
"test_code": "class BlackjackGameTestCheckWinner(unittest.TestCase):\n def setUp(self):\n self.blackjackGame = BlackjackGame()\n\n # player > 21 but dealer not, dealer wins.\n def test_check_winner_1(self):\n player_hand = ['2S', 'JS', 'QS']\n dealer_hand = ['7S', '9S']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins')\n\n # dealer > 21 but player not, player wins.\n def test_check_winner_2(self):\n player_hand = ['2S', '4S', '5S']\n dealer_hand = ['2S', 'JS', 'QS']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Player wins')\n\n # both > 21 but dealer smaller, dealer wins.\n def test_check_winner_3(self):\n player_hand = ['3S', 'JS', 'QS']\n dealer_hand = ['2S', 'JS', 'QS']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins')\n\n # both > 21 but player smaller, player wins.\n def test_check_winner_4(self):\n player_hand = ['2S', 'JS', 'QS']\n dealer_hand = ['3S', 'JS', 'QS']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Player wins')\n\n # both < 21 but dealer is bigger, dealer wins.\n def test_check_winner_5(self):\n player_hand = ['2S', '3S', '5S']\n dealer_hand = ['AS', 'JS']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins')\n\n # both < 21 but player is bigger, player wins.\n def test_check_winner_6(self):\n player_hand = ['AS', 'JS']\n dealer_hand = ['2S', '3S', '5S']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Player wins')",
"solution_code": "def check_winner(self, player_hand, dealer_hand):\n player_value = self.calculate_hand_value(player_hand)\n dealer_value = self.calculate_hand_value(dealer_hand)\n if player_value > 21 and dealer_value > 21:\n if player_value <= dealer_value:\n return 'Player wins'\n else:\n return 'Dealer wins'\n elif player_value > 21:\n return 'Dealer wins'\n elif dealer_value > 21:\n return 'Player wins'\n else:\n if player_value <= dealer_value:\n return 'Dealer wins'\n else:\n return 'Player wins'",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"calculate_hand_value"
]
}
}
] | BlackjackGame | [
"BlackjackGameTestCreateDeck",
"BlackjackGameTestCalculateHandValue",
"BlackjackGameTestCheckWinner",
"BlackjackGameTestMain"
] | class BlackjackGame:
def __init__(self):
"""
Initialize the Blackjack Game with the attribute deck, player_hand and dealer_hand.
While initializing deck attribute, call the create_deck method to generate.
The deck stores 52 rondom order poker with the Jokers removed, format is ['AS', '2S', ...].
player_hand is a list which stores player's hand cards.
dealer_hand is is a list which stores dealer's hand cards.
"""
self.deck = self.create_deck()
self.player_hand = []
self.dealer_hand = []
| [
"self.dealer_hand",
"self.deck",
"self.player_hand"
] |
ClassEval_13 | class BookManagement:
"""
This is a class as managing books system, which supports to add and remove books from the inventory dict, view the inventory, and check the quantity of a specific book.
"""
def __init__(self):
"""
Initialize the inventory of Book Manager.
"""
self.inventory = {}
def add_book(self, title, quantity=1):
"""
Add one or several books to inventory which is sorted by book title.
:param title: str, the book title
:param quantity: int, default value is 1.
"""
def remove_book(self, title, quantity):
"""
Remove one or several books from inventory which is sorted by book title.
Raise false while get invalid input.
:param title: str, the book title
:param quantity: int
"""
def view_inventory(self):
"""
Get the inventory of the Book Management.
:return self.inventory: dictionary, {title(str): quantity(int), ...}
>>> bookManagement = BookManagement()
>>> bookManagement.add_book("book1", 1)
>>> bookManagement.add_book("book2", 1)
>>> bookManagement.view_inventory()
{'book1': 1, 'book2': 1}
"""
def view_book_quantity(self, title):
"""
Get the quantity of a book.
:param title: str, the title of the book.
:return quantity: the quantity of this book title. return 0 when the title does not exist in self.invenroty
>>> bookManagement = BookManagement()
>>> bookManagement.add_book("book1", 1)
>>> bookManagement.view_book_quantity("book3")
0
""" | import unittest
class BookManagementTestAddBook(unittest.TestCase):
def test_add_book_1(self):
bookManagement = BookManagement()
bookManagement.add_book("book1")
self.assertEqual({"book1": 1}, bookManagement.inventory)
def test_add_book_2(self):
bookManagement = BookManagement()
self.assertEqual({}, bookManagement.inventory)
def test_add_book_3(self):
bookManagement = BookManagement()
bookManagement.add_book("book1")
bookManagement.add_book("book1", 2)
self.assertEqual({"book1": 3}, bookManagement.inventory)
def test_add_book_4(self):
bookManagement = BookManagement()
bookManagement.add_book("book1", 2)
self.assertEqual({"book1": 2}, bookManagement.inventory)
def test_add_book_5(self):
bookManagement = BookManagement()
bookManagement.add_book("book1", 2)
bookManagement.add_book("book1")
self.assertEqual({"book1": 3}, bookManagement.inventory)
class BookManagementTestRemoveBook(unittest.TestCase):
def setUp(self) -> None:
self.bookManagement = BookManagement()
self.bookManagement.add_book("book1", 2)
self.bookManagement.add_book("book2")
# remove all this title books
def test_remove_book_1(self):
self.bookManagement.remove_book("book1", 2)
self.assertEqual(self.bookManagement.inventory, {"book2": 1})
# remove part
def test_remove_book_2(self):
self.bookManagement.remove_book("book1", 1)
self.assertEqual(self.bookManagement.inventory, {"book1": 1, "book2": 1})
# remove the title that doesn't exist
def test_remove_book_3(self):
with self.assertRaises(Exception):
self.bookManagement.remove_book("book3", 1)
# invalid quantity
def test_remove_book_4(self):
with self.assertRaises(Exception):
self.bookManagement.remove_book("book2", 2)
def test_remove_book_5(self):
with self.assertRaises(Exception):
self.bookManagement.remove_book("book2", 5)
class BookManagementTestViewInventory(unittest.TestCase):
def test_view_inventory_1(self):
bookManagement = BookManagement()
bookManagement.add_book("book1", 2)
bookManagement.add_book("book2")
expected = {"book1": 2, "book2": 1}
self.assertEqual(expected, bookManagement.inventory)
def test_view_inventory_2(self):
bookManagement = BookManagement()
expected = {}
self.assertEqual(expected, bookManagement.inventory)
def test_view_inventory_3(self):
bookManagement = BookManagement()
bookManagement.add_book("book1", 2)
bookManagement.add_book("book2")
expected = {"book1": 2, "book2": 1}
self.assertEqual(expected, bookManagement.inventory)
def test_view_inventory_4(self):
bookManagement = BookManagement()
bookManagement.add_book("book1", 2)
bookManagement.add_book("book2")
bookManagement.remove_book("book1", 2)
expected = {"book2": 1}
self.assertEqual(expected, bookManagement.inventory)
def test_view_inventory_5(self):
bookManagement = BookManagement()
bookManagement.add_book("book1", 2)
bookManagement.add_book("book2", 1)
bookManagement.remove_book("book1", 2)
bookManagement.remove_book("book2",1)
expected = {}
self.assertEqual(expected, bookManagement.inventory)
class BookManagementTestViewBookQuantity(unittest.TestCase):
def test_view_book_quantity_1(self):
bookManagement = BookManagement()
bookManagement.add_book("book1", 2)
self.assertEqual(2, bookManagement.view_book_quantity("book1"))
def test_view_book_quantity_2(self):
bookManagement = BookManagement()
self.assertEqual(0, bookManagement.view_book_quantity("book1"))
def test_view_book_quantity_3(self):
bookManagement = BookManagement()
bookManagement.add_book("book1", 2)
self.assertEqual(2, bookManagement.view_book_quantity("book1"))
def test_view_book_quantity_4(self):
bookManagement = BookManagement()
bookManagement.add_book("book1", 2)
bookManagement.remove_book("book1", 2)
self.assertEqual(0, bookManagement.view_book_quantity("book1"))
def test_view_book_quantity_5(self):
bookManagement = BookManagement()
bookManagement.add_book("book1", 3)
bookManagement.remove_book("book1", 2)
self.assertEqual(1, bookManagement.view_book_quantity("book1"))
class BookManagementTestMain(unittest.TestCase):
def test_main(self):
bookManagement = BookManagement()
bookManagement.add_book("book1", 2)
bookManagement.add_book("book2")
self.assertEqual(bookManagement.view_inventory(), {"book1": 2, "book2": 1})
bookManagement.remove_book("book2", 1)
self.assertEqual(bookManagement.view_inventory(), {"book1": 2})
self.assertEqual(0, bookManagement.view_book_quantity("book2")) | class BookManagement:
def __init__(self):
self.inventory = {}
def add_book(self, title, quantity=1):
if title in self.inventory:
self.inventory[title] += quantity
else:
self.inventory[title] = quantity
def remove_book(self, title, quantity):
if title not in self.inventory or self.inventory[title] < quantity:
raise False
self.inventory[title] -= quantity
if self.inventory[title] == 0:
del (self.inventory[title])
def view_inventory(self):
return self.inventory
def view_book_quantity(self, title):
if title not in self.inventory:
return 0
return self.inventory[title] | [] | """
This is a class as managing books system, which supports to add and remove books from the inventory dict, view the inventory, and check the quantity of a specific book.
"""
| [
{
"method_name": "add_book",
"method_description": "def add_book(self, title, quantity=1):\n \"\"\"\n Add one or several books to inventory which is sorted by book title.\n :param title: str, the book title\n :param quantity: int, default value is 1.\n \"\"\"",
"test_class": "BookManagementTestAddBook",
"test_code": "class BookManagementTestAddBook(unittest.TestCase):\n def test_add_book_1(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\")\n self.assertEqual({\"book1\": 1}, bookManagement.inventory)\n\n def test_add_book_2(self):\n bookManagement = BookManagement()\n self.assertEqual({}, bookManagement.inventory)\n\n def test_add_book_3(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\")\n bookManagement.add_book(\"book1\", 2)\n self.assertEqual({\"book1\": 3}, bookManagement.inventory)\n\n def test_add_book_4(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n self.assertEqual({\"book1\": 2}, bookManagement.inventory)\n\n def test_add_book_5(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book1\")\n self.assertEqual({\"book1\": 3}, bookManagement.inventory)",
"solution_code": "def add_book(self, title, quantity=1):\n if title in self.inventory:\n self.inventory[title] += quantity\n else:\n self.inventory[title] = quantity",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.inventory"
],
"method_dependencies": []
}
},
{
"method_name": "remove_book",
"method_description": "def remove_book(self, title, quantity):\n \"\"\"\n Remove one or several books from inventory which is sorted by book title.\n Raise false while get invalid input.\n :param title: str, the book title\n :param quantity: int\n \"\"\"",
"test_class": "BookManagementTestRemoveBook",
"test_code": "class BookManagementTestRemoveBook(unittest.TestCase):\n def setUp(self) -> None:\n self.bookManagement = BookManagement()\n self.bookManagement.add_book(\"book1\", 2)\n self.bookManagement.add_book(\"book2\")\n\n # remove all this title books\n def test_remove_book_1(self):\n self.bookManagement.remove_book(\"book1\", 2)\n self.assertEqual(self.bookManagement.inventory, {\"book2\": 1})\n\n # remove part\n def test_remove_book_2(self):\n self.bookManagement.remove_book(\"book1\", 1)\n self.assertEqual(self.bookManagement.inventory, {\"book1\": 1, \"book2\": 1})\n\n # remove the title that doesn't exist\n def test_remove_book_3(self):\n with self.assertRaises(Exception):\n self.bookManagement.remove_book(\"book3\", 1)\n\n # invalid quantity\n def test_remove_book_4(self):\n with self.assertRaises(Exception):\n self.bookManagement.remove_book(\"book2\", 2)\n\n def test_remove_book_5(self):\n with self.assertRaises(Exception):\n self.bookManagement.remove_book(\"book2\", 5)",
"solution_code": "def remove_book(self, title, quantity):\n if title not in self.inventory or self.inventory[title] < quantity:\n raise False\n self.inventory[title] -= quantity\n if self.inventory[title] == 0:\n del (self.inventory[title])",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.inventory"
],
"method_dependencies": []
}
},
{
"method_name": "view_inventory",
"method_description": "def view_inventory(self):\n \"\"\"\n Get the inventory of the Book Management.\n :return self.inventory: dictionary, {title(str): quantity(int), ...}\n >>> bookManagement = BookManagement()\n >>> bookManagement.add_book(\"book1\", 1)\n >>> bookManagement.add_book(\"book2\", 1)\n >>> bookManagement.view_inventory()\n {'book1': 1, 'book2': 1}\n \"\"\"",
"test_class": "BookManagementTestViewInventory",
"test_code": "class BookManagementTestViewInventory(unittest.TestCase):\n def test_view_inventory_1(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book2\")\n expected = {\"book1\": 2, \"book2\": 1}\n self.assertEqual(expected, bookManagement.inventory)\n\n def test_view_inventory_2(self):\n bookManagement = BookManagement()\n expected = {}\n self.assertEqual(expected, bookManagement.inventory)\n\n def test_view_inventory_3(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book2\")\n expected = {\"book1\": 2, \"book2\": 1}\n self.assertEqual(expected, bookManagement.inventory)\n\n def test_view_inventory_4(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book2\")\n bookManagement.remove_book(\"book1\", 2)\n expected = {\"book2\": 1}\n self.assertEqual(expected, bookManagement.inventory)\n\n def test_view_inventory_5(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book2\", 1)\n bookManagement.remove_book(\"book1\", 2)\n bookManagement.remove_book(\"book2\",1)\n expected = {}\n self.assertEqual(expected, bookManagement.inventory)",
"solution_code": "def view_inventory(self):\n return self.inventory",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.inventory"
],
"method_dependencies": []
}
},
{
"method_name": "view_book_quantity",
"method_description": "def view_book_quantity(self, title):\n \"\"\"\n Get the quantity of a book.\n :param title: str, the title of the book.\n :return quantity: the quantity of this book title. return 0 when the title does not exist in self.invenroty\n >>> bookManagement = BookManagement()\n >>> bookManagement.add_book(\"book1\", 1)\n >>> bookManagement.view_book_quantity(\"book3\")\n 0\n \"\"\"",
"test_class": "BookManagementTestViewBookQuantity",
"test_code": "class BookManagementTestViewBookQuantity(unittest.TestCase):\n def test_view_book_quantity_1(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n self.assertEqual(2, bookManagement.view_book_quantity(\"book1\"))\n\n def test_view_book_quantity_2(self):\n bookManagement = BookManagement()\n self.assertEqual(0, bookManagement.view_book_quantity(\"book1\"))\n\n def test_view_book_quantity_3(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n self.assertEqual(2, bookManagement.view_book_quantity(\"book1\"))\n\n def test_view_book_quantity_4(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.remove_book(\"book1\", 2)\n self.assertEqual(0, bookManagement.view_book_quantity(\"book1\"))\n\n def test_view_book_quantity_5(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 3)\n bookManagement.remove_book(\"book1\", 2)\n self.assertEqual(1, bookManagement.view_book_quantity(\"book1\"))",
"solution_code": "def view_book_quantity(self, title):\n if title not in self.inventory:\n return 0\n return self.inventory[title]",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.inventory"
],
"method_dependencies": []
}
}
] | BookManagement | [
"BookManagementTestAddBook",
"BookManagementTestRemoveBook",
"BookManagementTestViewInventory",
"BookManagementTestViewBookQuantity",
"BookManagementTestMain"
] | class BookManagement:
def __init__(self):
"""
Initialize the inventory of Book Manager.
"""
self.inventory = {}
| [
"self.inventory"
] |
ClassEval_14 | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
"""
Initializes the class by creating a database connection and cursor,
and creates the book table if it does not already exist
:param db_name: str, the name of db file
"""
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
self.create_table()
def create_table(self):
"""
Creates the book table in the database if it does not already exist.
>>> book_db = BookManagementDB("test.db")
>>> book_db.create_table()
"""
def add_book(self, title, author):
"""
Adds a book to the database with the specified title and author,
setting its availability to 1 as free to borrow.
:param title: str, book title
:param author: str, author name
>>> book_db = BookManagementDB("test.db")
>>> book_db.create_table()
>>> book_db.add_book('book1', 'author')
"""
def remove_book(self, book_id):
"""
Removes a book from the database based on the given book ID.
:param book_id: int
>>> book_db = BookManagementDB("test.db")
>>> book_db.remove_book(1)
"""
def borrow_book(self, book_id):
"""
Marks a book as borrowed in the database based on the given book ID.
:param book_id: int
>>> book_db = BookManagementDB("test.db")
>>> book_db.borrow_book(1)
"""
def return_book(self, book_id):
"""
Marks a book as returned in the database based on the given book ID.
:param book_id: int
>>> book_db = BookManagementDB("test.db")
>>> book_db.return_book(1)
"""
def search_books(self):
"""
Retrieves all books from the database and returns their information.
:return books: list[tuple], the information of all books in database
>>> book_db.search_books()
[(1, 'book1', 'author', 1)]
""" | import unittest
import os
class BookManagementDBTestCreateTable(unittest.TestCase):
def setUp(self):
self.db_name = "test.db"
self.db = BookManagementDB(self.db_name)
self.connection = sqlite3.connect(self.db_name)
self.cursor = self.connection.cursor()
def test_create_table_1(self):
# Check if the table exists
self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='books'")
result = self.cursor.fetchone()
self.assertIsNotNone(result)
def test_create_table_2(self):
self.db.create_table()
# Check if the table has the correct columns
self.cursor.execute("PRAGMA table_info(books)")
columns = self.cursor.fetchall()
column_names = [column[1] for column in columns]
expected_column_names = ['id', 'title', 'author', 'available']
self.assertEqual(column_names, expected_column_names)
def tearDown(self):
self.db.connection.close()
self.connection.close()
# remove the test database file
os.remove(self.db_name)
class BookManagementDBTestAddBook(unittest.TestCase):
def setUp(self):
self.db_name = "test.db"
self.db = BookManagementDB(self.db_name)
self.connection = sqlite3.connect(self.db_name)
self.cursor = self.connection.cursor()
def test_add_book(self):
title = "Introduction to Python"
author = "John Smith"
self.db.add_book(title, author)
# Check if the book was added correctly
self.cursor.execute("SELECT title, author, available FROM books WHERE id=1")
result = self.cursor.fetchone()
self.assertIsNotNone(result)
self.assertEqual(result[0], title)
self.assertEqual(result[1], author)
self.assertEqual(result[2], 1)
def tearDown(self):
self.db.connection.close()
self.connection.close()
# remove the test database file
os.remove(self.db_name)
class BookManagementDBTestRemoveBook(unittest.TestCase):
def setUp(self):
self.db_name = "test.db"
self.db = BookManagementDB(self.db_name)
self.connection = sqlite3.connect(self.db_name)
self.cursor = self.connection.cursor()
# Add a book for testing removal
self.db.add_book("Book to Remove", "John Doe")
def test_remove_book(self):
self.db.remove_book(1)
# Check if the book was removed correctly
self.cursor.execute("SELECT * FROM books WHERE id=1")
result = self.cursor.fetchone()
self.assertIsNone(result)
def tearDown(self):
self.db.connection.close()
self.connection.close()
# remove the test database file
os.remove(self.db_name)
class BookManagementDBTestBorrowBook(unittest.TestCase):
def setUp(self):
self.db_name = "test.db"
self.db = BookManagementDB(self.db_name)
self.connection = sqlite3.connect(self.db_name)
self.cursor = self.connection.cursor()
# Add a book for testing borrowing
self.db.add_book("Book to Borrow", "Jane Smith")
def test_borrow_book(self):
self.db.borrow_book(1)
# Check if the book was marked as unavailable
self.cursor.execute("SELECT available FROM books WHERE id=1")
result = self.cursor.fetchone()
self.assertEqual(result[0], 0)
def tearDown(self):
self.db.connection.close()
self.connection.close()
# remove the test database file
os.remove(self.db_name)
class BookManagementDBTestReturnBook(unittest.TestCase):
def setUp(self):
self.db_name = "test.db"
self.db = BookManagementDB(self.db_name)
self.connection = sqlite3.connect(self.db_name)
self.cursor = self.connection.cursor()
# Add a book for testing returning
self.db.add_book("Book to Return", "James Smith")
self.db.borrow_book(1) # Mark the book as borrowed
def test_return_book(self):
self.db.return_book(1)
# Check if the book was marked as available again
self.cursor.execute("SELECT available FROM books WHERE id=1")
result = self.cursor.fetchone()
self.assertEqual(result[0], 1)
def tearDown(self):
self.db.connection.close()
self.connection.close()
# remove the test database file
os.remove(self.db_name)
class BookManagementDBTestSearchBooks(unittest.TestCase):
def setUp(self):
self.db_name = "test.db"
self.db = BookManagementDB(self.db_name)
self.connection = sqlite3.connect(self.db_name)
self.cursor = self.connection.cursor()
# Add some books for testing search
self.db.add_book("Book 1", "Author 1")
self.db.add_book("Book 2", "Author 2")
self.db.add_book("Book 3", "Author 3")
def test_search_books(self):
books = self.db.search_books()
# Ensure that all books were retrieved
self.assertEqual(len(books), 3)
# Ensure that the correct book information is retrieved
self.assertEqual(books[0][1], "Book 1")
self.assertEqual(books[1][2], "Author 2")
self.assertEqual(books[2][3], 1)
def tearDown(self):
self.db.connection.close()
self.connection.close()
# remove the test database file
os.remove(self.db_name) | import sqlite3
class BookManagementDB:
def __init__(self, db_name):
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
self.create_table()
def create_table(self):
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY,
title TEXT,
author TEXT,
available INTEGER
)
''')
self.connection.commit()
def add_book(self, title, author):
self.cursor.execute('''
INSERT INTO books (title, author, available)
VALUES (?, ?, 1)
''', (title, author))
self.connection.commit()
def remove_book(self, book_id):
self.cursor.execute('''
DELETE FROM books WHERE id = ?
''', (book_id,))
self.connection.commit()
def borrow_book(self, book_id):
self.cursor.execute('''
UPDATE books SET available = 0 WHERE id = ?
''', (book_id,))
self.connection.commit()
def return_book(self, book_id):
self.cursor.execute('''
UPDATE books SET available = 1 WHERE id = ?
''', (book_id,))
self.connection.commit()
def search_books(self):
self.cursor.execute('''
SELECT * FROM books
''')
books = self.cursor.fetchall()
return books | [
"import sqlite3"
] | """
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
| [
{
"method_name": "create_table",
"method_description": "def create_table(self):\n \"\"\"\n Creates the book table in the database if it does not already exist.\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.create_table()\n \"\"\"",
"test_class": "BookManagementDBTestCreateTable",
"test_code": "class BookManagementDBTestCreateTable(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n\n def test_create_table_1(self):\n # Check if the table exists\n self.cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='books'\")\n result = self.cursor.fetchone()\n self.assertIsNotNone(result)\n\n def test_create_table_2(self):\n self.db.create_table()\n # Check if the table has the correct columns\n self.cursor.execute(\"PRAGMA table_info(books)\")\n columns = self.cursor.fetchall()\n column_names = [column[1] for column in columns]\n expected_column_names = ['id', 'title', 'author', 'available']\n self.assertEqual(column_names, expected_column_names)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)",
"solution_code": "def create_table(self):\n self.cursor.execute('''\n CREATE TABLE IF NOT EXISTS books (\n id INTEGER PRIMARY KEY,\n title TEXT,\n author TEXT,\n available INTEGER\n )\n ''')\n self.connection.commit()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.connection",
"self.cursor"
],
"method_dependencies": []
}
},
{
"method_name": "add_book",
"method_description": "def add_book(self, title, author):\n \"\"\"\n Adds a book to the database with the specified title and author, \n setting its availability to 1 as free to borrow.\n :param title: str, book title\n :param author: str, author name\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.create_table()\n >>> book_db.add_book('book1', 'author')\n \"\"\"",
"test_class": "BookManagementDBTestAddBook",
"test_code": "class BookManagementDBTestAddBook(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n\n def test_add_book(self):\n title = \"Introduction to Python\"\n author = \"John Smith\"\n self.db.add_book(title, author)\n\n # Check if the book was added correctly\n self.cursor.execute(\"SELECT title, author, available FROM books WHERE id=1\")\n result = self.cursor.fetchone()\n self.assertIsNotNone(result)\n self.assertEqual(result[0], title)\n self.assertEqual(result[1], author)\n self.assertEqual(result[2], 1)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)",
"solution_code": "def add_book(self, title, author):\n self.cursor.execute('''\n INSERT INTO books (title, author, available)\n VALUES (?, ?, 1)\n ''', (title, author))\n self.connection.commit()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.connection",
"self.cursor"
],
"method_dependencies": []
}
},
{
"method_name": "remove_book",
"method_description": "def remove_book(self, book_id):\n \"\"\"\n Removes a book from the database based on the given book ID.\n :param book_id: int\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.remove_book(1)\n \"\"\"",
"test_class": "BookManagementDBTestRemoveBook",
"test_code": "class BookManagementDBTestRemoveBook(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n # Add a book for testing removal\n self.db.add_book(\"Book to Remove\", \"John Doe\")\n\n def test_remove_book(self):\n self.db.remove_book(1)\n\n # Check if the book was removed correctly\n self.cursor.execute(\"SELECT * FROM books WHERE id=1\")\n result = self.cursor.fetchone()\n self.assertIsNone(result)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)",
"solution_code": "def remove_book(self, book_id):\n self.cursor.execute('''\n DELETE FROM books WHERE id = ?\n ''', (book_id,))\n self.connection.commit()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.connection",
"self.cursor"
],
"method_dependencies": []
}
},
{
"method_name": "borrow_book",
"method_description": "def borrow_book(self, book_id):\n \"\"\"\n Marks a book as borrowed in the database based on the given book ID.\n :param book_id: int\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.borrow_book(1)\n \"\"\"",
"test_class": "BookManagementDBTestBorrowBook",
"test_code": "class BookManagementDBTestBorrowBook(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n # Add a book for testing borrowing\n self.db.add_book(\"Book to Borrow\", \"Jane Smith\")\n\n def test_borrow_book(self):\n self.db.borrow_book(1)\n\n # Check if the book was marked as unavailable\n self.cursor.execute(\"SELECT available FROM books WHERE id=1\")\n result = self.cursor.fetchone()\n self.assertEqual(result[0], 0)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)",
"solution_code": "def borrow_book(self, book_id):\n self.cursor.execute('''\n UPDATE books SET available = 0 WHERE id = ?\n ''', (book_id,))\n self.connection.commit()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.connection",
"self.cursor"
],
"method_dependencies": []
}
},
{
"method_name": "return_book",
"method_description": "def return_book(self, book_id):\n \"\"\"\n Marks a book as returned in the database based on the given book ID.\n :param book_id: int\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.return_book(1)\n \"\"\"",
"test_class": "BookManagementDBTestReturnBook",
"test_code": "class BookManagementDBTestReturnBook(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n # Add a book for testing returning\n self.db.add_book(\"Book to Return\", \"James Smith\")\n self.db.borrow_book(1) # Mark the book as borrowed\n\n def test_return_book(self):\n self.db.return_book(1)\n\n # Check if the book was marked as available again\n self.cursor.execute(\"SELECT available FROM books WHERE id=1\")\n result = self.cursor.fetchone()\n self.assertEqual(result[0], 1)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)",
"solution_code": "def return_book(self, book_id):\n self.cursor.execute('''\n UPDATE books SET available = 1 WHERE id = ?\n ''', (book_id,))\n self.connection.commit()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.connection",
"self.cursor"
],
"method_dependencies": []
}
},
{
"method_name": "search_books",
"method_description": "def search_books(self):\n \"\"\"\n Retrieves all books from the database and returns their information.\n :return books: list[tuple], the information of all books in database\n >>> book_db.search_books()\n [(1, 'book1', 'author', 1)]\n \"\"\"",
"test_class": "BookManagementDBTestSearchBooks",
"test_code": "class BookManagementDBTestSearchBooks(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n # Add some books for testing search\n self.db.add_book(\"Book 1\", \"Author 1\")\n self.db.add_book(\"Book 2\", \"Author 2\")\n self.db.add_book(\"Book 3\", \"Author 3\")\n\n def test_search_books(self):\n books = self.db.search_books()\n\n # Ensure that all books were retrieved\n self.assertEqual(len(books), 3)\n\n # Ensure that the correct book information is retrieved\n self.assertEqual(books[0][1], \"Book 1\")\n self.assertEqual(books[1][2], \"Author 2\")\n self.assertEqual(books[2][3], 1)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)",
"solution_code": "def search_books(self):\n self.cursor.execute('''\n SELECT * FROM books\n ''')\n books = self.cursor.fetchall()\n return books",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.cursor"
],
"method_dependencies": []
}
}
] | BookManagementDB | [
"BookManagementDBTestCreateTable",
"BookManagementDBTestAddBook",
"BookManagementDBTestRemoveBook",
"BookManagementDBTestBorrowBook",
"BookManagementDBTestReturnBook",
"BookManagementDBTestSearchBooks"
] | class BookManagementDB:
def __init__(self, db_name):
"""
Initializes the class by creating a database connection and cursor,
and creates the book table if it does not already exist
:param db_name: str, the name of db file
"""
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
self.create_table()
| [
"self.connection",
"self.cursor"
] |
ClassEval_15 | class BoyerMooreSearch:
"""
his is a class that implements the Boyer-Moore algorithm for string searching, which is used to find occurrences of a pattern within a given text.
"""
def __init__(self, text, pattern):
"""
Initializes the BoyerMooreSearch class with the given text and pattern.
:param text: The text to be searched, str.
:param pattern: The pattern to be searched for, str.
"""
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(text), len(pattern)
def match_in_pattern(self, char):
"""
Finds the rightmost occurrence of a character in the pattern.
:param char: The character to be searched for, str.
:return: The index of the rightmost occurrence of the character in the pattern, int.
>>> boyerMooreSearch = BoyerMooreSearch("ABAABA", "AB")
>>> boyerMooreSearch.match_in_pattern("A")
0
"""
def mismatch_in_text(self, currentPos):
"""
Determines the position of the first dismatch between the pattern and the text.
:param currentPos: The current position in the text, int.
:return: The position of the first dismatch between the pattern and the text, int,otherwise -1.
>>> boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABC")
>>> boyerMooreSearch.mismatch_in_text(0)
2
"""
def bad_character_heuristic(self):
"""
Finds all occurrences of the pattern in the text.
:return: A list of all positions of the pattern in the text, list.
>>> boyerMooreSearch = BoyerMooreSearch("ABAABA", "AB")
>>> boyerMooreSearch.bad_character_heuristic()
[0, 3]
""" | import unittest
class BoyerMooreSearchTestMatchInPattern(unittest.TestCase):
def test_match_in_pattern(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "AB")
self.assertEqual(boyerMooreSearch.match_in_pattern("A"), 0)
def test_match_in_pattern_2(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABAB")
self.assertEqual(boyerMooreSearch.match_in_pattern("B"), 3)
def test_match_in_pattern_3(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABCABC")
self.assertEqual(boyerMooreSearch.match_in_pattern("C"), 5)
def test_match_in_pattern_4(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABCABC")
self.assertEqual(boyerMooreSearch.match_in_pattern("D"), -1)
def test_match_in_pattern_5(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABCABC")
self.assertEqual(boyerMooreSearch.match_in_pattern("E"), -1)
class BoyerMooreSearchTestMismatchInText(unittest.TestCase):
def test_mismatch_in_text(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "AB")
self.assertEqual(boyerMooreSearch.mismatch_in_text(0), -1)
def test_mismatch_in_text_2(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABC")
self.assertEqual(boyerMooreSearch.mismatch_in_text(0), 2)
def test_mismatch_in_text_3(self):
boyerMooreSearch = BoyerMooreSearch("AAAA", "ABC")
self.assertEqual(boyerMooreSearch.mismatch_in_text(0), 2)
def test_mismatch_in_text_4(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "")
self.assertEqual(boyerMooreSearch.mismatch_in_text(0), -1)
def test_mismatch_in_text_5(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABC")
self.assertEqual(boyerMooreSearch.mismatch_in_text(3), 5)
class BoyerMooreSearchTestBadCharacterHeuristic(unittest.TestCase):
def test_bad_character_heuristic(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "AB")
self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 3])
def test_bad_character_heuristic_2(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABC")
self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [])
def test_bad_character_heuristic_3(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "")
self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 1, 2, 3, 4, 5, 6])
def test_bad_character_heuristic_4(self):
boyerMooreSearch = BoyerMooreSearch("ABACABA", "ABA")
self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 4])
def test_bad_character_heuristic_5(self):
boyerMooreSearch = BoyerMooreSearch("ABACABA", "ABAC")
self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0])
class BoyerMooreSearchTestMain(unittest.TestCase):
def test_main(self):
boyerMooreSearch = BoyerMooreSearch("ABAABA", "AB")
self.assertEqual(boyerMooreSearch.match_in_pattern("A"), 0)
self.assertEqual(boyerMooreSearch.mismatch_in_text(0), -1)
self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 3]) | class BoyerMooreSearch:
def __init__(self, text, pattern):
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(text), len(pattern)
def match_in_pattern(self, char):
for i in range(self.patLen - 1, -1, -1):
if char == self.pattern[i]:
return i
return -1
def mismatch_in_text(self, currentPos):
for i in range(self.patLen - 1, -1, -1):
if self.pattern[i] != self.text[currentPos + i]:
return currentPos + i
return -1
def bad_character_heuristic(self):
positions = []
for i in range(self.textLen - self.patLen + 1):
mismatch_index = self.mismatch_in_text(i)
if mismatch_index == -1:
positions.append(i)
else:
match_index = self.match_in_pattern(self.text[mismatch_index])
i = (mismatch_index - match_index)
return positions | [] | """
his is a class that implements the Boyer-Moore algorithm for string searching, which is used to find occurrences of a pattern within a given text.
"""
| [
{
"method_name": "match_in_pattern",
"method_description": "def match_in_pattern(self, char):\n \"\"\"\n Finds the rightmost occurrence of a character in the pattern.\n :param char: The character to be searched for, str.\n :return: The index of the rightmost occurrence of the character in the pattern, int.\n >>> boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n >>> boyerMooreSearch.match_in_pattern(\"A\")\n 0\n\n \"\"\"",
"test_class": "BoyerMooreSearchTestMatchInPattern",
"test_code": "class BoyerMooreSearchTestMatchInPattern(unittest.TestCase):\n def test_match_in_pattern(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"A\"), 0)\n\n def test_match_in_pattern_2(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABAB\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"B\"), 3)\n\n def test_match_in_pattern_3(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABCABC\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"C\"), 5)\n\n def test_match_in_pattern_4(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABCABC\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"D\"), -1)\n\n def test_match_in_pattern_5(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABCABC\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"E\"), -1)",
"solution_code": "def match_in_pattern(self, char):\n for i in range(self.patLen - 1, -1, -1):\n if char == self.pattern[i]:\n return i\n return -1",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.patLen",
"self.pattern"
],
"method_dependencies": []
}
},
{
"method_name": "mismatch_in_text",
"method_description": "def mismatch_in_text(self, currentPos):\n \"\"\"\n Determines the position of the first dismatch between the pattern and the text.\n :param currentPos: The current position in the text, int.\n :return: The position of the first dismatch between the pattern and the text, int,otherwise -1.\n >>> boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABC\")\n >>> boyerMooreSearch.mismatch_in_text(0)\n 2\n\n \"\"\"",
"test_class": "BoyerMooreSearchTestMismatchInText",
"test_code": "class BoyerMooreSearchTestMismatchInText(unittest.TestCase):\n def test_mismatch_in_text(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(0), -1)\n\n def test_mismatch_in_text_2(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABC\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(0), 2)\n\n def test_mismatch_in_text_3(self):\n boyerMooreSearch = BoyerMooreSearch(\"AAAA\", \"ABC\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(0), 2)\n\n def test_mismatch_in_text_4(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(0), -1)\n\n def test_mismatch_in_text_5(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABC\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(3), 5)",
"solution_code": "def mismatch_in_text(self, currentPos):\n for i in range(self.patLen - 1, -1, -1):\n if self.pattern[i] != self.text[currentPos + i]:\n return currentPos + i\n return -1",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.patLen",
"self.pattern",
"self.text"
],
"method_dependencies": []
}
},
{
"method_name": "bad_character_heuristic",
"method_description": "def bad_character_heuristic(self):\n \"\"\"\n Finds all occurrences of the pattern in the text.\n :return: A list of all positions of the pattern in the text, list.\n >>> boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n >>> boyerMooreSearch.bad_character_heuristic()\n [0, 3]\n\n \"\"\"",
"test_class": "BoyerMooreSearchTestBadCharacterHeuristic",
"test_code": "class BoyerMooreSearchTestBadCharacterHeuristic(unittest.TestCase):\n def test_bad_character_heuristic(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 3])\n\n def test_bad_character_heuristic_2(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABC\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [])\n\n def test_bad_character_heuristic_3(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 1, 2, 3, 4, 5, 6])\n\n def test_bad_character_heuristic_4(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABACABA\", \"ABA\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 4])\n\n def test_bad_character_heuristic_5(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABACABA\", \"ABAC\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0])",
"solution_code": "def bad_character_heuristic(self):\n positions = []\n for i in range(self.textLen - self.patLen + 1):\n mismatch_index = self.mismatch_in_text(i)\n if mismatch_index == -1:\n positions.append(i)\n else:\n match_index = self.match_in_pattern(self.text[mismatch_index])\n i = (mismatch_index - match_index)\n return positions",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.patLen",
"self.text",
"self.textLen"
],
"method_dependencies": [
"match_in_pattern",
"mismatch_in_text"
]
}
}
] | BoyerMooreSearch | [
"BoyerMooreSearchTestMatchInPattern",
"BoyerMooreSearchTestMismatchInText",
"BoyerMooreSearchTestBadCharacterHeuristic",
"BoyerMooreSearchTestMain"
] | class BoyerMooreSearch:
def __init__(self, text, pattern):
"""
Initializes the BoyerMooreSearch class with the given text and pattern.
:param text: The text to be searched, str.
:param pattern: The pattern to be searched for, str.
"""
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(text), len(pattern)
| [
"self.patLen",
"self.pattern",
"self.text",
"self.textLen"
] |
ClassEval_16 | class Calculator:
"""
This is a class for a calculator, capable of performing basic arithmetic calculations on numerical expressions using the operators +, -, *, /, and ^ (exponentiation).
"""
def __init__(self):
"""
Initialize the operations performed by the five operators'+','-','*','/','^'
"""
self.operators = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y,
'^': lambda x, y: x ** y
}
def calculate(self, expression):
"""
Calculate the value of a given expression
:param expression: string, given expression
:return:If successful, returns the value of the expression; otherwise, returns None
>>> calculator = Calculator()
>>> calculator.calculate('1+2-3')
0.0
"""
def precedence(self, operator):
"""
Returns the priority of the specified operator, where the higher the priority, the greater the assignment. The priority of '^' is greater than '/' and '*', and the priority of '/' and '*' is greater than '+' and '-'
:param operator: string, given operator
:return: int, the priority of the given operator, otherwise return 0
>>> calculator = Calculator()
>>> calculator.precedence('+')
1
>>> calculator.precedence('^')
3
"""
def apply_operator(self, operand_stack, operator_stack):
"""
Use the operator at the top of the operator stack to perform the operation on the two numbers at the top of the operator stack, and store the results at the top of the operator stack
:param operand_stack:list
:param operator_stack:list
:return: the updated operand_stack and operator_stack
>>> calculator = Calculator()
>>> calculator.apply_operator([1, 2, 3], ['+', '-'])
([1, -1], ['-'])
""" | import unittest
class CalculatorTestCalculate(unittest.TestCase):
def test_calculate_1(self):
calculator = Calculator()
res = calculator.calculate('1+2')
self.assertEqual(res, 3)
def test_calculate_2(self):
calculator = Calculator()
res = calculator.calculate('1+2*3')
self.assertEqual(res, 7)
def test_calculate_3(self):
calculator = Calculator()
res = calculator.calculate('1+2*3+4')
self.assertEqual(res, 11)
def test_calculate_4(self):
calculator = Calculator()
res = calculator.calculate('1+2^3*2+4*5')
self.assertEqual(res, 37)
def test_calculate_5(self):
calculator = Calculator()
res = calculator.calculate('1+2+3')
self.assertEqual(res, 6)
def test_calculate_6(self):
calculator = Calculator()
res = calculator.calculate('(1+2)+3')
self.assertEqual(res, 6)
def test_calculate_7(self):
calculator = Calculator()
res = calculator.calculate('')
self.assertEqual(res, None)
def test_calculate_8(self):
calculator = Calculator()
res = calculator.calculate('1+2?')
self.assertEqual(res, 3)
class CalculatorTestPrecedence(unittest.TestCase):
def test_precedence_1(self):
calculator = Calculator()
res1 = calculator.precedence('+')
res2 = calculator.precedence('-')
self.assertEqual(res1, res2)
def test_precedence_2(self):
calculator = Calculator()
res1 = calculator.precedence('*')
res2 = calculator.precedence('/')
self.assertEqual(res1, res2)
def test_precedence_3(self):
calculator = Calculator()
res1 = calculator.precedence('+')
res2 = calculator.precedence('/')
self.assertNotEqual(res1, res2)
def test_precedence_4(self):
calculator = Calculator()
res1 = calculator.precedence('+')
res2 = calculator.precedence('/')
self.assertNotEqual(res1, res2)
def test_precedence_5(self):
calculator = Calculator()
res1 = calculator.precedence('*')
res2 = calculator.precedence('-')
self.assertNotEqual(res1, res2)
class CalculatorTestApplyOperator(unittest.TestCase):
def test_apply_operator_1(self):
calculator = Calculator()
operand_stack = [1, 2, 3]
operator_stack = ['+', '-']
calculator.apply_operator(operand_stack, operator_stack)
self.assertEqual(operand_stack, [1, -1])
self.assertEqual(operator_stack, ['+'])
def test_apply_operator_2(self):
calculator = Calculator()
operand_stack = [1, 2, 3]
operator_stack = ['+', '*']
calculator.apply_operator(operand_stack, operator_stack)
self.assertEqual(operand_stack, [1, 6])
self.assertEqual(operator_stack, ['+'])
def test_apply_operator_3(self):
calculator = Calculator()
operand_stack = [6, 3, 3]
operator_stack = ['+', '/']
calculator.apply_operator(operand_stack, operator_stack)
self.assertEqual(operand_stack, [6, 1])
self.assertEqual(operator_stack, ['+'])
def test_apply_operator_4(self):
calculator = Calculator()
operand_stack = [1, 2, 3]
operator_stack = ['+', '^']
calculator.apply_operator(operand_stack, operator_stack)
self.assertEqual(operand_stack, [1, 8])
self.assertEqual(operator_stack, ['+'])
def test_apply_operator_5(self):
calculator = Calculator()
operand_stack = [1, 2, 3]
operator_stack = ['+', '+']
calculator.apply_operator(operand_stack, operator_stack)
self.assertEqual(operand_stack, [1, 5])
self.assertEqual(operator_stack, ['+'])
class CalculatorTest(unittest.TestCase):
def test_calculator(self):
calculator = Calculator()
res = calculator.calculate('1+2')
self.assertEqual(res, 3)
res1 = calculator.precedence('+')
res2 = calculator.precedence('-')
res3 = calculator.precedence('*')
res4 = calculator.precedence('/')
res5 = calculator.precedence('^')
self.assertEqual(res1, res2)
self.assertEqual(res3, res4)
self.assertGreater(res3, res1)
self.assertGreater(res5, res3)
operand_stack = [1, 2, 3]
operator_stack = ['+', '-']
calculator.apply_operator(operand_stack, operator_stack)
self.assertEqual(operand_stack, [1, -1])
self.assertEqual(operator_stack, ['+']) | class Calculator:
def __init__(self):
self.operators = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y,
'^': lambda x, y: x ** y
}
def calculate(self, expression):
operand_stack = []
operator_stack = []
num_buffer = ''
for char in expression:
if char.isdigit() or char == '.':
num_buffer += char
else:
if num_buffer:
operand_stack.append(float(num_buffer))
num_buffer = ''
if char in '+-*/^':
while (
operator_stack and
operator_stack[-1] != '(' and
self.precedence(operator_stack[-1]) >= self.precedence(char)
):
operand_stack, operator_stack = self.apply_operator(operand_stack, operator_stack)
operator_stack.append(char)
elif char == '(':
operator_stack.append(char)
elif char == ')':
while operator_stack and operator_stack[-1] != '(':
operand_stack, operator_stack = self.apply_operator(operand_stack, operator_stack)
operator_stack.pop()
if num_buffer:
operand_stack.append(float(num_buffer))
while operator_stack:
operand_stack, operator_stack = self.apply_operator(operand_stack, operator_stack)
return operand_stack[-1] if operand_stack else None
def precedence(self, operator):
precedences = {
'+': 1,
'-': 1,
'*': 2,
'/': 2,
'^': 3
}
return precedences.get(operator, 0)
def apply_operator(self, operand_stack, operator_stack):
operator = operator_stack.pop()
if operator == '^':
operand2 = operand_stack.pop()
operand1 = operand_stack.pop()
result = self.operators[operator](operand1, operand2)
operand_stack.append(result)
else:
operand2 = operand_stack.pop()
operand1 = operand_stack.pop()
result = self.operators[operator](operand1, operand2)
operand_stack.append(result)
return operand_stack, operator_stack | [] | """
This is a class for a calculator, capable of performing basic arithmetic calculations on numerical expressions using the operators +, -, *, /, and ^ (exponentiation).
"""
| [
{
"method_name": "calculate",
"method_description": "def calculate(self, expression):\n \"\"\"\n Calculate the value of a given expression\n :param expression: string, given expression\n :return:If successful, returns the value of the expression; otherwise, returns None\n >>> calculator = Calculator()\n >>> calculator.calculate('1+2-3')\n 0.0\n \"\"\"",
"test_class": "CalculatorTestCalculate",
"test_code": "class CalculatorTestCalculate(unittest.TestCase):\n def test_calculate_1(self):\n calculator = Calculator()\n res = calculator.calculate('1+2')\n self.assertEqual(res, 3)\n\n def test_calculate_2(self):\n calculator = Calculator()\n res = calculator.calculate('1+2*3')\n self.assertEqual(res, 7)\n\n def test_calculate_3(self):\n calculator = Calculator()\n res = calculator.calculate('1+2*3+4')\n self.assertEqual(res, 11)\n\n def test_calculate_4(self):\n calculator = Calculator()\n res = calculator.calculate('1+2^3*2+4*5')\n self.assertEqual(res, 37)\n\n def test_calculate_5(self):\n calculator = Calculator()\n res = calculator.calculate('1+2+3')\n self.assertEqual(res, 6)\n\n def test_calculate_6(self):\n calculator = Calculator()\n res = calculator.calculate('(1+2)+3')\n self.assertEqual(res, 6)\n\n def test_calculate_7(self):\n calculator = Calculator()\n res = calculator.calculate('')\n self.assertEqual(res, None)\n\n def test_calculate_8(self):\n calculator = Calculator()\n res = calculator.calculate('1+2?')\n self.assertEqual(res, 3)",
"solution_code": "def calculate(self, expression):\n operand_stack = []\n operator_stack = []\n num_buffer = ''\n\n for char in expression:\n if char.isdigit() or char == '.':\n num_buffer += char\n else:\n if num_buffer:\n operand_stack.append(float(num_buffer))\n num_buffer = ''\n\n if char in '+-*/^':\n while (\n operator_stack and\n operator_stack[-1] != '(' and\n self.precedence(operator_stack[-1]) >= self.precedence(char)\n ):\n operand_stack, operator_stack = self.apply_operator(operand_stack, operator_stack)\n\n operator_stack.append(char)\n elif char == '(':\n operator_stack.append(char)\n elif char == ')':\n while operator_stack and operator_stack[-1] != '(':\n operand_stack, operator_stack = self.apply_operator(operand_stack, operator_stack)\n\n operator_stack.pop()\n\n if num_buffer:\n operand_stack.append(float(num_buffer))\n\n while operator_stack:\n operand_stack, operator_stack = self.apply_operator(operand_stack, operator_stack)\n\n return operand_stack[-1] if operand_stack else None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"precedence",
"apply_operator"
]
}
},
{
"method_name": "precedence",
"method_description": "def precedence(self, operator):\n \"\"\"\n Returns the priority of the specified operator, where the higher the priority, the greater the assignment. The priority of '^' is greater than '/' and '*', and the priority of '/' and '*' is greater than '+' and '-'\n :param operator: string, given operator\n :return: int, the priority of the given operator, otherwise return 0\n >>> calculator = Calculator()\n >>> calculator.precedence('+')\n 1\n >>> calculator.precedence('^')\n 3\n \"\"\"",
"test_class": "CalculatorTestPrecedence",
"test_code": "class CalculatorTestPrecedence(unittest.TestCase):\n def test_precedence_1(self):\n calculator = Calculator()\n res1 = calculator.precedence('+')\n res2 = calculator.precedence('-')\n self.assertEqual(res1, res2)\n\n def test_precedence_2(self):\n calculator = Calculator()\n res1 = calculator.precedence('*')\n res2 = calculator.precedence('/')\n self.assertEqual(res1, res2)\n\n def test_precedence_3(self):\n calculator = Calculator()\n res1 = calculator.precedence('+')\n res2 = calculator.precedence('/')\n self.assertNotEqual(res1, res2)\n\n def test_precedence_4(self):\n calculator = Calculator()\n res1 = calculator.precedence('+')\n res2 = calculator.precedence('/')\n self.assertNotEqual(res1, res2)\n\n def test_precedence_5(self):\n calculator = Calculator()\n res1 = calculator.precedence('*')\n res2 = calculator.precedence('-')\n self.assertNotEqual(res1, res2)",
"solution_code": "def precedence(self, operator):\n precedences = {\n '+': 1,\n '-': 1,\n '*': 2,\n '/': 2,\n '^': 3\n }\n return precedences.get(operator, 0)",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "apply_operator",
"method_description": "def apply_operator(self, operand_stack, operator_stack):\n \"\"\"\n Use the operator at the top of the operator stack to perform the operation on the two numbers at the top of the operator stack, and store the results at the top of the operator stack\n :param operand_stack:list\n :param operator_stack:list\n :return: the updated operand_stack and operator_stack\n >>> calculator = Calculator()\n >>> calculator.apply_operator([1, 2, 3], ['+', '-'])\n ([1, -1], ['-'])\n \"\"\"",
"test_class": "CalculatorTestApplyOperator",
"test_code": "class CalculatorTestApplyOperator(unittest.TestCase):\n def test_apply_operator_1(self):\n calculator = Calculator()\n operand_stack = [1, 2, 3]\n operator_stack = ['+', '-']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [1, -1])\n self.assertEqual(operator_stack, ['+'])\n\n def test_apply_operator_2(self):\n calculator = Calculator()\n operand_stack = [1, 2, 3]\n operator_stack = ['+', '*']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [1, 6])\n self.assertEqual(operator_stack, ['+'])\n\n def test_apply_operator_3(self):\n calculator = Calculator()\n operand_stack = [6, 3, 3]\n operator_stack = ['+', '/']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [6, 1])\n self.assertEqual(operator_stack, ['+'])\n\n def test_apply_operator_4(self):\n calculator = Calculator()\n operand_stack = [1, 2, 3]\n operator_stack = ['+', '^']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [1, 8])\n self.assertEqual(operator_stack, ['+'])\n\n def test_apply_operator_5(self):\n calculator = Calculator()\n operand_stack = [1, 2, 3]\n operator_stack = ['+', '+']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [1, 5])\n self.assertEqual(operator_stack, ['+'])",
"solution_code": "def apply_operator(self, operand_stack, operator_stack):\n operator = operator_stack.pop()\n if operator == '^':\n operand2 = operand_stack.pop()\n operand1 = operand_stack.pop()\n result = self.operators[operator](operand1, operand2)\n operand_stack.append(result)\n else:\n operand2 = operand_stack.pop()\n operand1 = operand_stack.pop()\n result = self.operators[operator](operand1, operand2)\n operand_stack.append(result)\n return operand_stack, operator_stack",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.operators"
],
"method_dependencies": []
}
}
] | Calculator | [
"CalculatorTestCalculate",
"CalculatorTestPrecedence",
"CalculatorTestApplyOperator",
"CalculatorTest"
] | class Calculator:
def __init__(self):
"""
Initialize the operations performed by the five operators'+','-','*','/','^'
"""
self.operators = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y,
'^': lambda x, y: x ** y
}
| [
"self.operators"
] |
ClassEval_17 | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
"""
Initialize the calendar with an empty list of events.
"""
self.events = []
def add_event(self, event):
"""
Add an event to the calendar.
:param event: The event to be added to the calendar,dict.
>>> calendar = CalendarUtil()
>>> calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})
>>> calendar.events
[{'date': datetime.datetime(2023, 1, 1, 0, 0), 'start_time': datetime.datetime(2023, 1, 1, 0, 0), 'end_time': datetime.datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]
"""
def remove_event(self, event):
"""
Remove an event from the calendar.
:param event: The event to be removed from the calendar,dict.
>>> calendar = CalendarUtil()
>>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]
>>> calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})
>>> calendar.events
[]
"""
def get_events(self, date):
"""
Get all events on a given date.
:param date: The date to get events for,datetime.
:return: A list of events on the given date,list.
>>> calendar = CalendarUtil()
>>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]
>>> calendar.get_events(datetime(2023, 1, 1, 0, 0))
[{'date': datetime.datetime(2023, 1, 1, 0, 0), 'start_time': datetime.datetime(2023, 1, 1, 0, 0), 'end_time': datetime.datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]
"""
def is_available(self, start_time, end_time):
"""
Check if the calendar is available for a given time slot.
:param start_time: The start time of the time slot,datetime.
:param end_time: The end time of the time slot,datetime.
:return: True if the calendar is available for the given time slot, False otherwise,bool.
>>> calendar = CalendarUtil()
>>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]
>>> calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 1, 0))
False
"""
def get_available_slots(self, date):
"""
Get all available time slots on a given date.
:param date: The date to get available time slots for,datetime.
:return: A list of available time slots on the given date,list.
>>> calendar = CalendarUtil()
>>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]
>>> calendar.get_available_slots(datetime(2023, 1, 1))
[(datetime.datetime(2023, 1, 1, 23, 0), datetime.datetime(2023, 1, 2, 0, 0))]
"""
def get_upcoming_events(self, num_events):
"""
Get the next n upcoming events from a given date.
:param date: The date to get upcoming events from,datetime.
:param n: The number of upcoming events to get,int.
:return: A list of the next n upcoming events from the given date,list.
>>> calendar = CalendarUtil()
>>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'},{'date': datetime(2023, 1, 2, 0, 0),'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year 2'}]
>>> calendar.get_upcoming_events(1)
[{'date': datetime.datetime(2023, 1, 1, 0, 0), 'start_time': datetime.datetime(2023, 1, 1, 0, 0), 'end_time': datetime.datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}, {'date': datetime.datetime(2023, 1, 2, 0, 0), 'end_time': datetime.datetime(2023, 1, 2, 1, 0), 'description': 'New Year 2'}]
""" | import unittest
from datetime import datetime
class CalendarTestAddEvent(unittest.TestCase):
def test_add_event(self):
calendar = CalendarUtil()
calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})
self.assertEqual(calendar.events, [
{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])
def test_add_event_2(self):
calendar = CalendarUtil()
calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})
calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})
self.assertEqual(calendar.events, [
{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'},
{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])
def test_add_event_3(self):
calendar = CalendarUtil()
calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'})
self.assertEqual(calendar.events, [
{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}])
def test_add_event_4(self):
calendar = CalendarUtil()
calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'})
self.assertEqual(calendar.events, [
{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'}])
def test_add_event_5(self):
calendar = CalendarUtil()
calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 20, 0), 'description': 'New Year'})
self.assertEqual(calendar.events, [
{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 20, 0), 'description': 'New Year'}])
class CalendarTestRemoveEvent(unittest.TestCase):
def test_remove_event(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]
calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})
self.assertEqual(calendar.events, [])
def test_remove_event_2(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'},
{'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),
'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]
calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})
self.assertEqual(calendar.events, [
{'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),
'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}])
def test_remove_event_3(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'},
{'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),
'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]
calendar.remove_event({'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),
'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'})
self.assertEqual(calendar.events, [
{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])
def test_remove_event_4(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'},
{'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),
'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]
calendar.remove_event({'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),
'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'})
self.assertEqual(calendar.events, [
{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}])
def test_remove_event_5(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'},
{'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),
'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]
calendar.remove_event({'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),
'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'})
self.assertEqual(calendar.events, [
{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'}])
def test_remove_event_6(self):
calendar = CalendarUtil()
calendar.events = []
calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})
self.assertEqual(calendar.events, [])
class CalendarTestGetEvents(unittest.TestCase):
def test_get_events(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]
self.assertEqual(calendar.get_events(datetime(2023, 1, 1)), [
{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])
def test_get_events_2(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]
self.assertEqual(calendar.get_events(datetime(2023, 1, 2)), [])
class CalendarTestIsAvailable(unittest.TestCase):
def test_is_available(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]
self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 1, 0)), False)
def test_is_available_2(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]
self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 1, 0), datetime(2023, 1, 1, 2, 0)), True)
def test_is_available_3(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]
self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 0, 30)), False)
def test_is_available_4(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]
self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 30), datetime(2023, 1, 1, 1, 0)), False)
def test_is_available_5(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]
self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 1, 0), datetime(2023, 1, 1, 1, 30)), True)
class CalendarTestGetAvailableSlots(unittest.TestCase):
def test_get_available_slots(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]
self.assertEqual(calendar.get_available_slots(datetime(2023, 1, 1)),
[(datetime(2023, 1, 1, 23, 0), datetime(2023, 1, 2, 0, 0))])
def test_get_available_slots_2(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 1, 0),
'end_time': datetime(2023, 1, 1, 2, 0), 'description': 'New Year'}]
self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 23)
def test_get_available_slots_3(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),
'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]
self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 24)
def test_get_available_slots_4(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),
'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]
self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 24)
def test_get_available_slots_5(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),
'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]
self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 24)
class CalendarTestGetUpcomingEvents(unittest.TestCase):
def test_get_upcoming_events(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]
self.assertEqual(calendar.get_upcoming_events(1), [])
def test_get_upcoming_events_2(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 1, 0),
'end_time': datetime(2023, 1, 1, 2, 0), 'description': 'New Year'}]
self.assertEqual(calendar.get_upcoming_events(1), [])
def test_get_upcoming_events_3(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),
'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]
self.assertEqual(calendar.get_upcoming_events(1), [])
def test_get_upcoming_events_4(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),
'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]
self.assertEqual(calendar.get_upcoming_events(2), [])
def test_get_upcoming_events_5(self):
calendar = CalendarUtil()
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'},
{'date': datetime(2024, 1, 2, 0, 0), 'start_time': datetime(2024, 1, 2, 1, 0),
'end_time': datetime(2024, 1, 2, 2, 0),
'description': 'New Year 2'}]
self.assertEqual(calendar.get_upcoming_events(1), [
{'date': datetime(2024, 1, 2, 0, 0), 'start_time': datetime(2024, 1, 2, 1, 0),
'end_time': datetime(2024, 1, 2, 2, 0), 'description': 'New Year 2'}])
class CalendarTestMain(unittest.TestCase):
def test_main(self):
calendar = CalendarUtil()
calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})
self.assertEqual(calendar.events, [
{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])
calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})
self.assertEqual(calendar.events, [])
calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]
self.assertEqual(calendar.get_events(datetime(2023, 1, 1)), [
{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),
'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}])
self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 1, 0)), False)
self.assertEqual(calendar.get_available_slots(datetime(2023, 1, 1)),
[(datetime(2023, 1, 1, 23, 0), datetime(2023, 1, 2, 0, 0))])
self.assertEqual(calendar.get_upcoming_events(1), []) | from datetime import datetime, timedelta
class CalendarUtil:
def __init__(self):
self.events = []
def add_event(self, event):
self.events.append(event)
def remove_event(self, event):
if event in self.events:
self.events.remove(event)
def get_events(self, date):
events_on_date = []
for event in self.events:
if event['date'].date() == date.date():
events_on_date.append(event)
return events_on_date
def is_available(self, start_time, end_time):
for event in self.events:
if start_time < event['end_time'] and end_time > event['start_time']:
return False
return True
def get_available_slots(self, date):
available_slots = []
start_time = datetime(date.year, date.month, date.day, 0, 0)
end_time = datetime(date.year, date.month, date.day, 23, 59)
while start_time < end_time:
slot_end_time = start_time + timedelta(minutes=60)
if self.is_available(start_time, slot_end_time):
available_slots.append((start_time, slot_end_time))
start_time += timedelta(minutes=60)
return available_slots
def get_upcoming_events(self, num_events):
now = datetime.now()
upcoming_events = []
for event in self.events:
if event['start_time'] >= now:
upcoming_events.append(event)
if len(upcoming_events) == num_events:
break
return upcoming_events | [
"from datetime import datetime, timedelta"
] | """
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
| [
{
"method_name": "add_event",
"method_description": "def add_event(self, event):\n \"\"\"\n Add an event to the calendar.\n :param event: The event to be added to the calendar,dict.\n >>> calendar = CalendarUtil()\n >>> calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n >>> calendar.events\n [{'date': datetime.datetime(2023, 1, 1, 0, 0), 'start_time': datetime.datetime(2023, 1, 1, 0, 0), 'end_time': datetime.datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n\n \"\"\"",
"test_class": "CalendarTestAddEvent",
"test_code": "class CalendarTestAddEvent(unittest.TestCase):\n def test_add_event(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])\n\n def test_add_event_2(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])\n\n def test_add_event_3(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}])\n\n def test_add_event_4(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'}])\n\n def test_add_event_5(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 20, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 20, 0), 'description': 'New Year'}])",
"solution_code": "def add_event(self, event):\n self.events.append(event)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.events"
],
"method_dependencies": []
}
},
{
"method_name": "remove_event",
"method_description": "def remove_event(self, event):\n \"\"\"\n Remove an event from the calendar.\n :param event: The event to be removed from the calendar,dict.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n >>> calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n >>> calendar.events\n []\n\n \"\"\"",
"test_class": "CalendarTestRemoveEvent",
"test_code": "class CalendarTestRemoveEvent(unittest.TestCase):\n def test_remove_event(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [])\n\n def test_remove_event_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}])\n\n def test_remove_event_3(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])\n\n def test_remove_event_4(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}])\n\n def test_remove_event_5(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'}])\n\n def test_remove_event_6(self):\n calendar = CalendarUtil()\n calendar.events = []\n calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [])",
"solution_code": "def remove_event(self, event):\n if event in self.events:\n self.events.remove(event)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.events"
],
"method_dependencies": []
}
},
{
"method_name": "get_events",
"method_description": "def get_events(self, date):\n \"\"\"\n Get all events on a given date.\n :param date: The date to get events for,datetime.\n :return: A list of events on the given date,list.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n >>> calendar.get_events(datetime(2023, 1, 1, 0, 0))\n [{'date': datetime.datetime(2023, 1, 1, 0, 0), 'start_time': datetime.datetime(2023, 1, 1, 0, 0), 'end_time': datetime.datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n\n \"\"\"",
"test_class": "CalendarTestGetEvents",
"test_code": "class CalendarTestGetEvents(unittest.TestCase):\n def test_get_events(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_events(datetime(2023, 1, 1)), [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])\n\n def test_get_events_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_events(datetime(2023, 1, 2)), [])",
"solution_code": "def get_events(self, date):\n events_on_date = []\n for event in self.events:\n if event['date'].date() == date.date():\n events_on_date.append(event)\n return events_on_date",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.events"
],
"method_dependencies": []
}
},
{
"method_name": "is_available",
"method_description": "def is_available(self, start_time, end_time):\n \"\"\"\n Check if the calendar is available for a given time slot.\n :param start_time: The start time of the time slot,datetime.\n :param end_time: The end time of the time slot,datetime.\n :return: True if the calendar is available for the given time slot, False otherwise,bool.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n >>> calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 1, 0))\n False\n\n \"\"\"",
"test_class": "CalendarTestIsAvailable",
"test_code": "class CalendarTestIsAvailable(unittest.TestCase):\n def test_is_available(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 1, 0)), False)\n\n def test_is_available_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 1, 0), datetime(2023, 1, 1, 2, 0)), True)\n\n def test_is_available_3(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 0, 30)), False)\n\n def test_is_available_4(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 30), datetime(2023, 1, 1, 1, 0)), False)\n\n def test_is_available_5(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 1, 0), datetime(2023, 1, 1, 1, 30)), True)",
"solution_code": "def is_available(self, start_time, end_time):\n for event in self.events:\n if start_time < event['end_time'] and end_time > event['start_time']:\n return False\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.events"
],
"method_dependencies": []
}
},
{
"method_name": "get_available_slots",
"method_description": "def get_available_slots(self, date):\n \"\"\"\n Get all available time slots on a given date.\n :param date: The date to get available time slots for,datetime.\n :return: A list of available time slots on the given date,list.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]\n >>> calendar.get_available_slots(datetime(2023, 1, 1))\n [(datetime.datetime(2023, 1, 1, 23, 0), datetime.datetime(2023, 1, 2, 0, 0))]\n\n \"\"\"",
"test_class": "CalendarTestGetAvailableSlots",
"test_code": "class CalendarTestGetAvailableSlots(unittest.TestCase):\n def test_get_available_slots(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_available_slots(datetime(2023, 1, 1)),\n [(datetime(2023, 1, 1, 23, 0), datetime(2023, 1, 2, 0, 0))])\n\n def test_get_available_slots_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 1, 0),\n 'end_time': datetime(2023, 1, 1, 2, 0), 'description': 'New Year'}]\n self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 23)\n\n def test_get_available_slots_3(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 24)\n\n def test_get_available_slots_4(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 24)\n\n def test_get_available_slots_5(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 24)",
"solution_code": "def get_available_slots(self, date):\n available_slots = []\n start_time = datetime(date.year, date.month, date.day, 0, 0)\n end_time = datetime(date.year, date.month, date.day, 23, 59)\n\n while start_time < end_time:\n slot_end_time = start_time + timedelta(minutes=60)\n if self.is_available(start_time, slot_end_time):\n available_slots.append((start_time, slot_end_time))\n start_time += timedelta(minutes=60)\n\n\n return available_slots",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"is_available"
]
}
},
{
"method_name": "get_upcoming_events",
"method_description": "def get_upcoming_events(self, num_events):\n \"\"\"\n Get the next n upcoming events from a given date.\n :param date: The date to get upcoming events from,datetime.\n :param n: The number of upcoming events to get,int.\n :return: A list of the next n upcoming events from the given date,list.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'},{'date': datetime(2023, 1, 2, 0, 0),'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year 2'}]\n >>> calendar.get_upcoming_events(1)\n [{'date': datetime.datetime(2023, 1, 1, 0, 0), 'start_time': datetime.datetime(2023, 1, 1, 0, 0), 'end_time': datetime.datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}, {'date': datetime.datetime(2023, 1, 2, 0, 0), 'end_time': datetime.datetime(2023, 1, 2, 1, 0), 'description': 'New Year 2'}]\n\n \"\"\"",
"test_class": "CalendarTestGetUpcomingEvents",
"test_code": "class CalendarTestGetUpcomingEvents(unittest.TestCase):\n def test_get_upcoming_events(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_upcoming_events(1), [])\n\n def test_get_upcoming_events_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 1, 0),\n 'end_time': datetime(2023, 1, 1, 2, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_upcoming_events(1), [])\n\n def test_get_upcoming_events_3(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_upcoming_events(1), [])\n\n def test_get_upcoming_events_4(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_upcoming_events(2), [])\n\n def test_get_upcoming_events_5(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'},\n {'date': datetime(2024, 1, 2, 0, 0), 'start_time': datetime(2024, 1, 2, 1, 0),\n 'end_time': datetime(2024, 1, 2, 2, 0),\n 'description': 'New Year 2'}]\n self.assertEqual(calendar.get_upcoming_events(1), [\n {'date': datetime(2024, 1, 2, 0, 0), 'start_time': datetime(2024, 1, 2, 1, 0),\n 'end_time': datetime(2024, 1, 2, 2, 0), 'description': 'New Year 2'}])",
"solution_code": "def get_upcoming_events(self, num_events):\n now = datetime.now()\n upcoming_events = []\n for event in self.events:\n if event['start_time'] >= now:\n upcoming_events.append(event)\n if len(upcoming_events) == num_events:\n break\n return upcoming_events",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.events"
],
"method_dependencies": []
}
}
] | CalendarUtil | [
"CalendarTestAddEvent",
"CalendarTestRemoveEvent",
"CalendarTestGetEvents",
"CalendarTestIsAvailable",
"CalendarTestGetAvailableSlots",
"CalendarTestGetUpcomingEvents",
"CalendarTestMain"
] | class CalendarUtil:
def __init__(self):
"""
Initialize the calendar with an empty list of events.
"""
self.events = []
| [
"self.events"
] |
ClassEval_18 | class CamelCaseMap:
"""
This is a custom class that allows keys to be in camel case style by converting them from underscore style, which provides dictionary-like functionality.
"""
def __init__(self):
"""
Initialize data to an empty dictionary
"""
self._data = {}
def __getitem__(self, key):
"""
Return the value corresponding to the key
:param key:str
:return:str,the value corresponding to the key
>>> camelize_map = CamelCaseMap()
>>> camelize_map['first_name'] = 'John'
>>> camelize_map.__getitem__('first_name')
'John'
"""
def __setitem__(self, key, value):
"""
Set the value corresponding to the key to the specified value
:param key:str
:param value:str, the specified value
:return:None
>>> camelize_map = CamelCaseMap()
>>> camelize_map['first_name'] = 'John'
>>> camelize_map.__setitem__('first_name', 'new name')
camelize_map['first_name'] = 'new name'
"""
def __delitem__(self, key):
"""
Delete the value corresponding to the key
:param key:str
:return:None
>>> camelize_map = CamelCaseMap()
>>> camelize_map['first_name'] = 'John'
>>> camelize_map.__delitem__('first_name')
>>> flag = 'first_name' in camelize_map
flag = False
"""
def __iter__(self):
"""
Returning Iterateable Objects with Own Data
:return:Iterator
>>> camelize_map = CamelCaseMap()
>>> camelize_map['first_name'] = 'John'
>>> camelize_map['last_name'] = 'Doe'
>>> camelize_map['age'] = 30
>>> camelize_map.__iter__()
<dict_keyiterator object at 0x0000026739977C20>
"""
def __len__(self):
"""
Returns the length of the own data
:return:int, length of data
>>> camelize_map = CamelCaseMap()
>>> camelize_map['first_name'] = 'John'
>>> camelize_map['last_name'] = 'Doe'
>>> camelize_map['age'] = 30
>>> camelize_map.__len__()
3
"""
def _convert_key(self, key):
"""
convert key string into camel case
:param key:str
:return:str, converted key string
>>> camelize_map = CamelCaseMap()
>>> camelize_map._convert_key('first_name')
'firstName'
"""
@staticmethod
def _to_camel_case(key):
"""
convert key string into camel case
:param key:str
:return:str, converted key string
>>> camelize_map = CamelCaseMap()
>>> camelize_map._to_camel_case('first_name')
'firstName'
""" | import unittest
class CamelCaseMapTestGetitem(unittest.TestCase):
def test_getitem_1(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
self.assertEqual(camelize_map.__getitem__('first_name'), 'John')
def test_getitem_2(self):
camelize_map = CamelCaseMap()
camelize_map['last_name'] = 'Doe'
self.assertEqual(camelize_map.__getitem__('last_name'), 'Doe')
def test_getitem_3(self):
camelize_map = CamelCaseMap()
camelize_map['age'] = 30
self.assertEqual(camelize_map.__getitem__('age'), 30)
def test_getitem_4(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
self.assertEqual(camelize_map.__getitem__('first_Name'), 'John')
def test_getitem_5(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
self.assertEqual(camelize_map.__getitem__('firstName'), 'John')
class CamelCaseMapTestSetitem(unittest.TestCase):
def test_setitem_1(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
camelize_map.__setitem__('first_name', 'newname')
self.assertEqual(camelize_map['first_name'], 'newname')
def test_setitem_2(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
camelize_map.__setitem__('first_name', 'John')
self.assertEqual(camelize_map['first_name'], 'John')
def test_setitem_3(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
camelize_map.__setitem__('first_Name', 'newname')
self.assertEqual(camelize_map['first_name'], 'newname')
def test_setitem_4(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
camelize_map.__setitem__('firstName', 'newname')
self.assertEqual(camelize_map['first_name'], 'newname')
def test_setitem_5(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
camelize_map.__setitem__('first_name', '')
self.assertEqual(camelize_map['first_name'], '')
class CamelCaseMapTestDelitem(unittest.TestCase):
def test_delitem_1(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
camelize_map['last_name'] = 'Doe'
camelize_map.__delitem__('first_name')
self.assertEqual(camelize_map['last_name'], 'Doe')
def test_delitem_2(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
camelize_map.__delitem__('first_name')
self.assertEqual('first_name' in camelize_map, False)
def test_delitem_3(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
camelize_map.__delitem__('first_Name')
self.assertEqual('first_name' in camelize_map, False)
def test_delitem_4(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
camelize_map.__delitem__('firstName')
self.assertEqual('first_name' in camelize_map, False)
def test_delitem_5(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = ''
camelize_map.__delitem__('first_name')
self.assertEqual('first_name' in camelize_map, False)
class CamelCaseMapTestIter(unittest.TestCase):
def test_iter_1(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
camelize_map['last_name'] = 'Doe'
camelize_map['age'] = 30
lst = ['firstName', 'lastName', 'age']
iter = camelize_map.__iter__()
i = 0
for key in iter:
self.assertEqual(key, lst[i])
i += 1
def test_iter_2(self):
camelize_map = CamelCaseMap()
camelize_map['firstname'] = 'John'
camelize_map['lastname'] = 'Doe'
camelize_map['age'] = 30
lst = ['firstname', 'lastname', 'age']
iter = camelize_map.__iter__()
i = 0
for key in iter:
self.assertEqual(key, lst[i])
i += 1
def test_iter_3(self):
camelize_map = CamelCaseMap()
camelize_map['first_Name'] = 'John'
camelize_map['last_Name'] = 'Doe'
camelize_map['age'] = 30
lst = ['firstName', 'lastName', 'age']
iter = camelize_map.__iter__()
i = 0
for key in iter:
self.assertEqual(key, lst[i])
i += 1
def test_iter_4(self):
camelize_map = CamelCaseMap()
camelize_map['first_Name'] = 'John'
camelize_map['last_Name'] = 'Doe'
lst = ['firstName', 'lastName']
iter = camelize_map.__iter__()
i = 0
for key in iter:
self.assertEqual(key, lst[i])
i += 1
def test_iter_5(self):
camelize_map = CamelCaseMap()
camelize_map['first_Name'] = 'John'
lst = ['firstName']
iter = camelize_map.__iter__()
i = 0
for key in iter:
self.assertEqual(key, lst[i])
i += 1
class CamelCaseMapTestLen(unittest.TestCase):
def test_len_1(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
self.assertEqual(camelize_map.__len__(), 1)
def test_len_2(self):
camelize_map = CamelCaseMap()
camelize_map['last_name'] = 'Doe'
self.assertEqual(camelize_map.__len__(), 1)
def test_len_3(self):
camelize_map = CamelCaseMap()
camelize_map['age'] = 30
self.assertEqual(camelize_map.__len__(), 1)
def test_len_4(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
camelize_map['last_Name'] = 'Doe'
camelize_map['age'] = 30
self.assertEqual(camelize_map.__len__(), 3)
def test_len_5(self):
camelize_map = CamelCaseMap()
self.assertEqual(camelize_map.__len__(), 0)
class CamelCaseMapTestConvertKey(unittest.TestCase):
def test_convert_key_1(self):
camelize_map = CamelCaseMap()
self.assertEqual(camelize_map._convert_key('aaa_bbb'), 'aaaBbb')
def test_convert_key_2(self):
camelize_map = CamelCaseMap()
self.assertEqual(camelize_map._convert_key('first_name'), 'firstName')
def test_convert_key_3(self):
camelize_map = CamelCaseMap()
self.assertEqual(camelize_map._convert_key('last_name'), 'lastName')
def test_convert_key_4(self):
camelize_map = CamelCaseMap()
self.assertEqual(camelize_map._convert_key('ccc_ddd'), 'cccDdd')
def test_convert_key_5(self):
camelize_map = CamelCaseMap()
self.assertEqual(camelize_map._convert_key('eee_fff'), 'eeeFff')
def test_convert_key_6(self):
camelize_map = CamelCaseMap()
self.assertEqual(camelize_map._convert_key(1234), 1234)
class CamelCaseMapTestToCamelCase(unittest.TestCase):
def test_to_camel_case_1(self):
self.assertEqual(CamelCaseMap._to_camel_case('aaa_bbb'), 'aaaBbb')
def test_to_camel_case_2(self):
self.assertEqual(CamelCaseMap._to_camel_case('first_name'), 'firstName')
def test_to_camel_case_3(self):
self.assertEqual(CamelCaseMap._to_camel_case('last_name'), 'lastName')
def test_to_camel_case_4(self):
self.assertEqual(CamelCaseMap._to_camel_case('ccc_ddd'), 'cccDdd')
def test_to_camel_case_5(self):
self.assertEqual(CamelCaseMap._to_camel_case('eee_fff'), 'eeeFff')
class CamelCaseMapTest(unittest.TestCase):
def test_CamelCaseMap(self):
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
self.assertEqual(camelize_map.__getitem__('first_name'), 'John')
camelize_map = CamelCaseMap()
camelize_map['first_name'] = 'John'
camelize_map.__setitem__('first_name', 'newname')
self.assertEqual(camelize_map['first_name'], 'newname') | class CamelCaseMap:
def __init__(self):
self._data = {}
def __getitem__(self, key):
return self._data[self._convert_key(key)]
def __setitem__(self, key, value):
self._data[self._convert_key(key)] = value
def __delitem__(self, key):
del self._data[self._convert_key(key)]
def __iter__(self):
return iter(self._data)
def __len__(self):
return len(self._data)
def _convert_key(self, key):
if isinstance(key, str):
return self._to_camel_case(key)
return key
@staticmethod
def _to_camel_case(key):
parts = key.split('_')
return parts[0] + ''.join(part.title() for part in parts[1:]) | [] | """
This is a custom class that allows keys to be in camel case style by converting them from underscore style, which provides dictionary-like functionality.
"""
| [
{
"method_name": "__getitem__",
"method_description": "def __getitem__(self, key):\n \"\"\"\n Return the value corresponding to the key\n :param key:str\n :return:str,the value corresponding to the key\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map.__getitem__('first_name')\n 'John'\n \"\"\"",
"test_class": "CamelCaseMapTestGetitem",
"test_code": "class CamelCaseMapTestGetitem(unittest.TestCase):\n def test_getitem_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n self.assertEqual(camelize_map.__getitem__('first_name'), 'John')\n\n def test_getitem_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['last_name'] = 'Doe'\n self.assertEqual(camelize_map.__getitem__('last_name'), 'Doe')\n\n def test_getitem_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['age'] = 30\n self.assertEqual(camelize_map.__getitem__('age'), 30)\n\n def test_getitem_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n self.assertEqual(camelize_map.__getitem__('first_Name'), 'John')\n\n def test_getitem_5(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n self.assertEqual(camelize_map.__getitem__('firstName'), 'John')",
"solution_code": "def __getitem__(self, key):\n return self._data[self._convert_key(key)]",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self._data"
],
"method_dependencies": [
"_convert_key"
]
}
},
{
"method_name": "__setitem__",
"method_description": "def __setitem__(self, key, value):\n \"\"\"\n Set the value corresponding to the key to the specified value\n :param key:str\n :param value:str, the specified value\n :return:None\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map.__setitem__('first_name', 'new name')\n camelize_map['first_name'] = 'new name'\n \"\"\"",
"test_class": "CamelCaseMapTestSetitem",
"test_code": "class CamelCaseMapTestSetitem(unittest.TestCase):\n def test_setitem_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('first_name', 'newname')\n self.assertEqual(camelize_map['first_name'], 'newname')\n\n def test_setitem_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('first_name', 'John')\n self.assertEqual(camelize_map['first_name'], 'John')\n\n def test_setitem_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('first_Name', 'newname')\n self.assertEqual(camelize_map['first_name'], 'newname')\n\n def test_setitem_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('firstName', 'newname')\n self.assertEqual(camelize_map['first_name'], 'newname')\n\n def test_setitem_5(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('first_name', '')\n self.assertEqual(camelize_map['first_name'], '')",
"solution_code": "def __setitem__(self, key, value):\n self._data[self._convert_key(key)] = value",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self._data"
],
"method_dependencies": [
"_convert_key"
]
}
},
{
"method_name": "__delitem__",
"method_description": "def __delitem__(self, key):\n \"\"\"\n Delete the value corresponding to the key\n :param key:str\n :return:None\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map.__delitem__('first_name')\n >>> flag = 'first_name' in camelize_map\n flag = False\n \"\"\"",
"test_class": "CamelCaseMapTestDelitem",
"test_code": "class CamelCaseMapTestDelitem(unittest.TestCase):\n def test_delitem_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map['last_name'] = 'Doe'\n camelize_map.__delitem__('first_name')\n self.assertEqual(camelize_map['last_name'], 'Doe')\n\n def test_delitem_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__delitem__('first_name')\n self.assertEqual('first_name' in camelize_map, False)\n\n def test_delitem_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__delitem__('first_Name')\n self.assertEqual('first_name' in camelize_map, False)\n\n def test_delitem_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__delitem__('firstName')\n self.assertEqual('first_name' in camelize_map, False)\n\n def test_delitem_5(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = ''\n camelize_map.__delitem__('first_name')\n self.assertEqual('first_name' in camelize_map, False)",
"solution_code": "def __delitem__(self, key):\n del self._data[self._convert_key(key)]",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self._data"
],
"method_dependencies": [
"_convert_key"
]
}
},
{
"method_name": "__iter__",
"method_description": "def __iter__(self):\n \"\"\"\n Returning Iterateable Objects with Own Data\n :return:Iterator\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map['last_name'] = 'Doe'\n >>> camelize_map['age'] = 30\n >>> camelize_map.__iter__()\n <dict_keyiterator object at 0x0000026739977C20>\n \"\"\"",
"test_class": "CamelCaseMapTestIter",
"test_code": "class CamelCaseMapTestIter(unittest.TestCase):\n def test_iter_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map['last_name'] = 'Doe'\n camelize_map['age'] = 30\n lst = ['firstName', 'lastName', 'age']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1\n\n def test_iter_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['firstname'] = 'John'\n camelize_map['lastname'] = 'Doe'\n camelize_map['age'] = 30\n lst = ['firstname', 'lastname', 'age']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1\n\n def test_iter_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_Name'] = 'John'\n camelize_map['last_Name'] = 'Doe'\n camelize_map['age'] = 30\n lst = ['firstName', 'lastName', 'age']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1\n\n def test_iter_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_Name'] = 'John'\n camelize_map['last_Name'] = 'Doe'\n lst = ['firstName', 'lastName']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1\n\n def test_iter_5(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_Name'] = 'John'\n lst = ['firstName']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1",
"solution_code": "def __iter__(self):\n return iter(self._data)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self._data"
],
"method_dependencies": []
}
},
{
"method_name": "__len__",
"method_description": "def __len__(self):\n \"\"\"\n Returns the length of the own data\n :return:int, length of data\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map['last_name'] = 'Doe'\n >>> camelize_map['age'] = 30\n >>> camelize_map.__len__()\n 3\n \"\"\"",
"test_class": "CamelCaseMapTestLen",
"test_code": "class CamelCaseMapTestLen(unittest.TestCase):\n def test_len_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n self.assertEqual(camelize_map.__len__(), 1)\n\n def test_len_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['last_name'] = 'Doe'\n self.assertEqual(camelize_map.__len__(), 1)\n\n def test_len_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['age'] = 30\n self.assertEqual(camelize_map.__len__(), 1)\n\n def test_len_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map['last_Name'] = 'Doe'\n camelize_map['age'] = 30\n self.assertEqual(camelize_map.__len__(), 3)\n\n def test_len_5(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map.__len__(), 0)",
"solution_code": "def __len__(self):\n return len(self._data)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self._data"
],
"method_dependencies": []
}
},
{
"method_name": "_convert_key",
"method_description": "def _convert_key(self, key):\n \"\"\"\n convert key string into camel case\n :param key:str\n :return:str, converted key string\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map._convert_key('first_name')\n 'firstName'\n \"\"\"",
"test_class": "CamelCaseMapTestConvertKey",
"test_code": "class CamelCaseMapTestConvertKey(unittest.TestCase):\n def test_convert_key_1(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('aaa_bbb'), 'aaaBbb')\n\n def test_convert_key_2(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('first_name'), 'firstName')\n\n def test_convert_key_3(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('last_name'), 'lastName')\n\n def test_convert_key_4(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('ccc_ddd'), 'cccDdd')\n\n def test_convert_key_5(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('eee_fff'), 'eeeFff')\n\n def test_convert_key_6(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key(1234), 1234)",
"solution_code": "def _convert_key(self, key):\n if isinstance(key, str):\n return self._to_camel_case(key)\n return key",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"_to_camel_case"
]
}
},
{
"method_name": "_to_camel_case",
"method_description": "@staticmethod\n def _to_camel_case(key):\n \"\"\"\n convert key string into camel case\n :param key:str\n :return:str, converted key string\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map._to_camel_case('first_name')\n 'firstName'\n \"\"\"",
"test_class": "CamelCaseMapTestToCamelCase",
"test_code": "class CamelCaseMapTestToCamelCase(unittest.TestCase):\n def test_to_camel_case_1(self):\n self.assertEqual(CamelCaseMap._to_camel_case('aaa_bbb'), 'aaaBbb')\n\n def test_to_camel_case_2(self):\n self.assertEqual(CamelCaseMap._to_camel_case('first_name'), 'firstName')\n\n def test_to_camel_case_3(self):\n self.assertEqual(CamelCaseMap._to_camel_case('last_name'), 'lastName')\n\n def test_to_camel_case_4(self):\n self.assertEqual(CamelCaseMap._to_camel_case('ccc_ddd'), 'cccDdd')\n\n def test_to_camel_case_5(self):\n self.assertEqual(CamelCaseMap._to_camel_case('eee_fff'), 'eeeFff')",
"solution_code": "@staticmethod\n def _to_camel_case(key):\n parts = key.split('_')\n return parts[0] + ''.join(part.title() for part in parts[1:])",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | CamelCaseMap | [
"CamelCaseMapTestGetitem",
"CamelCaseMapTestSetitem",
"CamelCaseMapTestDelitem",
"CamelCaseMapTestIter",
"CamelCaseMapTestLen",
"CamelCaseMapTestConvertKey",
"CamelCaseMapTestToCamelCase",
"CamelCaseMapTest"
] | class CamelCaseMap:
def __init__(self):
"""
Initialize data to an empty dictionary
"""
self._data = {}
| [
"self._data"
] |
ClassEval_19 | class ChandrasekharSieve:
"""
This is a class that uses the Chandrasekhar's Sieve method to find all prime numbers within the range
"""
def __init__(self, n):
"""
Initialize the ChandrasekharSieve class with the given limit.
:param n: int, the upper limit for generating prime numbers
"""
self.n = n
self.primes = self.generate_primes()
def generate_primes(self):
"""
Generate prime numbers up to the specified limit using the Chandrasekhar sieve algorithm.
:return: list, a list of prime numbers
>>> cs = ChandrasekharSieve(20)
>>> cs.generate_primes()
[2, 3, 5, 7, 11, 13, 17, 19]
"""
def get_primes(self):
"""
Get the list of generated prime numbers.
:return: list, a list of prime numbers
>>> cs = ChandrasekharSieve(20)
>>> cs.get_primes()
[2, 3, 5, 7, 11, 13, 17, 19]
""" | import unittest
class ChandrasekharSieveTestGeneratePrimes(unittest.TestCase):
def test_generate_primes_1(self):
cs = ChandrasekharSieve(20)
res = cs.generate_primes()
self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])
def test_generate_primes_2(self):
cs = ChandrasekharSieve(18)
res = cs.generate_primes()
self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17])
def test_generate_primes_3(self):
cs = ChandrasekharSieve(15)
res = cs.generate_primes()
self.assertEqual(res, [2, 3, 5, 7, 11, 13])
def test_generate_primes_4(self):
cs = ChandrasekharSieve(10)
res = cs.generate_primes()
self.assertEqual(res, [2, 3, 5, 7])
def test_generate_primes_5(self):
cs = ChandrasekharSieve(1)
res = cs.generate_primes()
self.assertEqual(res, [])
class ChandrasekharSieveTestGetPrimes(unittest.TestCase):
def test_get_primes_1(self):
cs = ChandrasekharSieve(20)
cs.generate_primes()
res = cs.get_primes()
self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])
def test_get_primes_2(self):
cs = ChandrasekharSieve(18)
cs.generate_primes()
res = cs.get_primes()
self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17])
def test_get_primes_3(self):
cs = ChandrasekharSieve(15)
cs.generate_primes()
res = cs.get_primes()
self.assertEqual(res, [2, 3, 5, 7, 11, 13])
def test_get_primes_4(self):
cs = ChandrasekharSieve(10)
cs.generate_primes()
res = cs.get_primes()
self.assertEqual(res, [2, 3, 5, 7])
def test_get_primes_5(self):
cs = ChandrasekharSieve(1)
res = cs.get_primes()
self.assertEqual(res, [])
class ChandrasekharSieveTest(unittest.TestCase):
def test_chandrasekharsieve(self):
cs = ChandrasekharSieve(20)
res = cs.generate_primes()
self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])
res = cs.get_primes()
self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19]) | class ChandrasekharSieve:
def __init__(self, n):
self.n = n
self.primes = self.generate_primes()
def generate_primes(self):
if self.n < 2:
return []
sieve = [True] * (self.n + 1)
sieve[0] = sieve[1] = False
p = 2
while p * p <= self.n:
if sieve[p]:
for i in range(p * p, self.n + 1, p):
sieve[i] = False
p += 1
primes = []
for i in range(2, self.n + 1):
if sieve[i]:
primes.append(i)
return primes
def get_primes(self):
return self.primes | [] | """
This is a class that uses the Chandrasekhar's Sieve method to find all prime numbers within the range
"""
| [
{
"method_name": "generate_primes",
"method_description": "def generate_primes(self):\n \"\"\"\n Generate prime numbers up to the specified limit using the Chandrasekhar sieve algorithm.\n :return: list, a list of prime numbers\n >>> cs = ChandrasekharSieve(20)\n >>> cs.generate_primes()\n [2, 3, 5, 7, 11, 13, 17, 19]\n\n \"\"\"",
"test_class": "ChandrasekharSieveTestGeneratePrimes",
"test_code": "class ChandrasekharSieveTestGeneratePrimes(unittest.TestCase):\n def test_generate_primes_1(self):\n cs = ChandrasekharSieve(20)\n res = cs.generate_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])\n\n def test_generate_primes_2(self):\n cs = ChandrasekharSieve(18)\n res = cs.generate_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17])\n\n def test_generate_primes_3(self):\n cs = ChandrasekharSieve(15)\n res = cs.generate_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13])\n\n def test_generate_primes_4(self):\n cs = ChandrasekharSieve(10)\n res = cs.generate_primes()\n self.assertEqual(res, [2, 3, 5, 7])\n\n def test_generate_primes_5(self):\n cs = ChandrasekharSieve(1)\n res = cs.generate_primes()\n self.assertEqual(res, [])",
"solution_code": "def generate_primes(self):\n if self.n < 2:\n return []\n\n sieve = [True] * (self.n + 1)\n sieve[0] = sieve[1] = False\n\n p = 2\n while p * p <= self.n:\n if sieve[p]:\n for i in range(p * p, self.n + 1, p):\n sieve[i] = False\n p += 1\n\n primes = []\n for i in range(2, self.n + 1):\n if sieve[i]:\n primes.append(i)\n\n return primes",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.n"
],
"method_dependencies": []
}
},
{
"method_name": "get_primes",
"method_description": "def get_primes(self):\n \"\"\"\n Get the list of generated prime numbers.\n :return: list, a list of prime numbers\n >>> cs = ChandrasekharSieve(20)\n >>> cs.get_primes()\n [2, 3, 5, 7, 11, 13, 17, 19]\n\n \"\"\"",
"test_class": "ChandrasekharSieveTestGetPrimes",
"test_code": "class ChandrasekharSieveTestGetPrimes(unittest.TestCase):\n def test_get_primes_1(self):\n cs = ChandrasekharSieve(20)\n cs.generate_primes()\n res = cs.get_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])\n\n def test_get_primes_2(self):\n cs = ChandrasekharSieve(18)\n cs.generate_primes()\n res = cs.get_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17])\n\n def test_get_primes_3(self):\n cs = ChandrasekharSieve(15)\n cs.generate_primes()\n res = cs.get_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13])\n\n def test_get_primes_4(self):\n cs = ChandrasekharSieve(10)\n cs.generate_primes()\n res = cs.get_primes()\n self.assertEqual(res, [2, 3, 5, 7])\n\n def test_get_primes_5(self):\n cs = ChandrasekharSieve(1)\n res = cs.get_primes()\n self.assertEqual(res, [])",
"solution_code": "def get_primes(self):\n return self.primes",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.primes"
],
"method_dependencies": []
}
}
] | ChandrasekharSieve | [
"ChandrasekharSieveTestGeneratePrimes",
"ChandrasekharSieveTestGetPrimes",
"ChandrasekharSieveTest"
] | class ChandrasekharSieve:
def __init__(self, n):
"""
Initialize the ChandrasekharSieve class with the given limit.
:param n: int, the upper limit for generating prime numbers
"""
self.n = n
self.primes = self.generate_primes()
| [
"self.n",
"self.primes"
] |
ClassEval_20 | from datetime import datetime
class Chat:
"""
This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.
"""
def __init__(self):
"""
Initialize the Chat with an attribute users, which is an empty dictionary.
"""
self.users = {}
def add_user(self, username):
"""
Add a new user to the Chat.
:param username: The user's name, str.
:return: If the user is already in the Chat, returns False, otherwise, returns True.
>>> chat = Chat()
>>> chat.add_user('John')
True
self.users = {'John': []}
>>> chat.add_user('John')
False
"""
def remove_user(self, username):
"""
Remove a user from the Chat.
:param username: The user's name, str.
:return: If the user is already in the Chat, returns True, otherwise, returns False.
>>> chat = Chat()
>>> chat.users = {'John': []}
>>> chat.remove_user('John')
True
>>> chat.remove_user('John')
False
"""
def send_message(self, sender, receiver, message):
"""
Send a message from a user to another user.
:param sender: The sender's name, str.
:param receiver: The receiver's name, str.
:param message: The message, str.
:return: If the sender or the receiver is not in the Chat, returns False, otherwise, returns True.
>>> chat = Chat()
>>> chat.users = {'John': [], 'Mary': []}
>>> chat.send_message('John', 'Mary', 'Hello')
True
>>> chat.send_message('John', 'Tom', 'Hello')
False
"""
def get_messages(self, username):
"""
Get all the messages of a user from the Chat.
:param username: The user's name, str.
:return: A list of messages, each message is a dictionary with keys 'sender', 'receiver', 'message', 'timestamp'.
>>> chat = Chat()
>>> chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': '2023-01-01 00:00:00'}]}
>>> chat.get_messages('John')
[{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': '2023-01-01 00:00:00'}]
>>> chat.get_messages('Mary')
[]
""" | import unittest
class ChatTestAddUser(unittest.TestCase):
def test_add_user(self):
chat = Chat()
self.assertEqual(chat.add_user('John'), True)
self.assertEqual(chat.users, {'John': []})
def test_add_user_2(self):
chat = Chat()
chat.users = {'John': []}
self.assertEqual(chat.add_user('John'), False)
self.assertEqual(chat.users, {'John': []})
def test_add_user_3(self):
chat = Chat()
chat.users = {'John': []}
self.assertEqual(chat.add_user('Mary'), True)
self.assertEqual(chat.users, {'John': [], 'Mary': []})
def test_add_user_4(self):
chat = Chat()
chat.users = {'John': []}
self.assertEqual(chat.add_user('Mary'), True)
self.assertEqual(chat.users, {'John': [], 'Mary': []})
def test_add_user_5(self):
chat = Chat()
self.assertEqual(chat.add_user('John'), True)
self.assertEqual(chat.add_user('Mary'), True)
self.assertEqual(chat.users, {'John': [], 'Mary': []})
class ChatTestRemoveUser(unittest.TestCase):
def test_remove_user(self):
chat = Chat()
chat.users = {'John': []}
self.assertEqual(chat.remove_user('John'), True)
self.assertEqual(chat.users, {})
def test_remove_user_2(self):
chat = Chat()
self.assertEqual(chat.remove_user('John'), False)
self.assertEqual(chat.users, {})
def test_remove_user_3(self):
chat = Chat()
chat.users = {'John': [], 'Mary': []}
self.assertEqual(chat.remove_user('John'), True)
self.assertEqual(chat.users, {'Mary': []})
def test_remove_user_4(self):
chat = Chat()
chat.users = {'John': [], 'Mary': []}
self.assertEqual(chat.remove_user('Mary'), True)
self.assertEqual(chat.remove_user('John'), True)
self.assertEqual(chat.users, {})
def test_remove_user_5(self):
chat = Chat()
chat.users = {'John': [], 'Mary': []}
self.assertEqual(chat.remove_user('Amy'), False)
self.assertEqual(chat.users, {'John': [], 'Mary': []})
class ChatTestSendMessage(unittest.TestCase):
def test_send_message(self):
chat = Chat()
chat.users = {'John': [], 'Mary': []}
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.assertEqual(chat.send_message('John', 'Mary', 'Hello'), True)
self.assertEqual(chat.users, {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}], 'Mary': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]})
def test_send_message_2(self):
chat = Chat()
chat.users = {'John': [], 'Mary': []}
self.assertEqual(chat.send_message('John', 'Tom', 'Hello'), False)
self.assertEqual(chat.users, {'John': [], 'Mary': []})
def test_send_message_3(self):
chat = Chat()
chat.users = {'John': [], 'Mary': []}
self.assertEqual(chat.send_message('Amy', 'Mary', 'Hello'), False)
self.assertEqual(chat.users, {'John': [], 'Mary': []})
def test_send_message_4(self):
chat = Chat()
chat.users = {'John': [], 'Mary': []}
self.assertEqual(chat.send_message('Amy', 'Tom', 'Hello'), False)
self.assertEqual(chat.users, {'John': [], 'Mary': []})
def test_send_message_5(self):
chat = Chat()
chat.users = {'John': [], 'Mary': []}
self.assertEqual(chat.send_message('Amy', 'Amy', 'Hello'), False)
self.assertEqual(chat.users, {'John': [], 'Mary': []})
class ChatTestGetMessages(unittest.TestCase):
def test_get_messages(self):
chat = Chat()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]}
self.assertEqual(chat.get_messages('John'), [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}])
def test_get_messages_2(self):
chat = Chat()
chat.users = {'John': [], 'Mary': []}
self.assertEqual(chat.get_messages('John'), [])
def test_get_messages_3(self):
chat = Chat()
chat.users = {'John': [], 'Mary': []}
self.assertEqual(chat.get_messages('Amy'), [])
def test_get_messages_4(self):
chat = Chat()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]}
self.assertEqual(chat.get_messages('Mary'), [])
def test_get_messages_5(self):
chat = Chat()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]}
self.assertEqual(chat.get_messages('Amy'), [])
class ChatTestMain(unittest.TestCase):
def test_main(self):
chat = Chat()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.assertEqual(chat.add_user('John'), True)
self.assertEqual(chat.add_user('Mary'), True)
self.assertEqual(chat.add_user('Amy'), True)
self.assertEqual(chat.users, {'John': [], 'Mary': [], 'Amy': []})
self.assertEqual(chat.remove_user('Amy'), True)
self.assertEqual(chat.users, {'John': [], 'Mary': []})
self.assertEqual(chat.send_message('John', 'Mary', 'Hello'), True)
self.assertEqual(chat.send_message('John', 'Tom', 'Hello'), False)
self.assertEqual(chat.users, {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}], 'Mary': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]})
self.assertEqual(chat.get_messages('John'), [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}])
self.assertEqual(chat.get_messages('Mary'), [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}])
def test_main_2(self):
chat = Chat()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.assertEqual(chat.remove_user('Amy'), False)
self.assertEqual(chat.add_user('John'), True)
self.assertEqual(chat.add_user('Mary'), True)
self.assertEqual(chat.add_user('Amy'), True)
self.assertEqual(chat.users, {'John': [], 'Mary': [], 'Amy': []})
self.assertEqual(chat.send_message('John', 'Mary', 'Hello'), True)
self.assertEqual(chat.send_message('John', 'Tom', 'Hello'), False)
self.assertEqual(chat.remove_user('Amy'), True)
self.assertEqual(chat.users, {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}], 'Mary': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]})
self.assertEqual(chat.users, {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}], 'Mary': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]})
self.assertEqual(chat.get_messages('John'), [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]) | from datetime import datetime
class Chat:
def __init__(self):
self.users = {}
def add_user(self, username):
if username in self.users:
return False
else:
self.users[username] = []
return True
def remove_user(self, username):
if username in self.users:
del self.users[username]
return True
else:
return False
def send_message(self, sender, receiver, message):
if sender not in self.users or receiver not in self.users:
return False
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
message_info = {
'sender': sender,
'receiver': receiver,
'message': message,
'timestamp': timestamp
}
self.users[sender].append(message_info)
self.users[receiver].append(message_info)
return True
def get_messages(self, username):
if username not in self.users:
return []
return self.users[username] | [
"from datetime import datetime"
] | """
This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.
"""
| [
{
"method_name": "add_user",
"method_description": "def add_user(self, username):\n \"\"\"\n Add a new user to the Chat.\n :param username: The user's name, str.\n :return: If the user is already in the Chat, returns False, otherwise, returns True.\n >>> chat = Chat()\n >>> chat.add_user('John')\n True\n self.users = {'John': []}\n >>> chat.add_user('John')\n False\n\n \"\"\"",
"test_class": "ChatTestAddUser",
"test_code": "class ChatTestAddUser(unittest.TestCase):\n def test_add_user(self):\n chat = Chat()\n self.assertEqual(chat.add_user('John'), True)\n self.assertEqual(chat.users, {'John': []})\n def test_add_user_2(self):\n chat = Chat()\n chat.users = {'John': []}\n self.assertEqual(chat.add_user('John'), False)\n self.assertEqual(chat.users, {'John': []})\n\n def test_add_user_3(self):\n chat = Chat()\n chat.users = {'John': []}\n self.assertEqual(chat.add_user('Mary'), True)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_add_user_4(self):\n chat = Chat()\n chat.users = {'John': []}\n self.assertEqual(chat.add_user('Mary'), True)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_add_user_5(self):\n chat = Chat()\n self.assertEqual(chat.add_user('John'), True)\n self.assertEqual(chat.add_user('Mary'), True)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})",
"solution_code": "def add_user(self, username):\n if username in self.users:\n return False\n else:\n self.users[username] = []\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.users"
],
"method_dependencies": []
}
},
{
"method_name": "remove_user",
"method_description": "def remove_user(self, username):\n \"\"\"\n Remove a user from the Chat.\n :param username: The user's name, str.\n :return: If the user is already in the Chat, returns True, otherwise, returns False.\n >>> chat = Chat()\n >>> chat.users = {'John': []}\n >>> chat.remove_user('John')\n True\n >>> chat.remove_user('John')\n False\n\n \"\"\"",
"test_class": "ChatTestRemoveUser",
"test_code": "class ChatTestRemoveUser(unittest.TestCase):\n def test_remove_user(self):\n chat = Chat()\n chat.users = {'John': []}\n self.assertEqual(chat.remove_user('John'), True)\n self.assertEqual(chat.users, {})\n def test_remove_user_2(self):\n chat = Chat()\n self.assertEqual(chat.remove_user('John'), False)\n self.assertEqual(chat.users, {})\n\n def test_remove_user_3(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.remove_user('John'), True)\n self.assertEqual(chat.users, {'Mary': []})\n\n def test_remove_user_4(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.remove_user('Mary'), True)\n self.assertEqual(chat.remove_user('John'), True)\n self.assertEqual(chat.users, {})\n\n def test_remove_user_5(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.remove_user('Amy'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})",
"solution_code": "def remove_user(self, username):\n if username in self.users:\n del self.users[username]\n return True\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.users"
],
"method_dependencies": []
}
},
{
"method_name": "send_message",
"method_description": "def send_message(self, sender, receiver, message):\n \"\"\"\n Send a message from a user to another user.\n :param sender: The sender's name, str.\n :param receiver: The receiver's name, str.\n :param message: The message, str.\n :return: If the sender or the receiver is not in the Chat, returns False, otherwise, returns True.\n >>> chat = Chat()\n >>> chat.users = {'John': [], 'Mary': []}\n >>> chat.send_message('John', 'Mary', 'Hello')\n True\n >>> chat.send_message('John', 'Tom', 'Hello')\n False\n\n \"\"\"",
"test_class": "ChatTestSendMessage",
"test_code": "class ChatTestSendMessage(unittest.TestCase):\n def test_send_message(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertEqual(chat.send_message('John', 'Mary', 'Hello'), True)\n self.assertEqual(chat.users, {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}], 'Mary': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]})\n\n def test_send_message_2(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.send_message('John', 'Tom', 'Hello'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_send_message_3(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.send_message('Amy', 'Mary', 'Hello'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_send_message_4(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.send_message('Amy', 'Tom', 'Hello'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_send_message_5(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.send_message('Amy', 'Amy', 'Hello'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})",
"solution_code": "def send_message(self, sender, receiver, message):\n if sender not in self.users or receiver not in self.users:\n return False\n\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n message_info = {\n 'sender': sender,\n 'receiver': receiver,\n 'message': message,\n 'timestamp': timestamp\n }\n self.users[sender].append(message_info)\n self.users[receiver].append(message_info)\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"datetime"
],
"field_dependencies": [
"self.users"
],
"method_dependencies": []
}
},
{
"method_name": "get_messages",
"method_description": "def get_messages(self, username):\n \"\"\"\n Get all the messages of a user from the Chat.\n :param username: The user's name, str.\n :return: A list of messages, each message is a dictionary with keys 'sender', 'receiver', 'message', 'timestamp'.\n >>> chat = Chat()\n >>> chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': '2023-01-01 00:00:00'}]}\n >>> chat.get_messages('John')\n [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': '2023-01-01 00:00:00'}]\n >>> chat.get_messages('Mary')\n []\n\n \"\"\"",
"test_class": "ChatTestGetMessages",
"test_code": "class ChatTestGetMessages(unittest.TestCase):\n def test_get_messages(self):\n chat = Chat()\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]}\n self.assertEqual(chat.get_messages('John'), [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}])\n\n def test_get_messages_2(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.get_messages('John'), [])\n\n def test_get_messages_3(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.get_messages('Amy'), [])\n\n def test_get_messages_4(self):\n chat = Chat()\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]}\n self.assertEqual(chat.get_messages('Mary'), [])\n\n def test_get_messages_5(self):\n chat = Chat()\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]}\n self.assertEqual(chat.get_messages('Amy'), [])",
"solution_code": "def get_messages(self, username):\n if username not in self.users:\n return []\n return self.users[username]",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.users"
],
"method_dependencies": []
}
}
] | Chat | [
"ChatTestAddUser",
"ChatTestRemoveUser",
"ChatTestSendMessage",
"ChatTestGetMessages",
"ChatTestMain"
] | class Chat:
def __init__(self):
"""
Initialize the Chat with an attribute users, which is an empty dictionary.
"""
self.users = {}
| [
"self.users"
] |
ClassEval_21 | from datetime import datetime
class Classroom:
"""
This is a class representing a classroom, capable of adding and removing courses, checking availability at a given time, and detecting conflicts when scheduling new courses.
"""
def __init__(self, id):
"""
Initialize the classroom management system.
:param id: int, the id of classroom
"""
self.id = id
self.courses = []
def add_course(self, course):
"""
Add course to self.courses list if the course wasn't in it.
:param course: dict, information of the course, including 'start_time', 'end_time' and 'name'
>>> classroom = Classroom(1)
>>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})
"""
def remove_course(self, course):
"""
Remove course from self.courses list if the course was in it.
:param course: dict, information of the course, including 'start_time', 'end_time' and 'name'
>>> classroom = Classroom(1)
>>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})
>>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})
"""
def is_free_at(self, check_time):
"""
change the time format as '%H:%M' and check the time is free or not in the classroom.
:param check_time: str, the time need to be checked
:return: True if the check_time does not conflict with every course time, or False otherwise.
>>> classroom = Classroom(1)
>>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})
>>> classroom.is_free_at('10:00')
True
>>> classroom.is_free_at('9:00')
False
"""
def check_course_conflict(self, new_course):
"""
Before adding a new course, check if the new course time conflicts with any other course.
:param new_course: dict, information of the course, including 'start_time', 'end_time' and 'name'
:return: False if the new course time conflicts(including two courses have the same boundary time) with other courses, or True otherwise.
>>> classroom = Classroom(1)
>>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})
>>> classroom.check_course_conflict({'name': 'SE', 'start_time': '9:40', 'end_time': '10:40'})
False
""" | import unittest
from datetime import datetime
class ClassroomTestAddCourse(unittest.TestCase):
def test_add_course_1(self):
classroom = Classroom(1)
course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(course)
self.assertIn(course, classroom.courses)
def test_add_course_2(self):
classroom = Classroom(1)
course = {'name': 'Chinese', 'start_time': '10:00', 'end_time': '11:00'}
classroom.add_course(course)
self.assertIn(course, classroom.courses)
def test_add_course_3(self):
classroom = Classroom(1)
course = {'name': 'English', 'start_time': '11:00', 'end_time': '12:00'}
classroom.add_course(course)
self.assertIn(course, classroom.courses)
def test_add_course_4(self):
classroom = Classroom(1)
course = {'name': 'Art', 'start_time': '14:00', 'end_time': '15:00'}
classroom.add_course(course)
self.assertIn(course, classroom.courses)
def test_add_course_5(self):
classroom = Classroom(1)
course = {'name': 'P.E.', 'start_time': '15:00', 'end_time': '16:00'}
classroom.add_course(course)
self.assertIn(course, classroom.courses)
def test_add_course_6(self):
classroom = Classroom(1)
course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(course)
classroom.add_course(course)
self.assertIn(course, classroom.courses)
class ClassroomTestRemoveCourse(unittest.TestCase):
def test_remove_course_1(self):
classroom = Classroom(1)
course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(course)
classroom.remove_course(course)
self.assertNotIn(course, classroom.courses)
def test_remove_course_2(self):
classroom = Classroom(1)
course = {'name': 'Chinese', 'start_time': '10:00', 'end_time': '11:00'}
classroom.add_course(course)
classroom.remove_course(course)
self.assertNotIn(course, classroom.courses)
def test_remove_course_3(self):
classroom = Classroom(1)
course = {'name': 'English', 'start_time': '11:00', 'end_time': '12:00'}
classroom.add_course(course)
classroom.remove_course(course)
self.assertNotIn(course, classroom.courses)
def test_remove_course_4(self):
classroom = Classroom(1)
course = {'name': 'Art', 'start_time': '14:00', 'end_time': '15:00'}
classroom.add_course(course)
classroom.remove_course(course)
self.assertNotIn(course, classroom.courses)
def test_remove_course_5(self):
classroom = Classroom(1)
course = {'name': 'P.E.', 'start_time': '15:00', 'end_time': '16:00'}
classroom.add_course(course)
classroom.remove_course(course)
self.assertNotIn(course, classroom.courses)
def test_remove_course_6(self):
classroom = Classroom(1)
course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.remove_course(course)
self.assertNotIn(course, classroom.courses)
class ClassroomTestIsFreeAt(unittest.TestCase):
def test_is_free_at_1(self):
classroom = Classroom(1)
course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(course)
check_time = '11:00'
result = classroom.is_free_at(check_time)
self.assertTrue(result)
def test_is_free_at_2(self):
classroom = Classroom(1)
course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(course)
check_time = '09:30'
result = classroom.is_free_at(check_time)
self.assertFalse(result)
def test_is_free_at_3(self):
classroom = Classroom(1)
course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(course)
check_time = '12:00'
result = classroom.is_free_at(check_time)
self.assertTrue(result)
def test_is_free_at_4(self):
classroom = Classroom(1)
course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(course)
check_time = '14:00'
result = classroom.is_free_at(check_time)
self.assertTrue(result)
def test_is_free_at_5(self):
classroom = Classroom(1)
course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(course)
check_time = '09:40'
result = classroom.is_free_at(check_time)
self.assertFalse(result)
class ClassroomTestCheckCourseConflict(unittest.TestCase):
def test_check_course_conflict_1(self):
classroom = Classroom(1)
existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(existing_course)
new_course = {'name': 'SE', 'start_time': '10:30', 'end_time': '11:30'}
result = classroom.check_course_conflict(new_course)
self.assertTrue(result)
def test_check_course_conflict_2(self):
classroom = Classroom(1)
existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(existing_course)
new_course = {'name': 'SE', 'start_time': '09:30', 'end_time': '10:30'}
result = classroom.check_course_conflict(new_course)
self.assertFalse(result)
# have the same boundary time
# existing_course['end_time'] == new_course['start_time']
def test_check_course_conflict_3(self):
classroom = Classroom(1)
existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(existing_course)
new_course = {'name': 'SE', 'start_time': '10:00', 'end_time': '11:30'}
result = classroom.check_course_conflict(new_course)
self.assertFalse(result)
def test_check_course_conflict_4(self):
classroom = Classroom(1)
existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(existing_course)
new_course = {'name': 'SE', 'start_time': '09:40', 'end_time': '10:40'}
result = classroom.check_course_conflict(new_course)
self.assertFalse(result)
def test_check_course_conflict_5(self):
classroom = Classroom(1)
existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(existing_course)
new_course = {'name': 'SE', 'start_time': '14:30', 'end_time': '15:30'}
result = classroom.check_course_conflict(new_course)
self.assertTrue(result)
def test_check_course_conflict_6(self):
classroom = Classroom(1)
existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(existing_course)
new_course = {'name': 'SE', 'start_time': '8:30', 'end_time': '9:30'}
result = classroom.check_course_conflict(new_course)
self.assertFalse(result)
class ClassroomTestMain(unittest.TestCase):
def test_main(self):
classroom = Classroom(1)
course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}
classroom.add_course(course)
self.assertIn(course, classroom.courses)
classroom.remove_course(course)
self.assertNotIn(course, classroom.courses)
classroom.add_course(course)
self.assertIn(course, classroom.courses)
check_time = '09:30'
result = classroom.is_free_at(check_time)
self.assertFalse(result)
new_course = {'name': 'SE', 'start_time': '09:30', 'end_time': '10:30'}
result = classroom.check_course_conflict(new_course)
self.assertFalse(result) | from datetime import datetime
class Classroom:
def __init__(self, id):
self.id = id
self.courses = []
def add_course(self, course):
if course not in self.courses:
self.courses.append(course)
def remove_course(self, course):
if course in self.courses:
self.courses.remove(course)
def is_free_at(self, check_time):
check_time = datetime.strptime(check_time, '%H:%M')
for course in self.courses:
if datetime.strptime(course['start_time'], '%H:%M') <= check_time <= datetime.strptime(course['end_time'],
'%H:%M'):
return False
return True
def check_course_conflict(self, new_course):
new_start_time = datetime.strptime(new_course['start_time'], '%H:%M')
new_end_time = datetime.strptime(new_course['end_time'], '%H:%M')
flag = True
for course in self.courses:
start_time = datetime.strptime(course['start_time'], '%H:%M')
end_time = datetime.strptime(course['end_time'], '%H:%M')
if start_time <= new_start_time and end_time >= new_start_time:
flag = False
if start_time <= new_end_time and end_time >= new_end_time:
flag = False
return flag | [
"from datetime import datetime"
] | """
This is a class representing a classroom, capable of adding and removing courses, checking availability at a given time, and detecting conflicts when scheduling new courses.
"""
| [
{
"method_name": "add_course",
"method_description": "def add_course(self, course):\n \"\"\"\n Add course to self.courses list if the course wasn't in it.\n :param course: dict, information of the course, including 'start_time', 'end_time' and 'name'\n >>> classroom = Classroom(1)\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n \"\"\"",
"test_class": "ClassroomTestAddCourse",
"test_code": "class ClassroomTestAddCourse(unittest.TestCase):\n def test_add_course_1(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_2(self):\n classroom = Classroom(1)\n course = {'name': 'Chinese', 'start_time': '10:00', 'end_time': '11:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_3(self):\n classroom = Classroom(1)\n course = {'name': 'English', 'start_time': '11:00', 'end_time': '12:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_4(self):\n classroom = Classroom(1)\n course = {'name': 'Art', 'start_time': '14:00', 'end_time': '15:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_5(self):\n classroom = Classroom(1)\n course = {'name': 'P.E.', 'start_time': '15:00', 'end_time': '16:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_6(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)",
"solution_code": "def add_course(self, course):\n\n if course not in self.courses:\n self.courses.append(course)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.courses"
],
"method_dependencies": []
}
},
{
"method_name": "remove_course",
"method_description": "def remove_course(self, course):\n \"\"\"\n Remove course from self.courses list if the course was in it.\n :param course: dict, information of the course, including 'start_time', 'end_time' and 'name'\n >>> classroom = Classroom(1)\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n \"\"\"",
"test_class": "ClassroomTestRemoveCourse",
"test_code": "class ClassroomTestRemoveCourse(unittest.TestCase):\n def test_remove_course_1(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_2(self):\n classroom = Classroom(1)\n course = {'name': 'Chinese', 'start_time': '10:00', 'end_time': '11:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_3(self):\n classroom = Classroom(1)\n course = {'name': 'English', 'start_time': '11:00', 'end_time': '12:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_4(self):\n classroom = Classroom(1)\n course = {'name': 'Art', 'start_time': '14:00', 'end_time': '15:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_5(self):\n classroom = Classroom(1)\n course = {'name': 'P.E.', 'start_time': '15:00', 'end_time': '16:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_6(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)",
"solution_code": "def remove_course(self, course):\n if course in self.courses:\n self.courses.remove(course)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.courses"
],
"method_dependencies": []
}
},
{
"method_name": "is_free_at",
"method_description": "def is_free_at(self, check_time):\n \"\"\"\n change the time format as '%H:%M' and check the time is free or not in the classroom.\n :param check_time: str, the time need to be checked\n :return: True if the check_time does not conflict with every course time, or False otherwise.\n >>> classroom = Classroom(1)\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n >>> classroom.is_free_at('10:00')\n True\n >>> classroom.is_free_at('9:00')\n False\n \"\"\"",
"test_class": "ClassroomTestIsFreeAt",
"test_code": "class ClassroomTestIsFreeAt(unittest.TestCase):\n def test_is_free_at_1(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '11:00'\n result = classroom.is_free_at(check_time)\n self.assertTrue(result)\n\n def test_is_free_at_2(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '09:30'\n result = classroom.is_free_at(check_time)\n self.assertFalse(result)\n\n def test_is_free_at_3(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '12:00'\n result = classroom.is_free_at(check_time)\n self.assertTrue(result)\n\n def test_is_free_at_4(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '14:00'\n result = classroom.is_free_at(check_time)\n self.assertTrue(result)\n\n def test_is_free_at_5(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '09:40'\n result = classroom.is_free_at(check_time)\n self.assertFalse(result)",
"solution_code": "def is_free_at(self, check_time):\n check_time = datetime.strptime(check_time, '%H:%M')\n\n for course in self.courses:\n if datetime.strptime(course['start_time'], '%H:%M') <= check_time <= datetime.strptime(course['end_time'],\n '%H:%M'):\n return False\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"datetime"
],
"field_dependencies": [
"self.courses"
],
"method_dependencies": []
}
},
{
"method_name": "check_course_conflict",
"method_description": "def check_course_conflict(self, new_course):\n \"\"\"\n Before adding a new course, check if the new course time conflicts with any other course.\n :param new_course: dict, information of the course, including 'start_time', 'end_time' and 'name'\n :return: False if the new course time conflicts(including two courses have the same boundary time) with other courses, or True otherwise.\n >>> classroom = Classroom(1)\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n >>> classroom.check_course_conflict({'name': 'SE', 'start_time': '9:40', 'end_time': '10:40'})\n False\n \"\"\"",
"test_class": "ClassroomTestCheckCourseConflict",
"test_code": "class ClassroomTestCheckCourseConflict(unittest.TestCase):\n def test_check_course_conflict_1(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '10:30', 'end_time': '11:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertTrue(result)\n\n def test_check_course_conflict_2(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '09:30', 'end_time': '10:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertFalse(result)\n\n # have the same boundary time\n # existing_course['end_time'] == new_course['start_time']\n def test_check_course_conflict_3(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '10:00', 'end_time': '11:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertFalse(result)\n\n def test_check_course_conflict_4(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '09:40', 'end_time': '10:40'}\n result = classroom.check_course_conflict(new_course)\n self.assertFalse(result)\n\n def test_check_course_conflict_5(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '14:30', 'end_time': '15:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertTrue(result)\n\n def test_check_course_conflict_6(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '8:30', 'end_time': '9:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertFalse(result)",
"solution_code": "def check_course_conflict(self, new_course):\n new_start_time = datetime.strptime(new_course['start_time'], '%H:%M')\n new_end_time = datetime.strptime(new_course['end_time'], '%H:%M')\n\n flag = True\n for course in self.courses:\n start_time = datetime.strptime(course['start_time'], '%H:%M')\n end_time = datetime.strptime(course['end_time'], '%H:%M')\n if start_time <= new_start_time and end_time >= new_start_time:\n flag = False\n if start_time <= new_end_time and end_time >= new_end_time:\n flag = False\n return flag",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"datetime"
],
"field_dependencies": [
"self.courses"
],
"method_dependencies": []
}
}
] | Classroom | [
"ClassroomTestAddCourse",
"ClassroomTestRemoveCourse",
"ClassroomTestIsFreeAt",
"ClassroomTestCheckCourseConflict",
"ClassroomTestMain"
] | class Classroom:
def __init__(self, id):
"""
Initialize the classroom management system.
:param id: int, the id of classroom
"""
self.id = id
self.courses = []
| [
"self.courses",
"self.id"
] |
ClassEval_22 | class ClassRegistrationSystem:
"""
This is a class as a class registration system, allowing to register students, register them for classes, retrieve students by major, get a list of all majors, and determine the most popular class within a specific major.
"""
def __init__(self):
"""
Initialize the registration system with the attribute students and students_registration_class.
students is a list of student dictionaries, each student dictionary has the key of name and major.
students_registration_class is a dictionaries, key is the student name, value is a list of class names
"""
self.students = []
self.students_registration_classes = {}
def register_student(self, student):
"""
register a student to the system, add the student to the students list, if the student is already registered, return 0, else return 1
"""
def register_class(self, student_name, class_name):
"""
register a class to the student.
:param student_name: str
:param class_name: str
:return a list of class names that the student has registered
>>> registration_system = ClassRegistrationSystem()
>>> registration_system.register_class(student_name="John", class_name="CS101")
>>> registration_system.register_class(student_name="John", class_name="CS102")
["CS101", "CS102"]
def get_students_by_major(self, major):
"""
get all students in the major
:param major: str
:return a list of student name
>>> registration_system = ClassRegistrationSystem()
>>> student1 = {"name": "John", "major": "Computer Science"}
>>> registration_system.register_student(student1)
>>> registration_system.get_students_by_major("Computer Science")
["John"]
"""
def get_all_major(self):
"""
get all majors in the system
:return a list of majors
>>> registration_system = ClassRegistrationSystem()
>>> registration_system.students = [{"name": "John", "major": "Computer Science"}],
>>> registration_system.get_all_major(student1)
["Computer Science"]
"""
def get_most_popular_class_in_major(self, major):
"""
get the class with the highest enrollment in the major.
:return a string of the most popular class in this major
>>> registration_system = ClassRegistrationSystem()
>>> registration_system.students = [{"name": "John", "major": "Computer Science"},
{"name": "Bob", "major": "Computer Science"},
{"name": "Alice", "major": "Computer Science"}]
>>> registration_system.students_registration_classes = {"John": ["Algorithms", "Data Structures"],
"Bob": ["Operating Systems", "Data Structures", "Algorithms"]}
>>> registration_system.get_most_popular_class_in_major("Computer Science")
"Data Structures"
""" | import unittest
class ClassRegistrationSystemTestRegisterStudent(unittest.TestCase):
def setUp(self):
self.registration_system = ClassRegistrationSystem()
def test_register_student(self):
student1 = {"name": "John", "major": "Computer Science"}
self.assertEqual(self.registration_system.register_student(student1), 1)
def test_register_student2(self):
student1 = {"name": "John", "major": "Computer Science"}
self.registration_system.register_student(student1)
self.assertEqual(self.registration_system.register_student(student1), 0)
def test_register_student3(self):
student1 = {"name": "John", "major": "Computer Science"}
student2 = {"name": "Alice", "major": "Mathematics"}
self.assertEqual(self.registration_system.register_student(student1), 1)
self.assertEqual(self.registration_system.register_student(student2), 1)
self.assertEqual(self.registration_system.register_student(student2), 0)
class ClassRegistrationSystemTestRegisterClass(unittest.TestCase):
def setUp(self):
self.registration_system = ClassRegistrationSystem()
def test_register_class(self):
self.assertEqual(self.registration_system.register_class(student_name="John", class_name="CS101"), ["CS101"])
def test_register_class2(self):
self.registration_system.register_class(student_name="John", class_name="CS101")
self.registration_system.register_class(student_name="John", class_name="CS102")
self.assertEqual(self.registration_system.register_class(student_name="John", class_name="CS103"), ["CS101", "CS102", "CS103"])
def test_register_class3(self):
self.registration_system.register_class(student_name="John", class_name="CS101")
self.registration_system.register_class(student_name="Tom", class_name="CS102")
self.assertEqual(self.registration_system.register_class(student_name="John", class_name="CS103"), ["CS101", "CS103"])
class ClassRegistrationSystemTestGetStudent(unittest.TestCase):
def setUp(self):
self.registration_system = ClassRegistrationSystem()
def test_get_students_by_major(self):
self.registration_system.students = [{"name": "John", "major": "Computer Science"},
{"name": "Bob", "major": "Computer Science"}]
cs_students = self.registration_system.get_students_by_major("Computer Science")
self.assertEqual(cs_students, ["John", "Bob"])
def test_get_students_by_major2(self):
self.registration_system.students = [{"name": "John", "major": "Computer Science"},
{"name": "Bob", "major": "Computer Science"}]
cs_students = self.registration_system.get_students_by_major("Computer Science")
math_students = self.registration_system.get_students_by_major("Mathematics")
self.assertEqual(cs_students, ["John", "Bob"])
self.assertEqual(math_students, [])
def test_get_students_by_major3(self):
self.registration_system.students = [{"name": "John", "major": "Computer Science"},
{"name": "Bob", "major": "Computer Science"},
{"name": "Alice", "major": "Mathematics"}]
cs_students = self.registration_system.get_students_by_major("Computer Science")
math_students = self.registration_system.get_students_by_major("Mathematics")
self.assertEqual(cs_students, ["John", "Bob"])
self.assertEqual(math_students, ["Alice"])
def test_get_students_by_major4(self):
self.registration_system.students = [{"name": "John", "major": "Computer Science"},
{"name": "Bob", "major": "Computer Science"},
{"name": "Alice", "major": "Mathematics"},
{"name": "Tom", "major": "Mathematics"},
{"name": "Jerry", "major": "Mathematics"}]
cs_students = self.registration_system.get_students_by_major("Computer Science")
math_students = self.registration_system.get_students_by_major("Mathematics")
self.assertEqual(cs_students, ["John", "Bob"])
self.assertEqual(math_students, ["Alice", "Tom", "Jerry"])
class ClassRegistrationSystemTestGetMajor(unittest.TestCase):
def setUp(self):
self.registration_system = ClassRegistrationSystem()
def test_get_all_major(self):
self.registration_system.students = [{"name": "John", "major": "Computer Science"},
{"name": "Bob", "major": "Computer Science"}]
majors = self.registration_system.get_all_major()
self.assertEqual(majors, ["Computer Science"])
def test_get_all_major2(self):
self.registration_system.students = [{"name": "John", "major": "Computer Science"},
{"name": "Bob", "major": "Computer Science"},
{"name": "Alice", "major": "Mathematics"}]
majors = self.registration_system.get_all_major()
self.assertEqual(majors, ["Computer Science", "Mathematics"])
def test_get_all_major3(self):
self.registration_system.students = [{"name": "John", "major": "Computer Science"},
{"name": "Bob", "major": "Computer Science"},
{"name": "Alice", "major": "Mathematics"},
{"name": "Tom", "major": "Mathematics"},
{"name": "Jerry", "major": "Physics"}]
majors = self.registration_system.get_all_major()
self.assertEqual(majors, ["Computer Science", "Mathematics", "Physics"])
class ClassRegistrationSystemTestPopularClass(unittest.TestCase):
def setUp(self):
self.registration_system = ClassRegistrationSystem()
def test_get_most_popular_class_in_major(self):
self.registration_system.students = [{"name": "John", "major": "Computer Science"},
{"name": "Bob", "major": "Computer Science"},
{"name": "Alice", "major": "Computer Science"}]
self.registration_system.students_registration_classes = {"John": ["Algorithms", "Data Structures"],
"Bob": ["Operating Systems", "Data Structures", "Algorithms"],
"Alice": ["Data Structures", "Operating Systems", "Calculus"]}
cs_most_popular_class = self.registration_system.get_most_popular_class_in_major("Computer Science")
self.assertEqual(cs_most_popular_class, "Data Structures")
def test_get_most_popular_class_in_major2(self):
self.registration_system.students = [{"name": "John", "major": "Computer Science"},
{"name": "Bob", "major": "Computer Science"},
{"name": "Alice", "major": "Computer Science"},
{"name": "Tom", "major": "Mathematics"},
{"name": "Jerry", "major": "Mathematics"}]
self.registration_system.students_registration_classes = {"John": ["Algorithms", "Data Structures"],
"Bob": ["Data Structures", "Algorithms",
"Operating Systems"],
"Alice": ["Data Structures", "Operating Systems",
"Calculus"],
"Tom": ["Calculus", "Linear Algebra"],
"Jerry": ["Linear Algebra", "Statistics"]}
cs_most_popular_class = self.registration_system.get_most_popular_class_in_major("Computer Science")
math_most_popular_class = self.registration_system.get_most_popular_class_in_major("Mathematics")
self.assertEqual(cs_most_popular_class, "Data Structures")
self.assertEqual(math_most_popular_class, "Linear Algebra")
class ClassRegistrationSystemTest(unittest.TestCase):
def setUp(self):
self.registration_system = ClassRegistrationSystem()
def test(self):
student1 = {"name": "John", "major": "Computer Science"}
student2 = {"name": "Bob", "major": "Computer Science"}
student3 = {"name": "Alice", "major": "Mathematics"}
student4 = {"name": "Tom", "major": "Mathematics"}
self.registration_system.register_student(student1)
self.registration_system.register_student(student2)
self.registration_system.register_student(student3)
self.registration_system.register_student(student4)
self.registration_system.register_class("John", "Algorithms")
self.registration_system.register_class("John", "Data Structures")
self.registration_system.register_class("Bob", "Operating Systems")
self.registration_system.register_class("Bob", "Data Structures")
self.assertEqual(self.registration_system.get_students_by_major("Computer Science"), ["John", "Bob"])
self.assertEqual(self.registration_system.get_students_by_major("Mathematics"), ["Alice", "Tom"])
self.assertEqual(self.registration_system.get_all_major(), ["Computer Science", "Mathematics"])
self.assertEqual(self.registration_system.get_most_popular_class_in_major("Computer Science"), "Data Structures") | class ClassRegistrationSystem:
def __init__(self):
self.students = []
self.students_registration_classes = {}
def register_student(self, student):
if student in self.students:
return 0
else:
self.students.append(student)
return 1
def register_class(self, student_name, class_name):
if student_name in self.students_registration_classes:
self.students_registration_classes[student_name].append(class_name)
else:
self.students_registration_classes[student_name] = [class_name]
return self.students_registration_classes[student_name]
def get_students_by_major(self, major):
student_list = []
for student in self.students:
if student["major"] == major:
student_list.append(student["name"])
return student_list
def get_all_major(self):
major_list = []
for student in self.students:
if student["major"] not in major_list:
major_list.append(student["major"])
return major_list
def get_most_popular_class_in_major(self, major):
class_list = []
for student in self.students:
if student["major"] == major:
class_list += self.students_registration_classes[student["name"]]
most_popular_class = max(set(class_list), key=class_list.count)
return most_popular_class | [] | """
This is a class as a class registration system, allowing to register students, register them for classes, retrieve students by major, get a list of all majors, and determine the most popular class within a specific major.
"""
| [
{
"method_name": "register_student",
"method_description": "def register_student(self, student):\n \"\"\"\n register a student to the system, add the student to the students list, if the student is already registered, return 0, else return 1\n \"\"\"",
"test_class": "ClassRegistrationSystemTestRegisterStudent",
"test_code": "class ClassRegistrationSystemTestRegisterStudent(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_register_student(self):\n student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\n self.assertEqual(self.registration_system.register_student(student1), 1)\n\n def test_register_student2(self):\n student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\n self.registration_system.register_student(student1)\n self.assertEqual(self.registration_system.register_student(student1), 0)\n\n def test_register_student3(self):\n student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\n student2 = {\"name\": \"Alice\", \"major\": \"Mathematics\"}\n self.assertEqual(self.registration_system.register_student(student1), 1)\n self.assertEqual(self.registration_system.register_student(student2), 1)\n self.assertEqual(self.registration_system.register_student(student2), 0)",
"solution_code": "def register_student(self, student):\n if student in self.students:\n return 0\n else:\n self.students.append(student)\n return 1",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.students"
],
"method_dependencies": []
}
},
{
"method_name": "register_class",
"method_description": "def register_class(self, student_name, class_name):\n \"\"\"\n register a class to the student.\n :param student_name: str\n :param class_name: str\n :return a list of class names that the student has registered\n >>> registration_system = ClassRegistrationSystem()\n >>> registration_system.register_class(student_name=\"John\", class_name=\"CS101\")\n >>> registration_system.register_class(student_name=\"John\", class_name=\"CS102\")\n [\"CS101\", \"CS102\"]",
"test_class": "ClassRegistrationSystemTestRegisterClass",
"test_code": "class ClassRegistrationSystemTestRegisterClass(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_register_class(self):\n self.assertEqual(self.registration_system.register_class(student_name=\"John\", class_name=\"CS101\"), [\"CS101\"])\n\n def test_register_class2(self):\n self.registration_system.register_class(student_name=\"John\", class_name=\"CS101\")\n self.registration_system.register_class(student_name=\"John\", class_name=\"CS102\")\n self.assertEqual(self.registration_system.register_class(student_name=\"John\", class_name=\"CS103\"), [\"CS101\", \"CS102\", \"CS103\"])\n\n def test_register_class3(self):\n self.registration_system.register_class(student_name=\"John\", class_name=\"CS101\")\n self.registration_system.register_class(student_name=\"Tom\", class_name=\"CS102\")\n self.assertEqual(self.registration_system.register_class(student_name=\"John\", class_name=\"CS103\"), [\"CS101\", \"CS103\"])",
"solution_code": "def register_class(self, student_name, class_name):\n if student_name in self.students_registration_classes:\n self.students_registration_classes[student_name].append(class_name)\n else:\n self.students_registration_classes[student_name] = [class_name]\n return self.students_registration_classes[student_name]",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.students",
"self.students_registration_classes"
],
"method_dependencies": []
}
},
{
"method_name": "get_students_by_major",
"method_description": "def get_students_by_major(self, major):\n \"\"\"\n get all students in the major\n :param major: str\n :return a list of student name\n >>> registration_system = ClassRegistrationSystem()\n >>> student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\n >>> registration_system.register_student(student1)\n >>> registration_system.get_students_by_major(\"Computer Science\")\n [\"John\"]\n \"\"\"",
"test_class": "ClassRegistrationSystemTestGetStudent",
"test_code": "class ClassRegistrationSystemTestGetStudent(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_get_students_by_major(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"}]\n\n cs_students = self.registration_system.get_students_by_major(\"Computer Science\")\n\n self.assertEqual(cs_students, [\"John\", \"Bob\"])\n\n def test_get_students_by_major2(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"}]\n\n cs_students = self.registration_system.get_students_by_major(\"Computer Science\")\n math_students = self.registration_system.get_students_by_major(\"Mathematics\")\n\n self.assertEqual(cs_students, [\"John\", \"Bob\"])\n self.assertEqual(math_students, [])\n\n def test_get_students_by_major3(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Mathematics\"}]\n\n cs_students = self.registration_system.get_students_by_major(\"Computer Science\")\n math_students = self.registration_system.get_students_by_major(\"Mathematics\")\n\n self.assertEqual(cs_students, [\"John\", \"Bob\"])\n self.assertEqual(math_students, [\"Alice\"])\n\n def test_get_students_by_major4(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Mathematics\"},\n {\"name\": \"Tom\", \"major\": \"Mathematics\"},\n {\"name\": \"Jerry\", \"major\": \"Mathematics\"}]\n\n cs_students = self.registration_system.get_students_by_major(\"Computer Science\")\n math_students = self.registration_system.get_students_by_major(\"Mathematics\")\n self.assertEqual(cs_students, [\"John\", \"Bob\"])\n self.assertEqual(math_students, [\"Alice\", \"Tom\", \"Jerry\"])",
"solution_code": "def get_students_by_major(self, major):\n student_list = []\n for student in self.students:\n if student[\"major\"] == major:\n student_list.append(student[\"name\"])\n return student_list",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.students"
],
"method_dependencies": []
}
},
{
"method_name": "get_all_major",
"method_description": "def get_all_major(self):\n \"\"\"\n get all majors in the system\n :return a list of majors\n >>> registration_system = ClassRegistrationSystem()\n >>> registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"}],\n >>> registration_system.get_all_major(student1)\n [\"Computer Science\"]\n \"\"\"",
"test_class": "ClassRegistrationSystemTestGetMajor",
"test_code": "class ClassRegistrationSystemTestGetMajor(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_get_all_major(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"}]\n\n majors = self.registration_system.get_all_major()\n\n self.assertEqual(majors, [\"Computer Science\"])\n\n def test_get_all_major2(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Mathematics\"}]\n\n majors = self.registration_system.get_all_major()\n\n self.assertEqual(majors, [\"Computer Science\", \"Mathematics\"])\n\n def test_get_all_major3(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Mathematics\"},\n {\"name\": \"Tom\", \"major\": \"Mathematics\"},\n {\"name\": \"Jerry\", \"major\": \"Physics\"}]\n\n majors = self.registration_system.get_all_major()\n\n self.assertEqual(majors, [\"Computer Science\", \"Mathematics\", \"Physics\"])",
"solution_code": "def get_all_major(self):\n major_list = []\n for student in self.students:\n if student[\"major\"] not in major_list:\n major_list.append(student[\"major\"])\n return major_list",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.students"
],
"method_dependencies": []
}
},
{
"method_name": "get_most_popular_class_in_major",
"method_description": "def get_most_popular_class_in_major(self, major):\n \"\"\"\n get the class with the highest enrollment in the major.\n :return a string of the most popular class in this major\n >>> registration_system = ClassRegistrationSystem()\n >>> registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Computer Science\"}]\n >>> registration_system.students_registration_classes = {\"John\": [\"Algorithms\", \"Data Structures\"],\n \"Bob\": [\"Operating Systems\", \"Data Structures\", \"Algorithms\"]}\n >>> registration_system.get_most_popular_class_in_major(\"Computer Science\")\n \"Data Structures\"\n \"\"\"",
"test_class": "ClassRegistrationSystemTestPopularClass",
"test_code": "class ClassRegistrationSystemTestPopularClass(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_get_most_popular_class_in_major(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Computer Science\"}]\n\n self.registration_system.students_registration_classes = {\"John\": [\"Algorithms\", \"Data Structures\"],\n \"Bob\": [\"Operating Systems\", \"Data Structures\", \"Algorithms\"],\n \"Alice\": [\"Data Structures\", \"Operating Systems\", \"Calculus\"]}\n\n cs_most_popular_class = self.registration_system.get_most_popular_class_in_major(\"Computer Science\")\n\n self.assertEqual(cs_most_popular_class, \"Data Structures\")\n\n def test_get_most_popular_class_in_major2(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Computer Science\"},\n {\"name\": \"Tom\", \"major\": \"Mathematics\"},\n {\"name\": \"Jerry\", \"major\": \"Mathematics\"}]\n\n self.registration_system.students_registration_classes = {\"John\": [\"Algorithms\", \"Data Structures\"],\n \"Bob\": [\"Data Structures\", \"Algorithms\",\n \"Operating Systems\"],\n \"Alice\": [\"Data Structures\", \"Operating Systems\",\n \"Calculus\"],\n \"Tom\": [\"Calculus\", \"Linear Algebra\"],\n \"Jerry\": [\"Linear Algebra\", \"Statistics\"]}\n\n cs_most_popular_class = self.registration_system.get_most_popular_class_in_major(\"Computer Science\")\n math_most_popular_class = self.registration_system.get_most_popular_class_in_major(\"Mathematics\")\n self.assertEqual(cs_most_popular_class, \"Data Structures\")\n self.assertEqual(math_most_popular_class, \"Linear Algebra\")",
"solution_code": "def get_most_popular_class_in_major(self, major):\n class_list = []\n for student in self.students:\n if student[\"major\"] == major:\n class_list += self.students_registration_classes[student[\"name\"]]\n most_popular_class = max(set(class_list), key=class_list.count)\n return most_popular_class",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.students",
"self.students_registration_classes"
],
"method_dependencies": []
}
}
] | ClassRegistrationSystem | [
"ClassRegistrationSystemTestRegisterStudent",
"ClassRegistrationSystemTestRegisterClass",
"ClassRegistrationSystemTestGetStudent",
"ClassRegistrationSystemTestGetMajor",
"ClassRegistrationSystemTestPopularClass",
"ClassRegistrationSystemTest"
] | class ClassRegistrationSystem:
def __init__(self):
"""
Initialize the registration system with the attribute students and students_registration_class.
students is a list of student dictionaries, each student dictionary has the key of name and major.
students_registration_class is a dictionaries, key is the student name, value is a list of class names
"""
self.students = []
self.students_registration_classes = {}
| [
"self.students",
"self.students_registration_classes"
] |
ClassEval_23 | import math
from typing import List
class CombinationCalculator:
"""
This is a class that provides methods to calculate the number of combinations for a specific count, calculate all possible combinations, and generate combinations with a specified number of elements.
"""
def __init__(self, datas: List[str]):
"""
Initialize the calculator with a list of data.
"""
self.datas = datas
@staticmethod
def count(n: int, m: int) -> int:
"""
Calculate the number of combinations for a specific count.
:param n: The total number of elements,int.
:param m: The number of elements in each combination,int.
:return: The number of combinations,int.
>>> CombinationCalculator.count(4, 2)
6
"""
@staticmethod
def count_all(n: int) -> int:
"""
Calculate the number of all possible combinations.
:param n: The total number of elements,int.
:return: The number of all possible combinations,int,if the number of combinations is greater than 2^63-1,return float("inf").
>>> CombinationCalculator.count_all(4)
15
"""
def select(self, m: int) -> List[List[str]]:
"""
Generate combinations with a specified number of elements.
:param m: The number of elements in each combination,int.
:return: A list of combinations,List[List[str]].
>>> calc = CombinationCalculator(["A", "B", "C", "D"])
>>> calc.select(2)
[['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']]
"""
def select_all(self) -> List[List[str]]:
"""
Generate all possible combinations of selecting elements from the given data list,and it uses the select method.
:return: A list of combinations,List[List[str]].
>>> calc = CombinationCalculator(["A", "B", "C", "D"])
>>> calc.select_all()
[['A'], ['B'], ['C'], ['D'], ['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D'], ['A', 'B', 'C'], ['A', 'B', 'D'], ['A', 'C', 'D'], ['B', 'C', 'D'], ['A', 'B', 'C', 'D']]
"""
def _select(self, dataIndex: int, resultList: List[str], resultIndex: int, result: List[List[str]]):
"""
Generate combinations with a specified number of elements by recursion.
:param dataIndex: The index of the data to be selected,int.
:param resultList: The list of elements in the combination,List[str].
:param resultIndex: The index of the element in the combination,int.
:param result: The list of combinations,List[List[str]].
:return: None.
>>> calc = CombinationCalculator(["A", "B", "C", "D"])
>>> result = []
>>> calc._select(0, [None] * 2, 0, result)
>>> result
[['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']]
""" | import unittest
class CombinationCalculatorTestCount(unittest.TestCase):
def test_count(self):
self.assertEqual(CombinationCalculator.count(4, 2), 6)
def test_count_2(self):
self.assertEqual(CombinationCalculator.count(5, 3), 10)
def test_count_3(self):
self.assertEqual(CombinationCalculator.count(6, 6), 1)
def test_count_4(self):
self.assertEqual(CombinationCalculator.count(6, 0), 1)
def test_count_5(self):
self.assertEqual(CombinationCalculator.count(6, 3), 20)
class CombinationCalculatorTestCountAll(unittest.TestCase):
def test_count_all(self):
self.assertEqual(CombinationCalculator.count_all(4), 15)
def test_count_all_2(self):
self.assertEqual(CombinationCalculator.count_all(-1), False)
def test_count_all_3(self):
self.assertEqual(CombinationCalculator.count_all(65), False)
def test_count_all_4(self):
self.assertEqual(CombinationCalculator.count_all(0), 0)
def test_count_all_5(self):
self.assertEqual(CombinationCalculator.count_all(63), float("inf"))
class CombinationCalculatorTestSelect(unittest.TestCase):
def test_select(self):
calc = CombinationCalculator(["A", "B", "C", "D"])
self.assertEqual(calc.count(4, 2), 6)
def test_select_2(self):
calc = CombinationCalculator(["A", "B", "C", "D"])
self.assertEqual(calc.count(5, 3), 10)
def test_select_3(self):
calc = CombinationCalculator(["A", "B", "C", "D"])
self.assertEqual(calc.count(6, 6), 1)
def test_select_4(self):
calc = CombinationCalculator(["A", "B", "C", "D"])
self.assertEqual(calc.count(6, 0), 1)
def test_select_5(self):
calc = CombinationCalculator(["A", "B", "C", "D"])
self.assertEqual(calc.count(6, 3), 20)
class CombinationCalculatorTestSelectAll(unittest.TestCase):
def test_select_all(self):
calc = CombinationCalculator(["A"])
self.assertEqual(calc.select_all(), [['A']])
def test_select_all_2(self):
calc = CombinationCalculator(["A", "B"])
self.assertEqual(calc.select_all(), [['A'], ['B'], ['A', 'B']])
def test_select_all_3(self):
calc = CombinationCalculator(["A", "B", "C"])
self.assertEqual(calc.select_all(),[['A'], ['B'], ['C'], ['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'B', 'C']])
def test_select_all_4(self):
calc = CombinationCalculator([])
self.assertEqual(calc.select_all(),[])
def test_select_all_5(self):
calc = CombinationCalculator(["B"])
self.assertEqual(calc.select_all(),[['B']])
class CombinationCalculatorTestSelect2(unittest.TestCase):
def test_select2(self):
calc = CombinationCalculator(["A", "B", "C", "D"])
result = []
calc._select(0, [None] * 2, 0, result)
self.assertEqual(result, [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']])
def test_select2_2(self):
calc = CombinationCalculator(["A", "B", "C", "D"])
result = []
calc._select(0, [None] * 3, 0, result)
self.assertEqual(result, [['A', 'B', 'C'], ['A', 'B', 'D'], ['A', 'C', 'D'], ['B', 'C', 'D']])
def test_select2_3(self):
calc = CombinationCalculator(["A", "B", "C", "D"])
result = []
calc._select(0, [None] * 1, 0, result)
self.assertEqual(result, [['A'], ['B'], ['C'], ['D']])
def test_select2_4(self):
calc = CombinationCalculator(["A", "B", "C", "D"])
result = []
calc._select(0, [None] * 0, 0, result)
self.assertEqual(result, [[]])
def test_select2_5(self):
calc = CombinationCalculator(["A", "B", "C", "D"])
result = []
calc._select(0, [None] * 4, 0, result)
self.assertEqual(result, [['A', 'B', 'C', 'D']])
class CombinationCalculatorTestMain(unittest.TestCase):
def test_main(self):
calc = CombinationCalculator(["A", "B", "C", "D"])
self.assertEqual(calc.count(4, 2), 6)
self.assertEqual(calc.count_all(4), 15)
self.assertEqual(calc.select(2), [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']])
self.assertEqual(calc.select_all(), [['A'], ['B'], ['C'], ['D'], ['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D'], ['A', 'B', 'C'], ['A', 'B', 'D'], ['A', 'C', 'D'], ['B', 'C', 'D'], ['A', 'B', 'C', 'D']])
result = []
calc._select(0, [None] * 2, 0, result)
self.assertEqual(result, [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']]) | import math
from typing import List
class CombinationCalculator:
def __init__(self, datas: List[str]):
self.datas = datas
@staticmethod
def count(n: int, m: int) -> int:
if m == 0 or n == m:
return 1
return math.factorial(n) // (math.factorial(n - m) * math.factorial(m))
@staticmethod
def count_all(n: int) -> int:
if n < 0 or n > 63:
return False
return (1 << n) - 1 if n != 63 else float("inf")
def select(self, m: int) -> List[List[str]]:
result = []
self._select(0, [None] * m, 0, result)
return result
def select_all(self) -> List[List[str]]:
result = []
for i in range(1, len(self.datas) + 1):
result.extend(self.select(i))
return result
def _select(self, dataIndex: int, resultList: List[str], resultIndex: int, result: List[List[str]]):
resultLen = len(resultList)
resultCount = resultIndex + 1
if resultCount > resultLen:
result.append(resultList.copy())
return
for i in range(dataIndex, len(self.datas) + resultCount - resultLen):
resultList[resultIndex] = self.datas[i]
self._select(i + 1, resultList, resultIndex + 1, result) | [
"import math",
"from typing import List"
] | """
This is a class that provides methods to calculate the number of combinations for a specific count, calculate all possible combinations, and generate combinations with a specified number of elements.
"""
| [
{
"method_name": "count",
"method_description": "def count(n: int, m: int) -> int:\n \"\"\"\n Calculate the number of combinations for a specific count.\n :param n: The total number of elements,int.\n :param m: The number of elements in each combination,int.\n :return: The number of combinations,int.\n >>> CombinationCalculator.count(4, 2)\n 6\n \"\"\"",
"test_class": "CombinationCalculatorTestCount",
"test_code": "class CombinationCalculatorTestCount(unittest.TestCase):\n def test_count(self):\n self.assertEqual(CombinationCalculator.count(4, 2), 6)\n def test_count_2(self):\n self.assertEqual(CombinationCalculator.count(5, 3), 10)\n\n def test_count_3(self):\n self.assertEqual(CombinationCalculator.count(6, 6), 1)\n\n def test_count_4(self):\n self.assertEqual(CombinationCalculator.count(6, 0), 1)\n\n def test_count_5(self):\n self.assertEqual(CombinationCalculator.count(6, 3), 20)",
"solution_code": "def count(n: int, m: int) -> int:\n if m == 0 or n == m:\n return 1\n return math.factorial(n) // (math.factorial(n - m) * math.factorial(m))",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"math"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "count_all",
"method_description": "@staticmethod\n def count_all(n: int) -> int:\n \"\"\"\n Calculate the number of all possible combinations.\n :param n: The total number of elements,int.\n :return: The number of all possible combinations,int,if the number of combinations is greater than 2^63-1,return float(\"inf\").\n >>> CombinationCalculator.count_all(4)\n 15\n \"\"\"",
"test_class": "CombinationCalculatorTestCountAll",
"test_code": "class CombinationCalculatorTestCountAll(unittest.TestCase):\n def test_count_all(self):\n self.assertEqual(CombinationCalculator.count_all(4), 15)\n\n def test_count_all_2(self):\n self.assertEqual(CombinationCalculator.count_all(-1), False)\n\n def test_count_all_3(self):\n self.assertEqual(CombinationCalculator.count_all(65), False)\n\n def test_count_all_4(self):\n self.assertEqual(CombinationCalculator.count_all(0), 0)\n\n def test_count_all_5(self):\n self.assertEqual(CombinationCalculator.count_all(63), float(\"inf\"))",
"solution_code": "@staticmethod\n def count_all(n: int) -> int:\n if n < 0 or n > 63:\n return False\n return (1 << n) - 1 if n != 63 else float(\"inf\")",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "select",
"method_description": "def select(self, m: int) -> List[List[str]]:\n \"\"\"\n Generate combinations with a specified number of elements.\n :param m: The number of elements in each combination,int.\n :return: A list of combinations,List[List[str]].\n >>> calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n >>> calc.select(2)\n [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']]\n\n \"\"\"",
"test_class": "CombinationCalculatorTestSelect",
"test_code": "class CombinationCalculatorTestSelect(unittest.TestCase):\n def test_select(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(4, 2), 6)\n\n def test_select_2(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(5, 3), 10)\n\n def test_select_3(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(6, 6), 1)\n\n def test_select_4(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(6, 0), 1)\n\n def test_select_5(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(6, 3), 20)",
"solution_code": "def select(self, m: int) -> List[List[str]]:\n result = []\n self._select(0, [None] * m, 0, result)\n return result",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"_select"
]
}
},
{
"method_name": "select_all",
"method_description": "def select_all(self) -> List[List[str]]:\n \"\"\"\n Generate all possible combinations of selecting elements from the given data list,and it uses the select method.\n :return: A list of combinations,List[List[str]].\n >>> calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n >>> calc.select_all()\n [['A'], ['B'], ['C'], ['D'], ['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D'], ['A', 'B', 'C'], ['A', 'B', 'D'], ['A', 'C', 'D'], ['B', 'C', 'D'], ['A', 'B', 'C', 'D']]\n\n \"\"\"",
"test_class": "CombinationCalculatorTestSelectAll",
"test_code": "class CombinationCalculatorTestSelectAll(unittest.TestCase):\n def test_select_all(self):\n calc = CombinationCalculator([\"A\"])\n self.assertEqual(calc.select_all(), [['A']])\n\n def test_select_all_2(self):\n calc = CombinationCalculator([\"A\", \"B\"])\n self.assertEqual(calc.select_all(), [['A'], ['B'], ['A', 'B']])\n\n def test_select_all_3(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\"])\n self.assertEqual(calc.select_all(),[['A'], ['B'], ['C'], ['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'B', 'C']])\n\n def test_select_all_4(self):\n calc = CombinationCalculator([])\n self.assertEqual(calc.select_all(),[])\n\n def test_select_all_5(self):\n calc = CombinationCalculator([\"B\"])\n self.assertEqual(calc.select_all(),[['B']])",
"solution_code": "def select_all(self) -> List[List[str]]:\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": "_select",
"method_description": "def _select(self, dataIndex: int, resultList: List[str], resultIndex: int, result: List[List[str]]):\n \"\"\"\n Generate combinations with a specified number of elements by recursion.\n :param dataIndex: The index of the data to be selected,int.\n :param resultList: The list of elements in the combination,List[str].\n :param resultIndex: The index of the element in the combination,int.\n :param result: The list of combinations,List[List[str]].\n :return: None.\n >>> calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n >>> result = []\n >>> calc._select(0, [None] * 2, 0, result)\n >>> result\n [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']]\n\n \"\"\"",
"test_class": "CombinationCalculatorTestSelect2",
"test_code": "class CombinationCalculatorTestSelect2(unittest.TestCase):\n def test_select2(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 2, 0, result)\n self.assertEqual(result, [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']])\n\n def test_select2_2(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 3, 0, result)\n self.assertEqual(result, [['A', 'B', 'C'], ['A', 'B', 'D'], ['A', 'C', 'D'], ['B', 'C', 'D']])\n\n def test_select2_3(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 1, 0, result)\n self.assertEqual(result, [['A'], ['B'], ['C'], ['D']])\n\n def test_select2_4(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 0, 0, result)\n self.assertEqual(result, [[]])\n\n def test_select2_5(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 4, 0, result)\n self.assertEqual(result, [['A', 'B', 'C', 'D']])",
"solution_code": "def _select(self, dataIndex: int, resultList: List[str], resultIndex: int, result: List[List[str]]):\n resultLen = len(resultList)\n resultCount = resultIndex + 1\n if resultCount > resultLen:\n result.append(resultList.copy())\n return\n\n for i in range(dataIndex, len(self.datas) + resultCount - resultLen):\n resultList[resultIndex] = self.datas[i]\n self._select(i + 1, resultList, resultIndex + 1, result)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"List"
],
"field_dependencies": [
"self.datas"
],
"method_dependencies": [
"select"
]
}
}
] | CombinationCalculator | [
"CombinationCalculatorTestCount",
"CombinationCalculatorTestCountAll",
"CombinationCalculatorTestSelect",
"CombinationCalculatorTestSelectAll",
"CombinationCalculatorTestSelect2",
"CombinationCalculatorTestMain"
] | class CombinationCalculator:
def __init__(self, datas: List[str]):
"""
Initialize the calculator with a list of data.
"""
self.datas = datas
| [
"self.datas"
] |
ClassEval_24 | class ComplexCalculator:
"""
This is a class that implements addition, subtraction, multiplication, and division operations for complex numbers.
"""
def __init__(self):
pass
@staticmethod
def add(c1, c2):
"""
Adds two complex numbers.
:param c1: The first complex number,complex.
:param c2: The second complex number,complex.
:return: The sum of the two complex numbers,complex.
>>> complexCalculator = ComplexCalculator()
>>> complexCalculator.add(1+2j, 3+4j)
(4+6j)
"""
@staticmethod
def subtract(c1, c2):
"""
Subtracts two complex numbers.
:param c1: The first complex number,complex.
:param c2: The second complex number,complex.
:return: The difference of the two complex numbers,complex.
>>> complexCalculator = ComplexCalculator()
>>> complexCalculator.subtract(1+2j, 3+4j)
(-2-2j)
"""
@staticmethod
def multiply(c1, c2):
"""
Multiplies two complex numbers.
:param c1: The first complex number,complex.
:param c2: The second complex number,complex.
:return: The product of the two complex numbers,complex.
>>> complexCalculator = ComplexCalculator()
>>> complexCalculator.multiply(1+2j, 3+4j)
(-5+10j)
"""
@staticmethod
def divide(c1, c2):
"""
Divides two complex numbers.
:param c1: The first complex number,complex.
:param c2: The second complex number,complex.
:return: The quotient of the two complex numbers,complex.
>>> complexCalculator = ComplexCalculator()
>>> complexCalculator.divide(1+2j, 3+4j)
(0.44+0.08j)
""" | import unittest
class ComplexCalculatorTestAdd(unittest.TestCase):
def test_add(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.add(1+2j, 3+4j), (4+6j))
def test_add_2(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.add(-1 - 2j, -3 - 4j), (-4 - 6j))
def test_add_3(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.add(1-2j, 3-4j), (4-6j))
def test_add_4(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.add(-1+2j, -3+4j), (-4+6j))
def test_add_5(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.add(1+2j, -1-2j), (0+0j))
class ComplexCalculatorTestSubtract(unittest.TestCase):
def test_subtract(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.subtract(1+2j, 3+4j), (-2-2j))
def test_subtract_2(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.subtract(-1-2j, -3-4j), (2+2j))
def test_subtract_3(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.subtract(1-2j, 3-4j), (-2+2j))
def test_subtract_4(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.subtract(-1+2j, -3+4j), (2-2j))
def test_subtract_5(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.subtract(1+2j, 1+2j), (0+0j))
class ComplexCalculatorTestMultiply(unittest.TestCase):
def test_multiply(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.multiply(1+2j, 3+4j), (-5+10j))
def test_multiply_2(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.multiply(-1-2j, -3-4j), (-5+10j))
def test_multiply_3(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.multiply(1-2j, 3-4j), (-5-10j))
def test_multiply_4(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.multiply(-1+2j, -3+4j), (-5-10j))
def test_multiply_5(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.multiply(1+2j, -1-2j), (3-4j))
class ComplexCalculatorTestDivide(unittest.TestCase):
def test_divide(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.divide(1+2j, 3+4j), (0.44+0.08j))
def test_divide_2(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.divide(-1-2j, -3-4j), (0.44+0.08j))
def test_divide_3(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.divide(1-2j, 3-4j), (0.44-0.08j))
def test_divide_4(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.divide(-1+2j, -3+4j), (0.44-0.08j))
def test_divide_5(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.divide(1+2j, -1-2j), (-1+0j))
class ComplexCalculatorTestMain(unittest.TestCase):
def test_main(self):
complexCalculator = ComplexCalculator()
self.assertEqual(complexCalculator.add(1+2j, 3+4j), (4+6j))
self.assertEqual(complexCalculator.subtract(1+2j, 3+4j), (-2-2j))
self.assertEqual(complexCalculator.multiply(1+2j, 3+4j), (-5+10j))
self.assertEqual(complexCalculator.divide(1+2j, 3+4j), (0.44+0.08j)) | class ComplexCalculator:
def __init__(self):
pass
@staticmethod
def add(c1, c2):
real = c1.real + c2.real
imaginary = c1.imag + c2.imag
answer = complex(real, imaginary)
return answer
@staticmethod
def subtract(c1, c2):
real = c1.real - c2.real
imaginary = c1.imag - c2.imag
return complex(real, imaginary)
@staticmethod
def multiply(c1, c2):
real = c1.real * c2.real - c1.imag * c2.imag
imaginary = c1.real * c2.imag + c1.imag * c2.real
return complex(real, imaginary)
@staticmethod
def divide(c1, c2):
denominator = c2.real**2 + c2.imag**2
real = (c1.real * c2.real + c1.imag * c2.imag) / denominator
imaginary = (c1.imag * c2.real - c1.real * c2.imag) / denominator
return complex(real, imaginary) | [] | """
This is a class that implements addition, subtraction, multiplication, and division operations for complex numbers.
"""
| [
{
"method_name": "add",
"method_description": "def add(c1, c2):\n \"\"\"\n Adds two complex numbers.\n :param c1: The first complex number,complex.\n :param c2: The second complex number,complex.\n :return: The sum of the two complex numbers,complex.\n >>> complexCalculator = ComplexCalculator()\n >>> complexCalculator.add(1+2j, 3+4j)\n (4+6j)\n\n \"\"\"",
"test_class": "ComplexCalculatorTestAdd",
"test_code": "class ComplexCalculatorTestAdd(unittest.TestCase):\n def test_add(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(1+2j, 3+4j), (4+6j))\n\n def test_add_2(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(-1 - 2j, -3 - 4j), (-4 - 6j))\n\n def test_add_3(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(1-2j, 3-4j), (4-6j))\n\n def test_add_4(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(-1+2j, -3+4j), (-4+6j))\n\n def test_add_5(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(1+2j, -1-2j), (0+0j))",
"solution_code": "def add(c1, c2):\n real = c1.real + c2.real\n imaginary = c1.imag + c2.imag\n answer = complex(real, imaginary)\n return answer",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "subtract",
"method_description": "@staticmethod\n def subtract(c1, c2):\n \"\"\"\n Subtracts two complex numbers.\n :param c1: The first complex number,complex.\n :param c2: The second complex number,complex.\n :return: The difference of the two complex numbers,complex.\n >>> complexCalculator = ComplexCalculator()\n >>> complexCalculator.subtract(1+2j, 3+4j)\n (-2-2j)\n\n \"\"\"",
"test_class": "ComplexCalculatorTestSubtract",
"test_code": "class ComplexCalculatorTestSubtract(unittest.TestCase):\n def test_subtract(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(1+2j, 3+4j), (-2-2j))\n\n def test_subtract_2(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(-1-2j, -3-4j), (2+2j))\n\n def test_subtract_3(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(1-2j, 3-4j), (-2+2j))\n\n def test_subtract_4(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(-1+2j, -3+4j), (2-2j))\n\n def test_subtract_5(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(1+2j, 1+2j), (0+0j))",
"solution_code": "@staticmethod\n def subtract(c1, c2):\n real = c1.real - c2.real\n imaginary = c1.imag - c2.imag\n return complex(real, imaginary)",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "multiply",
"method_description": "@staticmethod\n def multiply(c1, c2):\n \"\"\"\n Multiplies two complex numbers.\n :param c1: The first complex number,complex.\n :param c2: The second complex number,complex.\n :return: The product of the two complex numbers,complex.\n >>> complexCalculator = ComplexCalculator()\n >>> complexCalculator.multiply(1+2j, 3+4j)\n (-5+10j)\n\n \"\"\"",
"test_class": "ComplexCalculatorTestMultiply",
"test_code": "class ComplexCalculatorTestMultiply(unittest.TestCase):\n def test_multiply(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(1+2j, 3+4j), (-5+10j))\n\n def test_multiply_2(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(-1-2j, -3-4j), (-5+10j))\n\n def test_multiply_3(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(1-2j, 3-4j), (-5-10j))\n\n def test_multiply_4(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(-1+2j, -3+4j), (-5-10j))\n\n def test_multiply_5(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(1+2j, -1-2j), (3-4j))",
"solution_code": "@staticmethod\n def multiply(c1, c2):\n real = c1.real * c2.real - c1.imag * c2.imag\n imaginary = c1.real * c2.imag + c1.imag * c2.real\n return complex(real, imaginary)",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "divide",
"method_description": "@staticmethod\n def divide(c1, c2):\n \"\"\"\n Divides two complex numbers.\n :param c1: The first complex number,complex.\n :param c2: The second complex number,complex.\n :return: The quotient of the two complex numbers,complex.\n >>> complexCalculator = ComplexCalculator()\n >>> complexCalculator.divide(1+2j, 3+4j)\n (0.44+0.08j)\n\n \"\"\"",
"test_class": "ComplexCalculatorTestDivide",
"test_code": "class ComplexCalculatorTestDivide(unittest.TestCase):\n def test_divide(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(1+2j, 3+4j), (0.44+0.08j))\n\n def test_divide_2(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(-1-2j, -3-4j), (0.44+0.08j))\n\n def test_divide_3(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(1-2j, 3-4j), (0.44-0.08j))\n\n def test_divide_4(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(-1+2j, -3+4j), (0.44-0.08j))\n\n def test_divide_5(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(1+2j, -1-2j), (-1+0j))",
"solution_code": "@staticmethod\n def divide(c1, c2):\n denominator = c2.real**2 + c2.imag**2\n real = (c1.real * c2.real + c1.imag * c2.imag) / denominator\n imaginary = (c1.imag * c2.real - c1.real * c2.imag) / denominator\n return complex(real, imaginary)",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | ComplexCalculator | [
"ComplexCalculatorTestAdd",
"ComplexCalculatorTestSubtract",
"ComplexCalculatorTestMultiply",
"ComplexCalculatorTestDivide",
"ComplexCalculatorTestMain"
] | class ComplexCalculator:
def __init__(self):
pass
| [] |
ClassEval_25 | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
"""
Initializes the CookiesUtil with the specified cookies file.
:param cookies_file: The cookies file to use, str.
"""
self.cookies_file = cookies_file
self.cookies = None
def get_cookies(self, reponse):
"""
Gets the cookies from the specified response,and save it to cookies_file.
:param reponse: The response to get cookies from, dict.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.get_cookies({'cookies': {'key1': 'value1', 'key2': 'value2'}})
>>> cookies_util.cookies
{'key1': 'value1', 'key2': 'value2'}
"""
def load_cookies(self):
"""
Loads the cookies from the cookies_file to the cookies data.
:return: The cookies data, dict.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.load_cookies()
{'key1': 'value1', 'key2': 'value2'}
"""
def _save_cookies(self):
"""
Saves the cookies to the cookies_file, and returns True if successful, False otherwise.
:return: True if successful, False otherwise.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.cookies = {'key1': 'value1', 'key2': 'value2'}
>>> cookies_util._save_cookies()
True
""" | import unittest
class CookiesUtilTestGetCookies(unittest.TestCase):
def test_get_cookies(self):
self.cookies_util = CookiesUtil('cookies.json')
self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'}}
self.cookies_util.get_cookies(self.response)
self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})
def test_get_cookies_2(self):
self.cookies_util = CookiesUtil('cookies.json')
self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},
'cookies2': {'key3': 'value3', 'key4': 'value4'}}
self.cookies_util.get_cookies(self.response)
self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})
def test_get_cookies_3(self):
self.cookies_util = CookiesUtil('cookies.json')
self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},
'cookies2': {'key3': 'value3', 'key4': 'value4'},
'cookies3': {'key5': 'value5', 'key6': 'value6'}}
self.cookies_util.get_cookies(self.response)
self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})
def test_get_cookies_4(self):
self.cookies_util = CookiesUtil('cookies.json')
self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},
'cookies2': {'key3': 'value3', 'key4': 'value4'},
'cookies3': {'key5': 'value5', 'key6': 'value6'},
'cookies4': {'key7': 'value7', 'key8': 'value8'}}
self.cookies_util.get_cookies(self.response)
self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})
def test_get_cookies_5(self):
self.cookies_util = CookiesUtil('cookies.json')
self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},
'cookies2': {'key3': 'value3', 'key4': 'value4'},
'cookies3': {'key5': 'value5', 'key6': 'value6'},
'cookies4': {'key7': 'value7', 'key8': 'value8'},
'cookies5': {'key9': 'value9', 'key10': 'value10'}}
self.cookies_util.get_cookies(self.response)
self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})
class CookiesUtilTestLoadCookies(unittest.TestCase):
def test_load_cookies(self):
self.cookies_util = CookiesUtil('cookies.json')
self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})
def test_load_cookies_2(self):
self.cookies_util = CookiesUtil('cookies.json')
self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'}}
self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})
def test_load_cookies_3(self):
self.cookies_util = CookiesUtil('cookies.json')
self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},
'cookies2': {'key3': 'value3', 'key4': 'value4'}}
self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})
def test_load_cookies_4(self):
self.cookies_util = CookiesUtil('cookies.json')
self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},
'cookies2': {'key3': 'value3', 'key4': 'value4'},
'cookies3': {'key5': 'value5', 'key6': 'value6'}}
self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})
def test_load_cookies_5(self):
self.cookies_util = CookiesUtil('cookies.json')
self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},
'cookies2': {'key3': 'value3', 'key4': 'value4'},
'cookies3': {'key5': 'value5', 'key6': 'value6'},
'cookies4': {'key7': 'value7', 'key8': 'value8'}}
self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})
def test_load_cookies_6(self):
self.cookies_util = CookiesUtil('')
self.assertEqual(self.cookies_util.load_cookies(), {})
class CookiesUtilTestSaveCookies(unittest.TestCase):
def setUp(self):
self.cookies_util = CookiesUtil('cookies.json')
self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'}}
def test_save_cookies(self):
self.assertTrue(self.cookies_util._save_cookies())
def test_save_cookies_2(self):
self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},
'cookies2': {'key3': 'value3', 'key4': 'value4'}}
self.assertTrue(self.cookies_util._save_cookies())
def test_save_cookies_3(self):
self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},
'cookies2': {'key3': 'value3', 'key4': 'value4'},
'cookies3': {'key5': 'value5', 'key6': 'value6'}}
self.assertTrue(self.cookies_util._save_cookies())
def test_save_cookies_4(self):
self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},
'cookies2': {'key3': 'value3', 'key4': 'value4'},
'cookies3': {'key5': 'value5', 'key6': 'value6'},
'cookies4': {'key7': 'value7', 'key8': 'value8'}}
self.assertTrue(self.cookies_util._save_cookies())
def test_save_cookies_5(self):
self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},
'cookies2': {'key3': 'value3', 'key4': 'value4'},
'cookies3': {'key5': 'value5', 'key6': 'value6'},
'cookies4': {'key7': 'value7', 'key8': 'value8'},
'cookies5': {'key9': 'value9', 'key10': 'value10'}}
self.assertTrue(self.cookies_util._save_cookies())
def test_save_cookies_6(self):
self.cookies_util = CookiesUtil('')
self.assertFalse(self.cookies_util._save_cookies())
class CookiesUtilTestSetCookies(unittest.TestCase):
def setUp(self):
self.cookies_util = CookiesUtil('cookies.json')
self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'}}
def test_set_cookies(self):
request = {}
self.cookies_util.set_cookies(request)
self.assertEqual(request['cookies'], "cookies={'key1': 'value1', 'key2': 'value2'}")
class CookiesUtilTestMain(unittest.TestCase):
def setUp(self):
self.cookies_util = CookiesUtil('cookies.json')
self.cookies_data = {'cookies': {'key1': 'value1', 'key2': 'value2'}}
def test_main(self):
self.cookies_util.get_cookies(self.cookies_data)
self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})
self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})
self.assertTrue(self.cookies_util._save_cookies()) | import json
class CookiesUtil:
def __init__(self, cookies_file):
self.cookies_file = cookies_file
self.cookies = None
def get_cookies(self, reponse):
self.cookies = reponse['cookies']
self._save_cookies()
def load_cookies(self):
try:
with open(self.cookies_file, 'r') as file:
cookies_data = json.load(file)
return cookies_data
except FileNotFoundError:
return {}
def _save_cookies(self):
try:
with open(self.cookies_file, 'w') as file:
json.dump(self.cookies, file)
return True
except:
return False
def set_cookies(self, request):
request['cookies'] = '; '.join([f'{key}={value}' for key, value in self.cookies.items()]) | [
"import json"
] | """
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
| [
{
"method_name": "get_cookies",
"method_description": "def get_cookies(self, reponse):\n \"\"\"\n Gets the cookies from the specified response,and save it to cookies_file.\n :param reponse: The response to get cookies from, dict.\n >>> cookies_util = CookiesUtil('cookies.json')\n >>> cookies_util.get_cookies({'cookies': {'key1': 'value1', 'key2': 'value2'}})\n >>> cookies_util.cookies\n {'key1': 'value1', 'key2': 'value2'}\n\n \"\"\"",
"test_class": "CookiesUtilTestGetCookies",
"test_code": "class CookiesUtilTestGetCookies(unittest.TestCase):\n\n def test_get_cookies(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n\n def test_get_cookies_2(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n\n def test_get_cookies_3(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n\n def test_get_cookies_4(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n\n def test_get_cookies_5(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'},\n 'cookies5': {'key9': 'value9', 'key10': 'value10'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})",
"solution_code": "def get_cookies(self, reponse):\n self.cookies = reponse['cookies']\n self._save_cookies()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.cookies"
],
"method_dependencies": [
"_save_cookies"
]
}
},
{
"method_name": "load_cookies",
"method_description": "def load_cookies(self):\n \"\"\"\n Loads the cookies from the cookies_file to the cookies data.\n :return: The cookies data, dict.\n >>> cookies_util = CookiesUtil('cookies.json')\n >>> cookies_util.load_cookies()\n {'key1': 'value1', 'key2': 'value2'}\n\n \"\"\"",
"test_class": "CookiesUtilTestLoadCookies",
"test_code": "class CookiesUtilTestLoadCookies(unittest.TestCase):\n\n def test_load_cookies(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_2(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'}}\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_3(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'}}\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_4(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'}}\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_5(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'}}\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_6(self):\n self.cookies_util = CookiesUtil('')\n self.assertEqual(self.cookies_util.load_cookies(), {})",
"solution_code": "def load_cookies(self):\n try:\n with open(self.cookies_file, 'r') as file:\n cookies_data = json.load(file)\n return cookies_data\n except FileNotFoundError:\n return {}",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"json"
],
"field_dependencies": [
"self.cookies",
"self.cookies_file"
],
"method_dependencies": []
}
},
{
"method_name": "_save_cookies",
"method_description": "def _save_cookies(self):\n \"\"\"\n Saves the cookies to the cookies_file, and returns True if successful, False otherwise.\n :return: True if successful, False otherwise.\n >>> cookies_util = CookiesUtil('cookies.json')\n >>> cookies_util.cookies = {'key1': 'value1', 'key2': 'value2'}\n >>> cookies_util._save_cookies()\n True\n\n \"\"\"",
"test_class": "CookiesUtilTestSaveCookies",
"test_code": "class CookiesUtilTestSaveCookies(unittest.TestCase):\n def setUp(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'}}\n\n def test_save_cookies(self):\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_2(self):\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'}}\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_3(self):\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'}}\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_4(self):\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'}}\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_5(self):\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'},\n 'cookies5': {'key9': 'value9', 'key10': 'value10'}}\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_6(self):\n self.cookies_util = CookiesUtil('')\n self.assertFalse(self.cookies_util._save_cookies())",
"solution_code": "def _save_cookies(self):\n try:\n with open(self.cookies_file, 'w') as file:\n json.dump(self.cookies, file)\n return True\n except:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"json"
],
"field_dependencies": [
"self.cookies",
"self.cookies_file"
],
"method_dependencies": []
}
}
] | CookiesUtil | [
"CookiesUtilTestGetCookies",
"CookiesUtilTestLoadCookies",
"CookiesUtilTestSaveCookies",
"CookiesUtilTestSetCookies",
"CookiesUtilTestMain"
] | class CookiesUtil:
def __init__(self, cookies_file):
"""
Initializes the CookiesUtil with the specified cookies file.
:param cookies_file: The cookies file to use, str.
"""
self.cookies_file = cookies_file
self.cookies = None
| [
"self.cookies",
"self.cookies_file"
] |
ClassEval_26 | import csv
class CSVProcessor:
"""
This is a class for processing CSV files, including readring and writing CSV data, as well as processing specific operations and saving as a new CSV file.
"""
def __init__(self):
pass
def read_csv(self, file_name):
"""
Read the csv file by file_name, get the title and data from it
:param file_name: str, name of the csv file
:return title, data: (list, list), first row is title, the rest is data
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.read_csv('read_test.csv')
(['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])
"""
def write_csv(self, data, file_name):
"""
Write data into a csv file.
:param file_name: str, name of the csv file
:return:int, if success return 1, or 0 otherwise
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.write_csv([['a', 'b', 'c', 'd'], ['1', '2', '3', '4']], 'write_test.csv')
1
"""
def process_csv_data(self, N, save_file_name):
"""
Read a csv file into variable title and data.
Only remain the N th (from 0) column data and Capitalize them, store the title and new data into a new csv file.
Add '_process' suffix after old file name, as a new file name.
:param N: int, the N th column(from 0)
:param save_file_name, the name of file that needs to be processed.
:return:int, if success return 1, or 0 otherwise
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.read_csv('read_test.csv')
(['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])
>>> csvProcessor.process_csv_data(0, 'read_test.csv')
1
>>> csvProcessor.read_csv('read_test_process.csv')
(['a', 'b', 'c', 'd'], [['HELLO']])
""" | import unittest
import os
class CSVProcessorTestReadCSV(unittest.TestCase):
def test_read_csv_1(self):
self.file = 'read_test.csv'
with open(self.file, 'w') as f:
f.write('a,b,c,d\nhElLo,YoU,ME,LoW')
expected_title = ['a', 'b', 'c', 'd']
expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]
csvProcessor = CSVProcessor()
title, data = csvProcessor.read_csv(self.file)
self.assertEqual(expected_data, data)
self.assertEqual(expected_title, title)
def test_read_csv_2(self):
self.file = 'read_test.csv'
with open(self.file, 'w') as f:
f.write('1234\nhElLo,YoU,ME,LoW')
expected_title = ['1234']
expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]
csvProcessor = CSVProcessor()
title, data = csvProcessor.read_csv(self.file)
self.assertEqual(expected_data, data)
self.assertEqual(expected_title, title)
def test_read_csv_3(self):
self.file = 'read_test.csv'
with open(self.file, 'w') as f:
f.write('title\nhElLo,YoU,ME,LoW')
expected_title = ['title']
expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]
csvProcessor = CSVProcessor()
title, data = csvProcessor.read_csv(self.file)
self.assertEqual(expected_data, data)
self.assertEqual(expected_title, title)
def test_read_csv_4(self):
self.file = 'read_test.csv'
with open(self.file, 'w') as f:
f.write('title4\nhElLo,YoU,ME,LoW')
expected_title = ['title4']
expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]
csvProcessor = CSVProcessor()
title, data = csvProcessor.read_csv(self.file)
self.assertEqual(expected_data, data)
self.assertEqual(expected_title, title)
def test_read_csv_5(self):
self.file = 'read_test.csv'
with open(self.file, 'w') as f:
f.write('title5\nhElLo,YoU,ME,LoW')
expected_title = ['title5']
expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]
csvProcessor = CSVProcessor()
title, data = csvProcessor.read_csv(self.file)
self.assertEqual(expected_data, data)
self.assertEqual(expected_title, title)
class CSVProcessorTestWriteCSV(unittest.TestCase):
def test_write_csv_1(self):
self.file = 'read_test.csv'
file_path = self.file
csvProcessor = CSVProcessor()
data = [['a', 'b', 'c', 'd'], ['1', '2', '3', '4']]
# assert return value
self.assertEqual(1, csvProcessor.write_csv(data, file_path))
# read to test if write correctly
read_title, read_data = csvProcessor.read_csv(file_path)
self.assertEqual(read_title, data[0])
self.assertEqual(read_data[0], data[1])
os.remove(file_path)
def test_write_csv_2(self):
self.file = 'read_test.csv'
file_path = self.file
csvProcessor = CSVProcessor()
data = [['aa', 'bb', 'cc', 'dd'], ['1', '2', '3', '4']]
# assert return value
self.assertEqual(1, csvProcessor.write_csv(data, file_path))
# read to test if write correctly
read_title, read_data = csvProcessor.read_csv(file_path)
self.assertEqual(read_title, data[0])
self.assertEqual(read_data[0], data[1])
os.remove(file_path)
def test_write_csv_3(self):
self.file = 'read_test.csv'
file_path = self.file
csvProcessor = CSVProcessor()
data = [['a', 'b', 'c', 'd'], ['11', '22', '33', '44']]
# assert return value
self.assertEqual(1, csvProcessor.write_csv(data, file_path))
# read to test if write correctly
read_title, read_data = csvProcessor.read_csv(file_path)
self.assertEqual(read_title, data[0])
self.assertEqual(read_data[0], data[1])
os.remove(file_path)
def test_write_csv_4(self):
self.file = 'read_test.csv'
file_path = self.file
csvProcessor = CSVProcessor()
data = [['e', 'f', 'g', 'h'], ['1', '2', '3', '4']]
# assert return value
self.assertEqual(1, csvProcessor.write_csv(data, file_path))
# read to test if write correctly
read_title, read_data = csvProcessor.read_csv(file_path)
self.assertEqual(read_title, data[0])
self.assertEqual(read_data[0], data[1])
os.remove(file_path)
def test_write_csv_5(self):
self.file = 'read_test.csv'
file_path = self.file
csvProcessor = CSVProcessor()
data = [['a', 'b', 'c', 'd'], ['5', '6', '7', '8']]
# assert return value
self.assertEqual(1, csvProcessor.write_csv(data, file_path))
# read to test if write correctly
read_title, read_data = csvProcessor.read_csv(file_path)
self.assertEqual(read_title, data[0])
self.assertEqual(read_data[0], data[1])
os.remove(file_path)
def test_write_csv_6(self):
self.file = ''
file_path = self.file
csvProcessor = CSVProcessor()
# assert return value
self.assertEqual(0, csvProcessor.write_csv([], file_path))
class CSVProcessorTestProcessCSVData(unittest.TestCase):
def setUp(self) -> None:
self.file = 'read_test.csv'
self.file_process = 'read_test_process.csv'
with open(self.file, 'w') as f:
f.write('a,b,c,d\nhElLo,YoU,ME,LoW,aBc')
def test_process_csv_data_1(self):
title = ['a', 'b', 'c', 'd']
data = ['HELLO']
csvProcessor = CSVProcessor()
self.assertEqual(1, csvProcessor.process_csv_data(0, self.file))
read_title, read_data = csvProcessor.read_csv(self.file_process)
self.assertEqual(read_title, title)
self.assertEqual(read_data[0], data)
def test_process_csv_data_2(self):
title = ['a', 'b', 'c', 'd']
data = ['YOU']
csvProcessor = CSVProcessor()
self.assertEqual(1, csvProcessor.process_csv_data(1, self.file))
read_title, read_data = csvProcessor.read_csv(self.file_process)
self.assertEqual(read_title, title)
self.assertEqual(read_data[0], data)
def test_process_csv_data_3(self):
title = ['a', 'b', 'c', 'd']
data = ['ME']
csvProcessor = CSVProcessor()
self.assertEqual(1, csvProcessor.process_csv_data(2, self.file))
read_title, read_data = csvProcessor.read_csv(self.file_process)
self.assertEqual(read_title, title)
self.assertEqual(read_data[0], data)
def test_process_csv_data_4(self):
title = ['a', 'b', 'c', 'd']
data = ['LOW']
csvProcessor = CSVProcessor()
self.assertEqual(1, csvProcessor.process_csv_data(3, self.file))
read_title, read_data = csvProcessor.read_csv(self.file_process)
self.assertEqual(read_title, title)
self.assertEqual(read_data[0], data)
def test_process_csv_data_5(self):
title = ['a', 'b', 'c', 'd']
data = ['ABC']
csvProcessor = CSVProcessor()
self.assertEqual(1, csvProcessor.process_csv_data(4, self.file))
read_title, read_data = csvProcessor.read_csv(self.file_process)
self.assertEqual(read_title, title)
self.assertEqual(read_data[0], data)
class CSVProcessorTestMain(unittest.TestCase):
def setUp(self) -> None:
self.file = 'test.csv'
self.file_process = 'test_process.csv'
with open(self.file, 'w') as f:
f.write('a,b,c,d\nhElLo,YoU,ME,LoW')
def test_main(self):
csvProcessor = CSVProcessor()
data = [['a', 'b', 'c', 'd'], ['hElLo', 'YoU', 'ME', 'LoW']]
# assert return value
self.assertEqual(1, csvProcessor.write_csv(data, self.file))
expected_title = ['a', 'b', 'c', 'd']
expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]
title, data = csvProcessor.read_csv(self.file)
self.assertEqual(expected_data, data)
self.assertEqual(expected_title, title)
title = ['a', 'b', 'c', 'd']
data = ['HELLO']
self.assertEqual(1, csvProcessor.process_csv_data(0, self.file))
read_title, read_data = csvProcessor.read_csv(self.file_process)
self.assertEqual(read_title, title)
self.assertEqual(read_data[0], data) | import csv
class CSVProcessor:
def __init__(self):
pass
def read_csv(self, file_name):
data = []
with open(file_name, 'r') as file:
reader = csv.reader(file)
title = next(reader)
for row in reader:
data.append(row)
return title, data
def write_csv(self, data, file_name):
try:
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
return 1
except:
return 0
def process_csv_data(self, N, save_file_name):
title, data = self.read_csv(save_file_name)
column_data = [row[N] for row in data]
column_data = [row.upper() for row in column_data]
new_data = [title, column_data]
return self.write_csv(new_data, save_file_name.split('.')[0] + '_process.csv') | [
"import csv"
] | """
This is a class for processing CSV files, including readring and writing CSV data, as well as processing specific operations and saving as a new CSV file.
"""
| [
{
"method_name": "read_csv",
"method_description": "def read_csv(self, file_name):\n \"\"\"\n Read the csv file by file_name, get the title and data from it\n :param file_name: str, name of the csv file\n :return title, data: (list, list), first row is title, the rest is data\n >>> csvProcessor = CSVProcessor()\n >>> csvProcessor.read_csv('read_test.csv')\n (['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])\n \"\"\"",
"test_class": "CSVProcessorTestReadCSV",
"test_code": "class CSVProcessorTestReadCSV(unittest.TestCase):\n def test_read_csv_1(self):\n self.file = 'read_test.csv'\n\n with open(self.file, 'w') as f:\n f.write('a,b,c,d\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['a', 'b', 'c', 'd']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n def test_read_csv_2(self):\n self.file = 'read_test.csv'\n with open(self.file, 'w') as f:\n f.write('1234\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['1234']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n def test_read_csv_3(self):\n self.file = 'read_test.csv'\n\n with open(self.file, 'w') as f:\n f.write('title\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['title']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n def test_read_csv_4(self):\n self.file = 'read_test.csv'\n\n with open(self.file, 'w') as f:\n f.write('title4\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['title4']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n def test_read_csv_5(self):\n self.file = 'read_test.csv'\n\n with open(self.file, 'w') as f:\n f.write('title5\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['title5']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)",
"solution_code": "def read_csv(self, file_name):\n data = []\n with open(file_name, 'r') as file:\n reader = csv.reader(file)\n title = next(reader)\n for row in reader:\n data.append(row)\n return title, data",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"csv"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "write_csv",
"method_description": "def write_csv(self, data, file_name):\n \"\"\"\n Write data into a csv file.\n :param file_name: str, name of the csv file\n :return:int, if success return 1, or 0 otherwise\n >>> csvProcessor = CSVProcessor()\n >>> csvProcessor.write_csv([['a', 'b', 'c', 'd'], ['1', '2', '3', '4']], 'write_test.csv')\n 1\n \"\"\"",
"test_class": "CSVProcessorTestWriteCSV",
"test_code": "class CSVProcessorTestWriteCSV(unittest.TestCase):\n def test_write_csv_1(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['a', 'b', 'c', 'd'], ['1', '2', '3', '4']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_2(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['aa', 'bb', 'cc', 'dd'], ['1', '2', '3', '4']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_3(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['a', 'b', 'c', 'd'], ['11', '22', '33', '44']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_4(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['e', 'f', 'g', 'h'], ['1', '2', '3', '4']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_5(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['a', 'b', 'c', 'd'], ['5', '6', '7', '8']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_6(self):\n self.file = ''\n file_path = self.file\n csvProcessor = CSVProcessor()\n # assert return value\n self.assertEqual(0, csvProcessor.write_csv([], file_path))",
"solution_code": "def write_csv(self, data, file_name):\n try:\n with open(file_name, 'w', newline='') as file:\n writer = csv.writer(file)\n writer.writerows(data)\n return 1\n except:\n return 0",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"csv"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "process_csv_data",
"method_description": "def process_csv_data(self, N, save_file_name):\n \"\"\"\n Read a csv file into variable title and data.\n Only remain the N th (from 0) column data and Capitalize them, store the title and new data into a new csv file.\n Add '_process' suffix after old file name, as a new file name.\n :param N: int, the N th column(from 0)\n :param save_file_name, the name of file that needs to be processed.\n :return:int, if success return 1, or 0 otherwise\n >>> csvProcessor = CSVProcessor()\n >>> csvProcessor.read_csv('read_test.csv')\n (['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])\n >>> csvProcessor.process_csv_data(0, 'read_test.csv')\n 1\n >>> csvProcessor.read_csv('read_test_process.csv')\n (['a', 'b', 'c', 'd'], [['HELLO']])\n \"\"\"",
"test_class": "CSVProcessorTestProcessCSVData",
"test_code": "class CSVProcessorTestProcessCSVData(unittest.TestCase):\n def setUp(self) -> None:\n self.file = 'read_test.csv'\n self.file_process = 'read_test_process.csv'\n with open(self.file, 'w') as f:\n f.write('a,b,c,d\\nhElLo,YoU,ME,LoW,aBc')\n\n def test_process_csv_data_1(self):\n title = ['a', 'b', 'c', 'd']\n data = ['HELLO']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(0, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)\n\n def test_process_csv_data_2(self):\n title = ['a', 'b', 'c', 'd']\n data = ['YOU']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(1, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)\n\n def test_process_csv_data_3(self):\n title = ['a', 'b', 'c', 'd']\n data = ['ME']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(2, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)\n\n def test_process_csv_data_4(self):\n title = ['a', 'b', 'c', 'd']\n data = ['LOW']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(3, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)\n\n def test_process_csv_data_5(self):\n title = ['a', 'b', 'c', 'd']\n data = ['ABC']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(4, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)",
"solution_code": "def process_csv_data(self, N, save_file_name):\n title, data = self.read_csv(save_file_name)\n column_data = [row[N] for row in data]\n column_data = [row.upper() for row in column_data]\n new_data = [title, column_data]\n return self.write_csv(new_data, save_file_name.split('.')[0] + '_process.csv')",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"csv"
],
"field_dependencies": [],
"method_dependencies": [
"read_csv",
"write_csv"
]
}
}
] | CSVProcessor | [
"CSVProcessorTestReadCSV",
"CSVProcessorTestWriteCSV",
"CSVProcessorTestProcessCSVData",
"CSVProcessorTestMain"
] | class CSVProcessor:
def __init__(self):
pass
| [] |
ClassEval_27 | class CurrencyConverter:
"""
This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.
"""
def __init__(self):
"""
Initialize the exchange rate of the US dollar against various currencies
"""
self.rates = {
'USD': 1.0,
'EUR': 0.85,
'GBP': 0.72,
'JPY': 110.15,
'CAD': 1.23,
'AUD': 1.34,
'CNY': 6.40,
}
def convert(self, amount, from_currency, to_currency):
"""
Convert the value of a given currency to another currency type
:param amount: float, The value of a given currency
:param from_currency: string, source currency type
:param to_currency: string, target currency type
:return: float, value converted to another currency type
>>> cc = CurrencyConverter()
>>> cc.convert(64, 'CNY','USD')
10.0
"""
def get_supported_currencies(self):
"""
Returns a list of supported currency types
:return:list, All supported currency types
>>> cc = CurrencyConverter()
>>> cc.get_supported_currencies()
['USD','EUR','GBP','JPY','CAD','AUD','CNY']
"""
def add_currency_rate(self, currency, rate):
"""
Add a new supported currency type, return False if the currency type is already in the support list
:param currency:string, currency type to be added
:param rate:float, exchange rate for this type of currency
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.add_currency_rate('KRW', 1308.84)
self.rates['KRW'] = 1308.84
"""
def update_currency_rate(self, currency, new_rate):
"""
Update the exchange rate for a certain currency
:param currency:string
:param new_rate:float
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.update_currency_rate('CNY', 7.18)
self.rates['CNY'] = 7.18
""" | import unittest
class CurrencyConverterTestConvert(unittest.TestCase):
def test_convert_1(self):
cc = CurrencyConverter()
res = cc.convert(64, 'CNY', 'USD')
self.assertEqual(res, 10.0)
def test_convert_2(self):
cc = CurrencyConverter()
res = cc.convert(64, 'USD', 'USD')
self.assertEqual(res, 64)
def test_convert_3(self):
cc = CurrencyConverter()
res = cc.convert(64, 'CNY', 'GBP')
self.assertAlmostEqual(res, 7.1999999999999)
def test_convert_4(self):
cc = CurrencyConverter()
res = cc.convert(64, 'USD', 'GBP')
self.assertAlmostEqual(res, 46.08)
def test_convert_5(self):
cc = CurrencyConverter()
res = cc.convert(64, 'USD', 'CAD')
self.assertAlmostEqual(res, 78.72)
def test_convert_6(self):
cc = CurrencyConverter()
res = cc.convert(64, '???', 'USD')
self.assertFalse(res)
class CurrencyConverterTestGetSupportedCurrencies(unittest.TestCase):
def test_get_supported_currencies_1(self):
cc = CurrencyConverter()
res = cc.get_supported_currencies()
self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])
def test_get_supported_currencies_2(self):
cc = CurrencyConverter()
res = cc.get_supported_currencies()
self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])
def test_get_supported_currencies_3(self):
cc = CurrencyConverter()
res = cc.get_supported_currencies()
self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])
def test_get_supported_currencies_4(self):
cc = CurrencyConverter()
res = cc.get_supported_currencies()
self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])
def test_get_supported_currencies_5(self):
cc = CurrencyConverter()
res = cc.get_supported_currencies()
self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])
class CurrencyConverterTestAddCurrencyRate(unittest.TestCase):
def test_add_currency_rate_1(self):
cc = CurrencyConverter()
cc.add_currency_rate('KRW', 1308.84)
self.assertEqual(cc.rates['KRW'], 1308.84)
def test_add_currency_rate_2(self):
cc = CurrencyConverter()
cc.add_currency_rate('aaa', 1.0)
self.assertEqual(cc.rates['aaa'], 1.0)
def test_add_currency_rate_3(self):
cc = CurrencyConverter()
cc.add_currency_rate('bbb', 2.0)
self.assertEqual(cc.rates['bbb'], 2.0)
def test_add_currency_rate_4(self):
cc = CurrencyConverter()
cc.add_currency_rate('ccc', 3.0)
self.assertEqual(cc.rates['ccc'], 3.0)
def test_add_currency_rate_5(self):
cc = CurrencyConverter()
cc.add_currency_rate('ddd', 4.0)
self.assertEqual(cc.rates['ddd'], 4.0)
def test_add_currency_rate_6(self):
cc = CurrencyConverter()
res = cc.add_currency_rate('USD', 1.0)
self.assertFalse(res)
class CurrencyConverterTestUpdateCurrencyRate(unittest.TestCase):
def test_update_currency_rate_1(self):
cc = CurrencyConverter()
cc.update_currency_rate('CNY', 7.18)
self.assertEqual(cc.rates['CNY'], 7.18)
def test_update_currency_rate_2(self):
cc = CurrencyConverter()
cc.update_currency_rate('CNY', 1.0)
self.assertEqual(cc.rates['CNY'], 1.0)
def test_update_currency_rate_3(self):
cc = CurrencyConverter()
cc.update_currency_rate('CNY', 2.0)
self.assertEqual(cc.rates['CNY'], 2.0)
def test_update_currency_rate_4(self):
cc = CurrencyConverter()
cc.update_currency_rate('CNY', 3.0)
self.assertEqual(cc.rates['CNY'], 3.0)
def test_update_currency_rate_5(self):
cc = CurrencyConverter()
cc.update_currency_rate('CNY', 4.0)
self.assertEqual(cc.rates['CNY'], 4.0)
def test_update_currency_rate_6(self):
cc = CurrencyConverter()
res = cc.update_currency_rate('???', 7.18)
self.assertFalse(res)
class CurrencyConverterTest(unittest.TestCase):
def test_currencyconverter(self):
cc = CurrencyConverter()
res = cc.convert(64, 'CNY', 'USD')
self.assertEqual(res, 10.0)
res = cc.get_supported_currencies()
self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])
cc.add_currency_rate('KRW', 1308.84)
self.assertEqual(cc.rates['KRW'], 1308.84)
cc.update_currency_rate('CNY', 7.18)
self.assertEqual(cc.rates['CNY'], 7.18) | class CurrencyConverter:
def __init__(self):
self.rates = {
'USD': 1.0,
'EUR': 0.85,
'GBP': 0.72,
'JPY': 110.15,
'CAD': 1.23,
'AUD': 1.34,
'CNY': 6.40,
}
def convert(self, amount, from_currency, to_currency):
if from_currency == to_currency:
return amount
if from_currency not in self.rates or to_currency not in self.rates:
return False
from_rate = self.rates[from_currency]
to_rate = self.rates[to_currency]
converted_amount = (amount / from_rate) * to_rate
return converted_amount
def get_supported_currencies(self):
return list(self.rates.keys())
def add_currency_rate(self, currency, rate):
if currency in self.rates:
return False
self.rates[currency] = rate
def update_currency_rate(self, currency, new_rate):
if currency not in self.rates:
return False
self.rates[currency] = new_rate | [] | """
This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.
"""
| [
{
"method_name": "convert",
"method_description": "def convert(self, amount, from_currency, to_currency):\n \"\"\"\n Convert the value of a given currency to another currency type\n :param amount: float, The value of a given currency\n :param from_currency: string, source currency type\n :param to_currency: string, target currency type\n :return: float, value converted to another currency type\n >>> cc = CurrencyConverter()\n >>> cc.convert(64, 'CNY','USD')\n 10.0\n \"\"\"",
"test_class": "CurrencyConverterTestConvert",
"test_code": "class CurrencyConverterTestConvert(unittest.TestCase):\n def test_convert_1(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'CNY', 'USD')\n self.assertEqual(res, 10.0)\n\n def test_convert_2(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'USD', 'USD')\n self.assertEqual(res, 64)\n\n def test_convert_3(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'CNY', 'GBP')\n self.assertAlmostEqual(res, 7.1999999999999)\n\n def test_convert_4(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'USD', 'GBP')\n self.assertAlmostEqual(res, 46.08)\n\n def test_convert_5(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'USD', 'CAD')\n self.assertAlmostEqual(res, 78.72)\n\n def test_convert_6(self):\n cc = CurrencyConverter()\n res = cc.convert(64, '???', 'USD')\n self.assertFalse(res)",
"solution_code": "def convert(self, amount, from_currency, to_currency):\n if from_currency == to_currency:\n return amount\n\n if from_currency not in self.rates or to_currency not in self.rates:\n return False\n\n from_rate = self.rates[from_currency]\n to_rate = self.rates[to_currency]\n\n converted_amount = (amount / from_rate) * to_rate\n return converted_amount",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.rates"
],
"method_dependencies": []
}
},
{
"method_name": "get_supported_currencies",
"method_description": "def get_supported_currencies(self):\n \"\"\"\n Returns a list of supported currency types\n :return:list, All supported currency types\n >>> cc = CurrencyConverter()\n >>> cc.get_supported_currencies()\n ['USD','EUR','GBP','JPY','CAD','AUD','CNY']\n \"\"\"",
"test_class": "CurrencyConverterTestGetSupportedCurrencies",
"test_code": "class CurrencyConverterTestGetSupportedCurrencies(unittest.TestCase):\n def test_get_supported_currencies_1(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n\n def test_get_supported_currencies_2(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n\n def test_get_supported_currencies_3(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n\n def test_get_supported_currencies_4(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n\n def test_get_supported_currencies_5(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])",
"solution_code": "def get_supported_currencies(self):\n return list(self.rates.keys())",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.rates"
],
"method_dependencies": []
}
},
{
"method_name": "add_currency_rate",
"method_description": "def add_currency_rate(self, currency, rate):\n \"\"\"\n Add a new supported currency type, return False if the currency type is already in the support list\n :param currency:string, currency type to be added\n :param rate:float, exchange rate for this type of currency\n :return:If successful, returns None; if unsuccessful, returns False\n >>> cc = CurrencyConverter()\n >>> cc.add_currency_rate('KRW', 1308.84)\n self.rates['KRW'] = 1308.84\n \"\"\"",
"test_class": "CurrencyConverterTestAddCurrencyRate",
"test_code": "class CurrencyConverterTestAddCurrencyRate(unittest.TestCase):\n def test_add_currency_rate_1(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('KRW', 1308.84)\n self.assertEqual(cc.rates['KRW'], 1308.84)\n\n def test_add_currency_rate_2(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('aaa', 1.0)\n self.assertEqual(cc.rates['aaa'], 1.0)\n\n def test_add_currency_rate_3(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('bbb', 2.0)\n self.assertEqual(cc.rates['bbb'], 2.0)\n\n def test_add_currency_rate_4(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('ccc', 3.0)\n self.assertEqual(cc.rates['ccc'], 3.0)\n\n def test_add_currency_rate_5(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('ddd', 4.0)\n self.assertEqual(cc.rates['ddd'], 4.0)\n\n def test_add_currency_rate_6(self):\n cc = CurrencyConverter()\n res = cc.add_currency_rate('USD', 1.0)\n self.assertFalse(res)",
"solution_code": "def add_currency_rate(self, currency, rate):\n if currency in self.rates:\n return False\n self.rates[currency] = rate",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.rates"
],
"method_dependencies": []
}
},
{
"method_name": "update_currency_rate",
"method_description": "def update_currency_rate(self, currency, new_rate):\n \"\"\"\n Update the exchange rate for a certain currency\n :param currency:string\n :param new_rate:float\n :return:If successful, returns None; if unsuccessful, returns False\n >>> cc = CurrencyConverter()\n >>> cc.update_currency_rate('CNY', 7.18)\n self.rates['CNY'] = 7.18\n \"\"\"",
"test_class": "CurrencyConverterTestUpdateCurrencyRate",
"test_code": "class CurrencyConverterTestUpdateCurrencyRate(unittest.TestCase):\n def test_update_currency_rate_1(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 7.18)\n self.assertEqual(cc.rates['CNY'], 7.18)\n\n def test_update_currency_rate_2(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 1.0)\n self.assertEqual(cc.rates['CNY'], 1.0)\n\n def test_update_currency_rate_3(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 2.0)\n self.assertEqual(cc.rates['CNY'], 2.0)\n\n def test_update_currency_rate_4(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 3.0)\n self.assertEqual(cc.rates['CNY'], 3.0)\n\n def test_update_currency_rate_5(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 4.0)\n self.assertEqual(cc.rates['CNY'], 4.0)\n\n def test_update_currency_rate_6(self):\n cc = CurrencyConverter()\n res = cc.update_currency_rate('???', 7.18)\n self.assertFalse(res)",
"solution_code": "def update_currency_rate(self, currency, new_rate):\n if currency not in self.rates:\n return False\n self.rates[currency] = new_rate",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.rates"
],
"method_dependencies": []
}
}
] | CurrencyConverter | [
"CurrencyConverterTestConvert",
"CurrencyConverterTestGetSupportedCurrencies",
"CurrencyConverterTestAddCurrencyRate",
"CurrencyConverterTestUpdateCurrencyRate",
"CurrencyConverterTest"
] | class CurrencyConverter:
def __init__(self):
"""
Initialize the exchange rate of the US dollar against various currencies
"""
self.rates = {
'USD': 1.0,
'EUR': 0.85,
'GBP': 0.72,
'JPY': 110.15,
'CAD': 1.23,
'AUD': 1.34,
'CNY': 6.40,
}
| [
"self.rates"
] |
ClassEval_28 | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.
"""
def __init__(self, database_name):
"""
Initialize database name of database processor
"""
self.database_name = database_name
def create_table(self, table_name, key1, key2):
"""
Create a new table in the database if it doesn't exist.
And make id (INTEGER) as PRIMARY KEY, make key1 as TEXT, key2 as INTEGER
:param table_name: str, the name of the table to create.
:param key1: str, the name of the first column in the table.
:param key2: str, the name of the second column in the table.
>>> db.create_table('user', 'name', 'age')
"""
def insert_into_database(self, table_name, data):
"""
Insert data into the specified table in the database.
:param table_name: str, the name of the table to insert data into.
:param data: list, a list of dictionaries where each dictionary represents a row of data.
>>> db.insert_into_database('user', [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
])
"""
def search_database(self, table_name, name):
"""
Search the specified table in the database for rows with a matching name.
:param table_name: str, the name of the table to search.
:param name: str, the name to search for.
:return: list, a list of tuples representing the rows with matching name, if any;
otherwise, returns None.
>>> db.search_database('user', 'John')
[(1, 'John', 25)]
"""
def delete_from_database(self, table_name, name):
"""
Delete rows from the specified table in the database with a matching name.
:param table_name: str, the name of the table to delete rows from.
:param name: str, the name to match for deletion.
>>> db.delete_from_database('user', 'John')
""" | import unittest
import sqlite3
class DatabaseProcessorTestCreateTable(unittest.TestCase):
def setUp(self):
self.database_name = "test.db"
self.processor = DatabaseProcessor(self.database_name)
def tearDown(self):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS test_table")
conn.commit()
conn.close()
def test_create_table_1(self):
table_name = "test_table"
self.processor.create_table(table_name, 'name', 'age')
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table_name,))
result = cursor.fetchone()
conn.close()
self.assertIsNotNone(result)
self.assertEqual(result[0], table_name)
def test_create_table_2(self):
table_name = "test_table2"
self.processor.create_table(table_name, 'name', 'age')
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table_name,))
result = cursor.fetchone()
conn.close()
self.assertIsNotNone(result)
self.assertEqual(result[0], table_name)
def test_create_table_3(self):
table_name = "test_table3"
self.processor.create_table(table_name, 'name', 'age')
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table_name,))
result = cursor.fetchone()
conn.close()
self.assertIsNotNone(result)
self.assertEqual(result[0], table_name)
def test_create_table_4(self):
table_name = "test_table4"
self.processor.create_table(table_name, 'name', 'age')
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table_name,))
result = cursor.fetchone()
conn.close()
self.assertIsNotNone(result)
self.assertEqual(result[0], table_name)
def test_create_table_5(self):
table_name = "test_table5"
self.processor.create_table(table_name, 'name', 'age')
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table_name,))
result = cursor.fetchone()
conn.close()
self.assertIsNotNone(result)
self.assertEqual(result[0], table_name)
class DatabaseProcessorTestInsertIntoDatabase(unittest.TestCase):
def setUp(self):
self.database_name = "test.db"
self.processor = DatabaseProcessor(self.database_name)
def tearDown(self):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS test_table")
conn.commit()
conn.close()
def test_insert_into_database_1(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM {table_name}")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), len(data))
self.assertEqual(result[0][2], 25)
def test_insert_into_database_2(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 15},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM {table_name}")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), len(data))
self.assertEqual(result[0][2], 15)
def test_insert_into_database_3(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 16},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM {table_name}")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), len(data))
self.assertEqual(result[0][2], 16)
def test_insert_into_database_4(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 17},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM {table_name}")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), len(data))
self.assertEqual(result[0][2], 17)
def test_insert_into_database_5(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 18},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM {table_name}")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), len(data))
self.assertEqual(result[0][2], 18)
class DatabaseProcessorTestSearchDatabase(unittest.TestCase):
def setUp(self):
self.database_name = "test.db"
self.processor = DatabaseProcessor(self.database_name)
def tearDown(self):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS test_table")
conn.commit()
conn.close()
def test_search_database_1(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
result = self.processor.search_database(table_name, 'John')
self.assertIsNotNone(result)
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'John')
def test_search_database_2(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
result = self.processor.search_database(table_name, 'Alice')
self.assertIsNotNone(result)
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'Alice')
def test_search_database_3(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
result = self.processor.search_database(table_name, 'Bob')
self.assertIsNone(result)
def test_search_database_4(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
result = self.processor.search_database(table_name, 'aaa')
self.assertIsNone(result)
def test_search_database_5(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
result = self.processor.search_database(table_name, 'bbb')
self.assertIsNone(result)
class DatabaseProcessorTestDeteleFromDatabase(unittest.TestCase):
def setUp(self):
self.database_name = "test.db"
self.processor = DatabaseProcessor(self.database_name)
def tearDown(self):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS test_table")
conn.commit()
conn.close()
def test_delete_from_database_1(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
self.processor.delete_from_database(table_name, 'John')
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM {table_name}")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'Alice')
def test_delete_from_database_2(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
self.processor.delete_from_database(table_name, 'Alice')
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM {table_name}")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'John')
def test_delete_from_database_3(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
self.processor.delete_from_database(table_name, 'John')
self.processor.delete_from_database(table_name, 'Alice')
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM {table_name}")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 0)
def test_delete_from_database_4(self):
table_name = "test_table"
data = [
{'name': 'John', 'age': 25},
{'name': 'aaa', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
self.processor.delete_from_database(table_name, 'John')
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM {table_name}")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'aaa')
def test_delete_from_database_5(self):
table_name = "test_table"
data = [
{'name': 'bbb', 'age': 25},
{'name': 'Alice', 'age': 30}
]
self.processor.create_table(table_name, 'name', 'age')
self.processor.insert_into_database(table_name, data)
self.processor.delete_from_database(table_name, 'bbb')
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM {table_name}")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'Alice')
class DatabaseProcessorTest(unittest.TestCase):
def setUp(self):
self.database_name = "test.db"
self.processor = DatabaseProcessor(self.database_name)
def tearDown(self):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS test_table")
conn.commit()
conn.close()
def test_DatabaseProcessor(self):
table_name = "test_table"
self.processor.create_table(table_name, 'name', 'age')
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table_name,))
result = cursor.fetchone()
conn.close()
self.assertIsNotNone(result)
self.assertEqual(result[0], table_name)
data = [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
]
self.processor.insert_into_database(table_name, data)
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM {table_name}")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), len(data))
self.assertEqual(result[0][2], 25)
result = self.processor.search_database(table_name, 'John')
self.assertIsNotNone(result)
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'John')
self.processor.delete_from_database(table_name, 'John')
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM {table_name}")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'Alice') | import sqlite3
import pandas as pd
class DatabaseProcessor:
def __init__(self, database_name):
self.database_name = database_name
def create_table(self, table_name, key1, key2):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
create_table_query = f"CREATE TABLE IF NOT EXISTS {table_name} (id INTEGER PRIMARY KEY, {key1} TEXT, {key2} INTEGER)"
cursor.execute(create_table_query)
conn.commit()
conn.close()
def insert_into_database(self, table_name, data):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
for item in data:
insert_query = f"INSERT INTO {table_name} (name, age) VALUES (?, ?)"
cursor.execute(insert_query, (item['name'], item['age']))
conn.commit()
conn.close()
def search_database(self, table_name, name):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
select_query = f"SELECT * FROM {table_name} WHERE name = ?"
cursor.execute(select_query, (name,))
result = cursor.fetchall()
if result:
return result
else:
return None
def delete_from_database(self, table_name, name):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
delete_query = f"DELETE FROM {table_name} WHERE name = ?"
cursor.execute(delete_query, (name,))
conn.commit()
conn.close() | [
"import sqlite3",
"import pandas as pd"
] | """
This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.
"""
| [
{
"method_name": "create_table",
"method_description": "def create_table(self, table_name, key1, key2):\n \"\"\"\n Create a new table in the database if it doesn't exist.\n And make id (INTEGER) as PRIMARY KEY, make key1 as TEXT, key2 as INTEGER\n :param table_name: str, the name of the table to create.\n :param key1: str, the name of the first column in the table.\n :param key2: str, the name of the second column in the table.\n >>> db.create_table('user', 'name', 'age')\n \"\"\"",
"test_class": "DatabaseProcessorTestCreateTable",
"test_code": "class DatabaseProcessorTestCreateTable(unittest.TestCase):\n def setUp(self):\n self.database_name = \"test.db\"\n self.processor = DatabaseProcessor(self.database_name)\n\n def tearDown(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n conn.commit()\n conn.close()\n\n def test_create_table_1(self):\n table_name = \"test_table\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n def test_create_table_2(self):\n table_name = \"test_table2\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n def test_create_table_3(self):\n table_name = \"test_table3\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n def test_create_table_4(self):\n table_name = \"test_table4\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n def test_create_table_5(self):\n table_name = \"test_table5\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)",
"solution_code": "def create_table(self, table_name, key1, key2):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n create_table_query = f\"CREATE TABLE IF NOT EXISTS {table_name} (id INTEGER PRIMARY KEY, {key1} TEXT, {key2} INTEGER)\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"sqlite3"
],
"field_dependencies": [
"self.database_name"
],
"method_dependencies": []
}
},
{
"method_name": "insert_into_database",
"method_description": "def insert_into_database(self, table_name, data):\n \"\"\"\n Insert data into the specified table in the database.\n :param table_name: str, the name of the table to insert data into.\n :param data: list, a list of dictionaries where each dictionary represents a row of data.\n >>> db.insert_into_database('user', [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ])\n \"\"\"",
"test_class": "DatabaseProcessorTestInsertIntoDatabase",
"test_code": "class DatabaseProcessorTestInsertIntoDatabase(unittest.TestCase):\n def setUp(self):\n self.database_name = \"test.db\"\n self.processor = DatabaseProcessor(self.database_name)\n\n def tearDown(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n conn.commit()\n conn.close()\n\n def test_insert_into_database_1(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 25)\n\n def test_insert_into_database_2(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 15},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 15)\n\n def test_insert_into_database_3(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 16},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 16)\n\n def test_insert_into_database_4(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 17},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 17)\n\n def test_insert_into_database_5(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 18},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 18)",
"solution_code": "def insert_into_database(self, table_name, data):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n for item in data:\n insert_query = f\"INSERT INTO {table_name} (name, age) VALUES (?, ?)\"\n cursor.execute(insert_query, (item['name'], item['age']))\n\n conn.commit()\n conn.close()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"sqlite3"
],
"field_dependencies": [
"self.database_name"
],
"method_dependencies": []
}
},
{
"method_name": "search_database",
"method_description": "def search_database(self, table_name, name):\n \"\"\"\n Search the specified table in the database for rows with a matching name.\n :param table_name: str, the name of the table to search.\n :param name: str, the name to search for.\n :return: list, a list of tuples representing the rows with matching name, if any;\n otherwise, returns None.\n >>> db.search_database('user', 'John')\n [(1, 'John', 25)]\n \"\"\"",
"test_class": "DatabaseProcessorTestSearchDatabase",
"test_code": "class DatabaseProcessorTestSearchDatabase(unittest.TestCase):\n def setUp(self):\n self.database_name = \"test.db\"\n self.processor = DatabaseProcessor(self.database_name)\n\n def tearDown(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n conn.commit()\n conn.close()\n\n def test_search_database_1(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'John')\n self.assertIsNotNone(result)\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'John')\n\n def test_search_database_2(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'Alice')\n self.assertIsNotNone(result)\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')\n\n def test_search_database_3(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'Bob')\n self.assertIsNone(result)\n\n def test_search_database_4(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'aaa')\n self.assertIsNone(result)\n\n def test_search_database_5(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'bbb')\n self.assertIsNone(result)",
"solution_code": "def search_database(self, table_name, name):\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n select_query = f\"SELECT * FROM {table_name} WHERE name = ?\"\n cursor.execute(select_query, (name,))\n result = cursor.fetchall()\n\n if result:\n return result\n else:\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"sqlite3"
],
"field_dependencies": [
"self.database_name"
],
"method_dependencies": []
}
},
{
"method_name": "delete_from_database",
"method_description": "def delete_from_database(self, table_name, name):\n \"\"\"\n Delete rows from the specified table in the database with a matching name.\n :param table_name: str, the name of the table to delete rows from.\n :param name: str, the name to match for deletion.\n >>> db.delete_from_database('user', 'John')\n \"\"\"",
"test_class": "DatabaseProcessorTestDeteleFromDatabase",
"test_code": "class DatabaseProcessorTestDeteleFromDatabase(unittest.TestCase):\n def setUp(self):\n self.database_name = \"test.db\"\n self.processor = DatabaseProcessor(self.database_name)\n\n def tearDown(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n conn.commit()\n conn.close()\n\n def test_delete_from_database_1(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'John')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')\n\n def test_delete_from_database_2(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'Alice')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'John')\n\n def test_delete_from_database_3(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'John')\n self.processor.delete_from_database(table_name, 'Alice')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_from_database_4(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'aaa', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'John')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'aaa')\n\n def test_delete_from_database_5(self):\n table_name = \"test_table\"\n data = [\n {'name': 'bbb', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'bbb')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')",
"solution_code": "def delete_from_database(self, table_name, name):\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n delete_query = f\"DELETE FROM {table_name} WHERE name = ?\"\n cursor.execute(delete_query, (name,))\n\n conn.commit()\n conn.close()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"sqlite3"
],
"field_dependencies": [
"self.database_name"
],
"method_dependencies": []
}
}
] | DatabaseProcessor | [
"DatabaseProcessorTestCreateTable",
"DatabaseProcessorTestInsertIntoDatabase",
"DatabaseProcessorTestSearchDatabase",
"DatabaseProcessorTestDeteleFromDatabase",
"DatabaseProcessorTest"
] | class DatabaseProcessor:
def __init__(self, database_name):
"""
Initialize database name of database processor
"""
self.database_name = database_name
| [
"self.database_name"
] |
ClassEval_29 | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def mean(self, data):
"""
Calculate the average value of a group of data, accurate to two digits after the Decimal separator
:param data:list, data list
:return:float, the mean value
>>> ds = DataStatistics()
>>> ds.mean([1, 2, 3, 4, 5])
3.00
"""
def median(self, data):
"""
Calculate the median of a group of data, accurate to two digits after the Decimal separator
:param data:list, data list
:return:float, the median value
>>> ds = DataStatistics()
>>> ds.median([2, 5, 1, 3, 4])
3.00
"""
def mode(self, data):
"""
Calculate the mode of a set of data
:param data:list, data list
:return:float, the mode
>>> ds = DataStatistics()
>>> ds.mode([2, 2, 3, 3, 4])
[2, 3]
""" | import unittest
class DataStatisticsTestMean(unittest.TestCase):
def test_mean_1(self):
ds = DataStatistics()
res = ds.mean([1, 2, 3, 4, 5])
self.assertEqual(res, 3.00)
def test_mean_2(self):
ds = DataStatistics()
res = ds.mean([1, 2, 3, 4, 5, 6])
self.assertEqual(res, 3.50)
def test_mean_3(self):
ds = DataStatistics()
res = ds.mean([1, 2, 4, 5, 6, 7])
self.assertEqual(res, 4.17)
def test_mean_4(self):
ds = DataStatistics()
res = ds.mean([1, 2, 4, 5, 6, 7, 8])
self.assertEqual(res, 4.71)
def test_mean_5(self):
ds = DataStatistics()
res = ds.mean([1, 2, 4, 5, 6, 7, 8, 9])
self.assertEqual(res, 5.25)
class DataStatisticsTestMedian(unittest.TestCase):
def test_median_1(self):
ds = DataStatistics()
res = ds.median([2, 5, 1, 3, 4])
self.assertEqual(res, 3)
def test_median_2(self):
ds = DataStatistics()
res = ds.median([2, 5, 1, 3, 4, 6])
self.assertEqual(res, 3.50)
def test_median_3(self):
ds = DataStatistics()
res = ds.median([2, 5, 1, 4, 6, 7])
self.assertEqual(res, 4.5)
def test_median_4(self):
ds = DataStatistics()
res = ds.median([2, 5, 1, 4, 6, 7, 8])
self.assertEqual(res, 5)
def test_median_5(self):
ds = DataStatistics()
res = ds.median([2, 5, 1, 4, 6, 7, 8, 9])
self.assertEqual(res, 5.5)
class DataStatisticsTestMode(unittest.TestCase):
def test_mode_1(self):
ds = DataStatistics()
res = ds.mode([2, 2, 3, 3, 4])
self.assertEqual(res, [2, 3])
def test_mode_2(self):
ds = DataStatistics()
res = ds.mode([2, 2, 2, 3, 3, 4])
self.assertEqual(res, [2])
def test_mode_3(self):
ds = DataStatistics()
res = ds.mode([2, 2, 3, 3, 4, 4])
self.assertEqual(res, [2, 3, 4])
def test_mode_4(self):
ds = DataStatistics()
res = ds.mode([2, 2, 3, 3, 4, 4, 4])
self.assertEqual(res, [4])
def test_mode_5(self):
ds = DataStatistics()
res = ds.mode([2, 2, 3, 3, 4, 4, 4, 5])
self.assertEqual(res, [4])
class DataStatisticsTest(unittest.TestCase):
def test_datastatistics(self):
ds = DataStatistics()
res = ds.mean([1, 2, 3, 4, 5])
self.assertEqual(res, 3.00)
res = ds.median([2, 5, 1, 3, 4])
self.assertEqual(res, 3.00)
res = ds.mode([2, 2, 3, 3, 4])
self.assertEqual(res, [2, 3]) | from collections import Counter
class DataStatistics:
def mean(self, data):
return round(sum(data) / len(data), 2)
def median(self, data):
sorted_data = sorted(data)
n = len(sorted_data)
if n % 2 == 0:
middle = n // 2
return round((sorted_data[middle - 1] + sorted_data[middle]) / 2, 2)
else:
middle = n // 2
return sorted_data[middle]
def mode(self, data):
counter = Counter(data)
mode_count = max(counter.values())
mode = [x for x, count in counter.items() if count == mode_count]
return mode | [
"from collections import Counter"
] | """
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
| [
{
"method_name": "mean",
"method_description": "def mean(self, data):\n \"\"\"\n Calculate the average value of a group of data, accurate to two digits after the Decimal separator\n :param data:list, data list\n :return:float, the mean value\n >>> ds = DataStatistics()\n >>> ds.mean([1, 2, 3, 4, 5])\n 3.00\n \"\"\"",
"test_class": "DataStatisticsTestMean",
"test_code": "class DataStatisticsTestMean(unittest.TestCase):\n def test_mean_1(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 3, 4, 5])\n self.assertEqual(res, 3.00)\n\n def test_mean_2(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 3, 4, 5, 6])\n self.assertEqual(res, 3.50)\n\n def test_mean_3(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 4, 5, 6, 7])\n self.assertEqual(res, 4.17)\n\n def test_mean_4(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 4, 5, 6, 7, 8])\n self.assertEqual(res, 4.71)\n\n def test_mean_5(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 4, 5, 6, 7, 8, 9])\n self.assertEqual(res, 5.25)",
"solution_code": "def mean(self, data):\n return round(sum(data) / len(data), 2)",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "median",
"method_description": "def median(self, data):\n \"\"\"\n Calculate the median of a group of data, accurate to two digits after the Decimal separator\n :param data:list, data list\n :return:float, the median value\n >>> ds = DataStatistics()\n >>> ds.median([2, 5, 1, 3, 4])\n 3.00\n \"\"\"",
"test_class": "DataStatisticsTestMedian",
"test_code": "class DataStatisticsTestMedian(unittest.TestCase):\n def test_median_1(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 3, 4])\n self.assertEqual(res, 3)\n\n def test_median_2(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 3, 4, 6])\n self.assertEqual(res, 3.50)\n\n def test_median_3(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 4, 6, 7])\n self.assertEqual(res, 4.5)\n\n def test_median_4(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 4, 6, 7, 8])\n self.assertEqual(res, 5)\n\n def test_median_5(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 4, 6, 7, 8, 9])\n self.assertEqual(res, 5.5)",
"solution_code": "def median(self, data):\n sorted_data = sorted(data)\n n = len(sorted_data)\n if n % 2 == 0:\n middle = n // 2\n return round((sorted_data[middle - 1] + sorted_data[middle]) / 2, 2)\n else:\n middle = n // 2\n return sorted_data[middle]",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "mode",
"method_description": "def mode(self, data):\n \"\"\"\n Calculate the mode of a set of data\n :param data:list, data list\n :return:float, the mode\n >>> ds = DataStatistics()\n >>> ds.mode([2, 2, 3, 3, 4])\n [2, 3]\n \"\"\"",
"test_class": "DataStatisticsTestMode",
"test_code": "class DataStatisticsTestMode(unittest.TestCase):\n def test_mode_1(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 3, 3, 4])\n self.assertEqual(res, [2, 3])\n\n def test_mode_2(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 2, 3, 3, 4])\n self.assertEqual(res, [2])\n\n def test_mode_3(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 3, 3, 4, 4])\n self.assertEqual(res, [2, 3, 4])\n\n def test_mode_4(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 3, 3, 4, 4, 4])\n self.assertEqual(res, [4])\n\n def test_mode_5(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 3, 3, 4, 4, 4, 5])\n self.assertEqual(res, [4])",
"solution_code": "def mode(self, data):\n counter = Counter(data)\n mode_count = max(counter.values())\n mode = [x for x, count in counter.items() if count == mode_count]\n return mode",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"Counter"
],
"field_dependencies": [],
"method_dependencies": []
}
}
] | DataStatistics | [
"DataStatisticsTestMean",
"DataStatisticsTestMedian",
"DataStatisticsTestMode",
"DataStatisticsTest"
] | class DataStatistics:
| [] |
ClassEval_30 | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
"""
self.data = np.array(data)
def get_sum(self):
"""
Calculate the sum of data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_sum()
10
"""
def get_min(self):
"""
Calculate the minimum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_min()
1
"""
def get_max(self):
"""
Calculate the maximum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_max()
4
"""
def get_variance(self):
"""
Calculate variance, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_variance()
1.25
"""
def get_std_deviation(self):
"""
Calculate standard deviation, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_std_deviation()
1.12
"""
def get_correlation(self):
"""
Calculate correlation
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_correlation()
1.0
""" | import unittest
class DataStatistics2TestGetSum(unittest.TestCase):
def test_get_sum_1(self):
ds2 = DataStatistics2([1, 2, 3, 4])
res = ds2.get_sum()
self.assertEqual(res, 10)
def test_get_sum_2(self):
ds2 = DataStatistics2([1, 2, 203, 4])
res = ds2.get_sum()
self.assertEqual(res, 210)
def test_get_sum_3(self):
ds2 = DataStatistics2([1, 2, 33, 4])
res = ds2.get_sum()
self.assertEqual(res, 40)
def test_get_sum_4(self):
ds2 = DataStatistics2([1, 2, 333, 4])
res = ds2.get_sum()
self.assertEqual(res, 340)
def test_get_sum_5(self):
ds2 = DataStatistics2([1, 2, 6, 4])
res = ds2.get_sum()
self.assertEqual(res, 13)
class DataStatistics2TestGetMin(unittest.TestCase):
def test_get_min_1(self):
ds2 = DataStatistics2([1, 2, 3, 4])
res = ds2.get_min()
self.assertEqual(res, 1)
def test_get_min_2(self):
ds2 = DataStatistics2([1, 2, 203, 4])
res = ds2.get_min()
self.assertEqual(res, 1)
def test_get_min_3(self):
ds2 = DataStatistics2([0, -1, -3, 2])
res = ds2.get_min()
self.assertEqual(res, -3)
def test_get_min_4(self):
ds2 = DataStatistics2([-111, -1, -3, 2])
res = ds2.get_min()
self.assertEqual(res, -111)
def test_get_min_5(self):
ds2 = DataStatistics2([0, -1111, -3, 2])
res = ds2.get_min()
self.assertEqual(res, -1111)
class DataStatistics2TestGetMax(unittest.TestCase):
def test_get_max_1(self):
ds2 = DataStatistics2([1, 2, 3, 4])
res = ds2.get_max()
self.assertEqual(res, 4)
def test_get_max_2(self):
ds2 = DataStatistics2([1, 2, 203, 4])
res = ds2.get_max()
self.assertEqual(res, 203)
def test_get_max_3(self):
ds2 = DataStatistics2([-1, -4, 3, 2])
res = ds2.get_max()
self.assertEqual(res, 3)
def test_get_max_4(self):
ds2 = DataStatistics2([-1, 4, 3, 2])
res = ds2.get_max()
self.assertEqual(res, 4)
def test_get_max_5(self):
ds2 = DataStatistics2([-1, 444, 3, 2])
res = ds2.get_max()
self.assertEqual(res, 444)
class DataStatistics2TestGetVariance(unittest.TestCase):
def test_get_variance_1(self):
ds2 = DataStatistics2([1, 2, 3, 4])
res = ds2.get_variance()
self.assertEqual(res, 1.25)
def test_get_variance_2(self):
ds2 = DataStatistics2([1, 2, 203, 4])
res = ds2.get_variance()
self.assertEqual(res, 7551.25)
def test_get_variance_3(self):
ds2 = DataStatistics2([1, 4, 3, 2])
res = ds2.get_variance()
self.assertEqual(res, 1.25)
def test_get_variance_4(self):
ds2 = DataStatistics2([11, 14, 13, 12])
res = ds2.get_variance()
self.assertEqual(res, 1.25)
def test_get_variance_5(self):
ds2 = DataStatistics2([111, 114, 113, 112])
res = ds2.get_variance()
self.assertEqual(res, 1.25)
class DataStatistics2TestGetStdDeviation(unittest.TestCase):
def test_get_std_deviation_1(self):
ds2 = DataStatistics2([1, 2, 3, 4])
res = ds2.get_std_deviation()
self.assertEqual(res, 1.12)
def test_get_std_deviation_2(self):
ds2 = DataStatistics2([1, 2, 203, 4])
res = ds2.get_std_deviation()
self.assertEqual(res, 86.9)
def test_get_std_deviation_3(self):
ds2 = DataStatistics2([1, 4, 3, 2])
res = ds2.get_std_deviation()
self.assertEqual(res, 1.12)
def test_get_std_deviation_4(self):
ds2 = DataStatistics2([11, 14, 13, 12])
res = ds2.get_std_deviation()
self.assertEqual(res, 1.12)
def test_get_std_deviation_5(self):
ds2 = DataStatistics2([111, 114, 113, 112])
res = ds2.get_std_deviation()
self.assertEqual(res, 1.12)
class DataStatistics2TestGetCorrelation(unittest.TestCase):
def test_get_correlation_1(self):
ds2 = DataStatistics2([1, 2, 3, 4])
res = ds2.get_correlation()
self.assertEqual(res, 1.0)
def test_get_correlation_2(self):
ds2 = DataStatistics2([1, 2, 203, 4])
res = ds2.get_correlation()
self.assertEqual(res, 1.0)
def test_get_correlation_3(self):
ds2 = DataStatistics2([1, 4, 3, 2])
res = ds2.get_correlation()
self.assertEqual(res, 1.0)
def test_get_correlation_4(self):
ds2 = DataStatistics2([11, 14, 13, 12])
res = ds2.get_correlation()
self.assertEqual(res, 1.0)
def test_get_correlation_5(self):
ds2 = DataStatistics2([111, 114, 113, 112])
res = ds2.get_correlation()
self.assertEqual(res, 1.0)
class DataStatistics2Test(unittest.TestCase):
def test_datastatistics2(self):
ds2 = DataStatistics2([1, 2, 3, 4])
res = ds2.get_sum()
self.assertEqual(res, 10)
res = ds2.get_min()
self.assertEqual(res, 1)
res = ds2.get_max()
self.assertEqual(res, 4)
res = ds2.get_variance()
self.assertEqual(res, 1.25)
res = ds2.get_std_deviation()
self.assertEqual(res, 1.12)
res = ds2.get_correlation()
self.assertEqual(res, 1.0) | import numpy as np
class DataStatistics2:
def __init__(self, data):
self.data = np.array(data)
def get_sum(self):
return np.sum(self.data)
def get_min(self):
return np.min(self.data)
def get_max(self):
return np.max(self.data)
def get_variance(self):
return round(np.var(self.data), 2)
def get_std_deviation(self):
return round(np.std(self.data), 2)
def get_correlation(self):
return np.corrcoef(self.data, rowvar=False) | [
"import numpy as np"
] | """
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
| [
{
"method_name": "get_sum",
"method_description": "def get_sum(self):\n \"\"\"\n Calculate the sum of data\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_sum()\n 10\n \"\"\"",
"test_class": "DataStatistics2TestGetSum",
"test_code": "class DataStatistics2TestGetSum(unittest.TestCase):\n def test_get_sum_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 10)\n\n def test_get_sum_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 210)\n\n def test_get_sum_3(self):\n ds2 = DataStatistics2([1, 2, 33, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 40)\n\n def test_get_sum_4(self):\n ds2 = DataStatistics2([1, 2, 333, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 340)\n\n def test_get_sum_5(self):\n ds2 = DataStatistics2([1, 2, 6, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 13)",
"solution_code": "def get_sum(self):\n return np.sum(self.data)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.data"
],
"method_dependencies": []
}
},
{
"method_name": "get_min",
"method_description": "def get_min(self):\n \"\"\"\n Calculate the minimum value in the data\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_min()\n 1\n \"\"\"",
"test_class": "DataStatistics2TestGetMin",
"test_code": "class DataStatistics2TestGetMin(unittest.TestCase):\n def test_get_min_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_min()\n self.assertEqual(res, 1)\n\n def test_get_min_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_min()\n self.assertEqual(res, 1)\n\n def test_get_min_3(self):\n ds2 = DataStatistics2([0, -1, -3, 2])\n res = ds2.get_min()\n self.assertEqual(res, -3)\n\n def test_get_min_4(self):\n ds2 = DataStatistics2([-111, -1, -3, 2])\n res = ds2.get_min()\n self.assertEqual(res, -111)\n\n def test_get_min_5(self):\n ds2 = DataStatistics2([0, -1111, -3, 2])\n res = ds2.get_min()\n self.assertEqual(res, -1111)",
"solution_code": "def get_min(self):\n return np.min(self.data)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.data"
],
"method_dependencies": []
}
},
{
"method_name": "get_max",
"method_description": "def get_max(self):\n \"\"\"\n Calculate the maximum value in the data\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_max()\n 4\n \"\"\"",
"test_class": "DataStatistics2TestGetMax",
"test_code": "class DataStatistics2TestGetMax(unittest.TestCase):\n def test_get_max_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_max()\n self.assertEqual(res, 4)\n\n def test_get_max_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_max()\n self.assertEqual(res, 203)\n\n def test_get_max_3(self):\n ds2 = DataStatistics2([-1, -4, 3, 2])\n res = ds2.get_max()\n self.assertEqual(res, 3)\n\n def test_get_max_4(self):\n ds2 = DataStatistics2([-1, 4, 3, 2])\n res = ds2.get_max()\n self.assertEqual(res, 4)\n\n def test_get_max_5(self):\n ds2 = DataStatistics2([-1, 444, 3, 2])\n res = ds2.get_max()\n self.assertEqual(res, 444)",
"solution_code": "def get_max(self):\n return np.max(self.data)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.data"
],
"method_dependencies": []
}
},
{
"method_name": "get_variance",
"method_description": "def get_variance(self):\n \"\"\"\n Calculate variance, accurate to two digits after the Decimal separator\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_variance()\n 1.25\n \"\"\"",
"test_class": "DataStatistics2TestGetVariance",
"test_code": "class DataStatistics2TestGetVariance(unittest.TestCase):\n def test_get_variance_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_variance()\n self.assertEqual(res, 1.25)\n\n def test_get_variance_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_variance()\n self.assertEqual(res, 7551.25)\n\n def test_get_variance_3(self):\n ds2 = DataStatistics2([1, 4, 3, 2])\n res = ds2.get_variance()\n self.assertEqual(res, 1.25)\n\n def test_get_variance_4(self):\n ds2 = DataStatistics2([11, 14, 13, 12])\n res = ds2.get_variance()\n self.assertEqual(res, 1.25)\n\n def test_get_variance_5(self):\n ds2 = DataStatistics2([111, 114, 113, 112])\n res = ds2.get_variance()\n self.assertEqual(res, 1.25)",
"solution_code": "def get_variance(self):\n return round(np.var(self.data), 2)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.data"
],
"method_dependencies": []
}
},
{
"method_name": "get_std_deviation",
"method_description": "def get_std_deviation(self):\n \"\"\"\n Calculate standard deviation, accurate to two digits after the Decimal separator\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_std_deviation()\n 1.12\n \"\"\"",
"test_class": "DataStatistics2TestGetStdDeviation",
"test_code": "class DataStatistics2TestGetStdDeviation(unittest.TestCase):\n def test_get_std_deviation_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 1.12)\n\n def test_get_std_deviation_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 86.9)\n\n def test_get_std_deviation_3(self):\n ds2 = DataStatistics2([1, 4, 3, 2])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 1.12)\n\n def test_get_std_deviation_4(self):\n ds2 = DataStatistics2([11, 14, 13, 12])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 1.12)\n\n def test_get_std_deviation_5(self):\n ds2 = DataStatistics2([111, 114, 113, 112])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 1.12)",
"solution_code": "def get_std_deviation(self):\n return round(np.std(self.data), 2)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.data"
],
"method_dependencies": []
}
},
{
"method_name": "get_correlation",
"method_description": "def get_correlation(self):\n \"\"\"\n Calculate correlation\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_correlation()\n 1.0\n \"\"\"",
"test_class": "DataStatistics2TestGetCorrelation",
"test_code": "class DataStatistics2TestGetCorrelation(unittest.TestCase):\n def test_get_correlation_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)\n\n def test_get_correlation_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)\n\n def test_get_correlation_3(self):\n ds2 = DataStatistics2([1, 4, 3, 2])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)\n\n def test_get_correlation_4(self):\n ds2 = DataStatistics2([11, 14, 13, 12])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)\n\n def test_get_correlation_5(self):\n ds2 = DataStatistics2([111, 114, 113, 112])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)",
"solution_code": "def get_correlation(self):\n return np.corrcoef(self.data, rowvar=False)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.data"
],
"method_dependencies": []
}
}
] | DataStatistics2 | [
"DataStatistics2TestGetSum",
"DataStatistics2TestGetMin",
"DataStatistics2TestGetMax",
"DataStatistics2TestGetVariance",
"DataStatistics2TestGetStdDeviation",
"DataStatistics2TestGetCorrelation",
"DataStatistics2Test"
] | class DataStatistics2:
def __init__(self, data):
"""
Initialize Data List
:param data:list
"""
self.data = np.array(data)
| [
"self.data"
] |
ClassEval_31 | import math
class DataStatistics4:
"""
This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.
"""
@staticmethod
def correlation_coefficient(data1, data2):
"""
Calculate the correlation coefficient of two sets of data.
:param data1: The first set of data,list.
:param data2: The second set of data,list.
:return: The correlation coefficient, float.
>>> DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6])
0.9999999999999998
"""
@staticmethod
def skewness(data):
"""
Calculate the skewness of a set of data.
:param data: The input data list, list.
:return: The skewness, float.
>>> DataStatistics4.skewness([1, 2, 5])
2.3760224064818463
"""
@staticmethod
def kurtosis(data):
"""
Calculate the kurtosis of a set of data.
:param data: The input data list, list.
:return: The kurtosis, float.
>>> DataStatistics4.kurtosis([1, 20,100])
-1.5000000000000007
"""
@staticmethod
def pdf(data, mu, sigma):
"""
Calculate the probability density function (PDF) of a set of data under a normal distribution.
:param data: The input data list, list.
:param mu: The mean of the normal distribution, float.
:param sigma: The standard deviation of the normal distribution, float.
:return: The probability density function (PDF), list.
>>> DataStatistics4.pdf([1, 2, 3], 1, 1)
[0.3989422804014327, 0.24197072451914337, 0.05399096651318806]
""" | import unittest
class DataStatistics4TestCorrelationCoefficient(unittest.TestCase):
def test_correlation_coefficient(self):
self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6]), 0.9999999999999998)
def test_correlation_coefficient_2(self):
self.assertEqual(DataStatistics4.correlation_coefficient([1, 1, 1], [2, 2, 2]), 0)
def test_correlation_coefficient_3(self):
self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [1, 2, 3]), 0.9999999999999998)
def test_correlation_coefficient_4(self):
self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [1, 2, 4]), 0.9819805060619659)
def test_correlation_coefficient_5(self):
self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [1, 5, 3]), 0.4999999999999999)
class DataStatistics4TestSkewness(unittest.TestCase):
def test_skewness(self):
self.assertEqual(DataStatistics4.skewness([1, 2, 5]), 2.3760224064818463)
def test_skewness_2(self):
self.assertEqual(DataStatistics4.skewness([1, 1, 1]), 0)
def test_skewness_3(self):
self.assertEqual(DataStatistics4.skewness([1, 2, 3]), 0)
def test_skewness_4(self):
self.assertEqual(DataStatistics4.skewness([1, 2, 4]), 1.7181079837227264)
def test_skewness_5(self):
self.assertEqual(DataStatistics4.skewness([1, 5, 3]), 0.0)
class DataStatistics4TestKurtosis(unittest.TestCase):
def test_kurtosis(self):
self.assertEqual(DataStatistics4.kurtosis([1, 2, 5]), -1.5000000000000002)
def test_kurtosis_2(self):
self.assertTrue(math.isnan(DataStatistics4.kurtosis([1, 1, 1])))
def test_kurtosis_3(self):
self.assertEqual(DataStatistics4.kurtosis([1, 2, 3]), -1.5000000000000002)
def test_kurtosis_4(self):
self.assertEqual(DataStatistics4.kurtosis([1, 2, 4]), -1.4999999999999996)
def test_kurtosis_5(self):
self.assertEqual(DataStatistics4.kurtosis([1, 5, 3]), -1.5000000000000002)
class DataStatistics4TestPDF(unittest.TestCase):
def test_pdf(self):
self.assertEqual(DataStatistics4.pdf([1, 2, 3], 1, 1),
[0.3989422804014327, 0.24197072451914337, 0.05399096651318806])
def test_pdf_2(self):
self.assertEqual(DataStatistics4.pdf([1, 1, 1], 1, 1),
[0.3989422804014327, 0.3989422804014327, 0.3989422804014327])
def test_pdf_3(self):
self.assertEqual(DataStatistics4.pdf([1, 2, 3], 2, 1),
[0.24197072451914337, 0.3989422804014327, 0.24197072451914337])
def test_pdf_4(self):
self.assertEqual(DataStatistics4.pdf([1, 2, 3], 1, 2),
[0.19947114020071635, 0.17603266338214976, 0.12098536225957168])
def test_pdf_5(self):
self.assertEqual(DataStatistics4.pdf([1, 2, 3], 2, 2),
[0.17603266338214976, 0.19947114020071635, 0.17603266338214976])
class DataStatistics4TestMain(unittest.TestCase):
def test_main(self):
self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6]), 0.9999999999999998)
self.assertEqual(DataStatistics4.skewness([1, 2, 5]), 2.3760224064818463)
self.assertEqual(DataStatistics4.kurtosis([1, 2, 5]), -1.5000000000000002)
self.assertEqual(DataStatistics4.pdf([1, 2, 3], 1, 1),
[0.3989422804014327, 0.24197072451914337, 0.05399096651318806]) | import math
class DataStatistics4:
@staticmethod
def correlation_coefficient(data1, data2):
n = len(data1)
mean1 = sum(data1) / n
mean2 = sum(data2) / n
numerator = sum((data1[i] - mean1) * (data2[i] - mean2) for i in range(n))
denominator = math.sqrt(sum((data1[i] - mean1) ** 2 for i in range(n))) * math.sqrt(sum((data2[i] - mean2) ** 2 for i in range(n)))
return numerator / denominator if denominator != 0 else 0
@staticmethod
def skewness(data):
n = len(data)
mean = sum(data) / n
variance = sum((x - mean) ** 2 for x in data) / n
std_deviation = math.sqrt(variance)
skewness = sum((x - mean) ** 3 for x in data) * n / ((n - 1) * (n - 2) * std_deviation ** 3) if std_deviation != 0 else 0
return skewness
@staticmethod
def kurtosis(data):
n = len(data)
mean = sum(data) / n
std_dev = math.sqrt(sum((x - mean) ** 2 for x in data) / n)
if std_dev == 0:
return math.nan
centered_data = [(x - mean) for x in data]
fourth_moment = sum(x ** 4 for x in centered_data) / n
kurtosis_value = (fourth_moment / std_dev ** 4) - 3
return kurtosis_value
@staticmethod
def pdf(data, mu, sigma):
pdf_values = [1 / (sigma * math.sqrt(2 * math.pi)) * math.exp(-0.5 * ((x - mu) / sigma) ** 2) for x in data]
return pdf_values | [
"import math"
] | """
This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.
"""
| [
{
"method_name": "correlation_coefficient",
"method_description": "def correlation_coefficient(data1, data2):\n \"\"\"\n Calculate the correlation coefficient of two sets of data.\n :param data1: The first set of data,list.\n :param data2: The second set of data,list.\n :return: The correlation coefficient, float.\n >>> DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6])\n 0.9999999999999998\n\n \"\"\"",
"test_class": "DataStatistics4TestCorrelationCoefficient",
"test_code": "class DataStatistics4TestCorrelationCoefficient(unittest.TestCase):\n def test_correlation_coefficient(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6]), 0.9999999999999998)\n\n def test_correlation_coefficient_2(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 1, 1], [2, 2, 2]), 0)\n\n def test_correlation_coefficient_3(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [1, 2, 3]), 0.9999999999999998)\n\n def test_correlation_coefficient_4(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [1, 2, 4]), 0.9819805060619659)\n\n def test_correlation_coefficient_5(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [1, 5, 3]), 0.4999999999999999)",
"solution_code": "def correlation_coefficient(data1, data2):\n n = len(data1)\n mean1 = sum(data1) / n\n mean2 = sum(data2) / n\n\n numerator = sum((data1[i] - mean1) * (data2[i] - mean2) for i in range(n))\n denominator = math.sqrt(sum((data1[i] - mean1) ** 2 for i in range(n))) * math.sqrt(sum((data2[i] - mean2) ** 2 for i in range(n)))\n\n return numerator / denominator if denominator != 0 else 0",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"math"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "skewness",
"method_description": "@staticmethod\n def skewness(data):\n \"\"\"\n Calculate the skewness of a set of data.\n :param data: The input data list, list.\n :return: The skewness, float.\n >>> DataStatistics4.skewness([1, 2, 5])\n 2.3760224064818463\n\n \"\"\"",
"test_class": "DataStatistics4TestSkewness",
"test_code": "class DataStatistics4TestSkewness(unittest.TestCase):\n def test_skewness(self):\n self.assertEqual(DataStatistics4.skewness([1, 2, 5]), 2.3760224064818463)\n\n def test_skewness_2(self):\n self.assertEqual(DataStatistics4.skewness([1, 1, 1]), 0)\n\n def test_skewness_3(self):\n self.assertEqual(DataStatistics4.skewness([1, 2, 3]), 0)\n\n def test_skewness_4(self):\n self.assertEqual(DataStatistics4.skewness([1, 2, 4]), 1.7181079837227264)\n\n def test_skewness_5(self):\n self.assertEqual(DataStatistics4.skewness([1, 5, 3]), 0.0)",
"solution_code": "@staticmethod\n def skewness(data):\n n = len(data)\n mean = sum(data) / n\n variance = sum((x - mean) ** 2 for x in data) / n\n std_deviation = math.sqrt(variance)\n\n skewness = sum((x - mean) ** 3 for x in data) * n / ((n - 1) * (n - 2) * std_deviation ** 3) if std_deviation != 0 else 0\n\n return skewness",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"math"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "kurtosis",
"method_description": "@staticmethod\n def kurtosis(data):\n \"\"\"\n Calculate the kurtosis of a set of data.\n :param data: The input data list, list.\n :return: The kurtosis, float.\n >>> DataStatistics4.kurtosis([1, 20,100])\n -1.5000000000000007\n\n \"\"\"",
"test_class": "DataStatistics4TestKurtosis",
"test_code": "class DataStatistics4TestKurtosis(unittest.TestCase):\n def test_kurtosis(self):\n self.assertEqual(DataStatistics4.kurtosis([1, 2, 5]), -1.5000000000000002)\n\n def test_kurtosis_2(self):\n self.assertTrue(math.isnan(DataStatistics4.kurtosis([1, 1, 1])))\n\n def test_kurtosis_3(self):\n self.assertEqual(DataStatistics4.kurtosis([1, 2, 3]), -1.5000000000000002)\n\n def test_kurtosis_4(self):\n self.assertEqual(DataStatistics4.kurtosis([1, 2, 4]), -1.4999999999999996)\n\n def test_kurtosis_5(self):\n self.assertEqual(DataStatistics4.kurtosis([1, 5, 3]), -1.5000000000000002)",
"solution_code": "@staticmethod\n def kurtosis(data):\n\n n = len(data)\n mean = sum(data) / n\n std_dev = math.sqrt(sum((x - mean) ** 2 for x in data) / n)\n\n if std_dev == 0:\n return math.nan\n\n centered_data = [(x - mean) for x in data]\n fourth_moment = sum(x ** 4 for x in centered_data) / n\n\n kurtosis_value = (fourth_moment / std_dev ** 4) - 3\n\n return kurtosis_value",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"math"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "pdf",
"method_description": "@staticmethod\n def pdf(data, mu, sigma):\n \"\"\"\n Calculate the probability density function (PDF) of a set of data under a normal distribution.\n :param data: The input data list, list.\n :param mu: The mean of the normal distribution, float.\n :param sigma: The standard deviation of the normal distribution, float.\n :return: The probability density function (PDF), list.\n >>> DataStatistics4.pdf([1, 2, 3], 1, 1)\n [0.3989422804014327, 0.24197072451914337, 0.05399096651318806]\n\n \"\"\"",
"test_class": "DataStatistics4TestPDF",
"test_code": "class DataStatistics4TestPDF(unittest.TestCase):\n def test_pdf(self):\n self.assertEqual(DataStatistics4.pdf([1, 2, 3], 1, 1),\n [0.3989422804014327, 0.24197072451914337, 0.05399096651318806])\n\n def test_pdf_2(self):\n self.assertEqual(DataStatistics4.pdf([1, 1, 1], 1, 1),\n [0.3989422804014327, 0.3989422804014327, 0.3989422804014327])\n\n def test_pdf_3(self):\n self.assertEqual(DataStatistics4.pdf([1, 2, 3], 2, 1),\n [0.24197072451914337, 0.3989422804014327, 0.24197072451914337])\n\n def test_pdf_4(self):\n self.assertEqual(DataStatistics4.pdf([1, 2, 3], 1, 2),\n [0.19947114020071635, 0.17603266338214976, 0.12098536225957168])\n\n def test_pdf_5(self):\n self.assertEqual(DataStatistics4.pdf([1, 2, 3], 2, 2),\n [0.17603266338214976, 0.19947114020071635, 0.17603266338214976])",
"solution_code": "@staticmethod\n def pdf(data, mu, sigma):\n pdf_values = [1 / (sigma * math.sqrt(2 * math.pi)) * math.exp(-0.5 * ((x - mu) / sigma) ** 2) for x in data]\n return pdf_values",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"math"
],
"field_dependencies": [],
"method_dependencies": []
}
}
] | DataStatistics4 | [
"DataStatistics4TestCorrelationCoefficient",
"DataStatistics4TestSkewness",
"DataStatistics4TestKurtosis",
"DataStatistics4TestPDF",
"DataStatistics4TestMain"
] | class DataStatistics4:
| [] |
ClassEval_32 | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the decryption utility with a key.
:param key: The key to use for decryption,str.
"""
self.key = key
def caesar_decipher(self, ciphertext, shift):
"""
Deciphers the given ciphertext using the Caesar cipher
:param ciphertext: The ciphertext to decipher,str.
:param shift: The shift to use for decryption,int.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.caesar_decipher('ifmmp', 1)
'hello'
"""
def vigenere_decipher(self, ciphertext):
"""
Deciphers the given ciphertext using the Vigenere cipher
:param ciphertext: The ciphertext to decipher,str.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.vigenere_decipher('ifmmp')
'ybocl'
"""
def rail_fence_decipher(self, encrypted_text, rails):
"""
Deciphers the given ciphertext using the Rail Fence cipher
:param encrypted_text: The ciphertext to decipher,str.
:param rails: The number of rails to use for decryption,int.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.rail_fence_decipher('Hoo!el,Wrdl l', 3)
'Hello, World!'
""" | import unittest
class DecryptionUtilsTestCaesarDecipher(unittest.TestCase):
def test_caesar_decipher(self):
d = DecryptionUtils('key')
self.assertEqual(d.caesar_decipher('ifmmp', 1), 'hello')
def test_caesar_decipher_2(self):
d = DecryptionUtils('key')
self.assertEqual(d.caesar_decipher('bcdyza', 27), 'abcxyz')
def test_caesar_decipher_3(self):
d = DecryptionUtils('key')
self.assertEqual(d.caesar_decipher('bcd', 0), 'bcd')
def test_caesar_decipher_4(self):
d = DecryptionUtils('key')
self.assertEqual(d.caesar_decipher('bcd', 26), 'bcd')
def test_caesar_decipher_5(self):
d = DecryptionUtils('key')
self.assertEqual(d.caesar_decipher('bcd', -26), 'bcd')
def test_caesar_decipher_6(self):
d = DecryptionUtils('key')
self.assertEqual(d.caesar_decipher('IFMMP', 1), 'HELLO')
def test_caesar_decipher_7(self):
d = DecryptionUtils('key')
self.assertEqual(d.caesar_decipher('123', 1), '123')
class DecryptionUtilsTestVigenereDecipher(unittest.TestCase):
def test_vigenere_decipher(self):
d = DecryptionUtils('key')
self.assertEqual(d.vigenere_decipher('ifmmp'), 'ybocl')
def test_vigenere_decipher_2(self):
d = DecryptionUtils('key')
self.assertEqual(d.vigenere_decipher('rijvs'), 'hello')
def test_vigenere_decipher_3(self):
d = DecryptionUtils('longkey')
self.assertEqual(d.vigenere_decipher('LpPjOjE'), 'AbCdEfG')
def test_vigenere_decipher_4(self):
d = DecryptionUtils('key')
self.assertEqual(d.vigenere_decipher('bcd'), 'ryf')
def test_vigenere_decipher_5(self):
d = DecryptionUtils('key')
self.assertEqual(d.vigenere_decipher('bcdaa'), 'ryfqw')
def test_vigenere_decipher_6(self):
d = DecryptionUtils('key')
self.assertEqual(d.vigenere_decipher('123'), '123')
class DecryptionUtilsTestRailFenceDecipher(unittest.TestCase):
def test_rail_fence_decipher(self):
d = DecryptionUtils('key')
self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 3), 'Hello, World!')
def test_rail_fence_decipher_2(self):
d = DecryptionUtils('key')
self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 4), 'H!W reoldll,o')
def test_rail_fence_decipher_3(self):
d = DecryptionUtils('key')
self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 5), 'Holr d,!oeWll')
def test_rail_fence_decipher_4(self):
d = DecryptionUtils('key')
self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 6), 'Holrll d,!oeW')
def test_rail_fence_decipher_5(self):
d = DecryptionUtils('key')
self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 7), 'Hoe,rll dWl!o')
class DecryptionUtilsTestMain(unittest.TestCase):
def test_main(self):
d = DecryptionUtils('key')
self.assertEqual(d.caesar_decipher('ifmmp', 1), 'hello')
self.assertEqual(d.vigenere_decipher('ifmmp'), 'ybocl')
self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 3), 'Hello, World!') | class DecryptionUtils:
def __init__(self, key):
self.key = key
def caesar_decipher(self, ciphertext, shift):
plaintext = ""
for char in ciphertext:
if char.isalpha():
if char.isupper():
ascii_offset = 65
else:
ascii_offset = 97
shifted_char = chr((ord(char) - ascii_offset - shift) % 26 + ascii_offset)
plaintext += shifted_char
else:
plaintext += char
return plaintext
def vigenere_decipher(self, ciphertext):
decrypted_text = ""
key_index = 0
for char in ciphertext:
if char.isalpha():
shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')
decrypted_char = chr((ord(char.lower()) - ord('a') - shift) % 26 + ord('a'))
decrypted_text += decrypted_char.upper() if char.isupper() else decrypted_char
key_index += 1
else:
decrypted_text += char
return decrypted_text
def rail_fence_decipher(self, encrypted_text, rails):
fence = [['\n' for _ in range(len(encrypted_text))] for _ in range(rails)]
direction = -1
row, col = 0, 0
for _ in range(len(encrypted_text)):
if row == 0 or row == rails - 1:
direction = -direction
fence[row][col] = ''
col += 1
row += direction
index = 0
for i in range(rails):
for j in range(len(encrypted_text)):
if fence[i][j] == '':
fence[i][j] = encrypted_text[index]
index += 1
plain_text = ''
direction = -1
row, col = 0, 0
for _ in range(len(encrypted_text)):
if row == 0 or row == rails - 1:
direction = -direction
plain_text += fence[row][col]
col += 1
row += direction
return plain_text | [] | """
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
| [
{
"method_name": "caesar_decipher",
"method_description": "def caesar_decipher(self, ciphertext, shift):\n \"\"\"\n Deciphers the given ciphertext using the Caesar cipher\n :param ciphertext: The ciphertext to decipher,str.\n :param shift: The shift to use for decryption,int.\n :return: The deciphered plaintext,str.\n >>> d = DecryptionUtils('key')\n >>> d.caesar_decipher('ifmmp', 1)\n 'hello'\n\n \"\"\"",
"test_class": "DecryptionUtilsTestCaesarDecipher",
"test_code": "class DecryptionUtilsTestCaesarDecipher(unittest.TestCase):\n def test_caesar_decipher(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('ifmmp', 1), 'hello')\n\n def test_caesar_decipher_2(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('bcdyza', 27), 'abcxyz')\n\n def test_caesar_decipher_3(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('bcd', 0), 'bcd')\n\n def test_caesar_decipher_4(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('bcd', 26), 'bcd')\n\n def test_caesar_decipher_5(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('bcd', -26), 'bcd')\n\n def test_caesar_decipher_6(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('IFMMP', 1), 'HELLO')\n\n def test_caesar_decipher_7(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('123', 1), '123')",
"solution_code": "def caesar_decipher(self, ciphertext, shift):\n plaintext = \"\"\n for char in ciphertext:\n if char.isalpha():\n if char.isupper():\n ascii_offset = 65\n else:\n ascii_offset = 97\n shifted_char = chr((ord(char) - ascii_offset - shift) % 26 + ascii_offset)\n plaintext += shifted_char\n else:\n plaintext += char\n return plaintext",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "vigenere_decipher",
"method_description": "def vigenere_decipher(self, ciphertext):\n \"\"\"\n Deciphers the given ciphertext using the Vigenere cipher\n :param ciphertext: The ciphertext to decipher,str.\n :return: The deciphered plaintext,str.\n >>> d = DecryptionUtils('key')\n >>> d.vigenere_decipher('ifmmp')\n 'ybocl'\n\n \"\"\"",
"test_class": "DecryptionUtilsTestVigenereDecipher",
"test_code": "class DecryptionUtilsTestVigenereDecipher(unittest.TestCase):\n def test_vigenere_decipher(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('ifmmp'), 'ybocl')\n\n def test_vigenere_decipher_2(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('rijvs'), 'hello')\n\n def test_vigenere_decipher_3(self):\n d = DecryptionUtils('longkey')\n self.assertEqual(d.vigenere_decipher('LpPjOjE'), 'AbCdEfG')\n\n def test_vigenere_decipher_4(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('bcd'), 'ryf')\n\n def test_vigenere_decipher_5(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('bcdaa'), 'ryfqw')\n\n def test_vigenere_decipher_6(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('123'), '123')",
"solution_code": "def vigenere_decipher(self, ciphertext):\n decrypted_text = \"\"\n key_index = 0\n for char in ciphertext:\n if char.isalpha():\n shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')\n decrypted_char = chr((ord(char.lower()) - ord('a') - shift) % 26 + ord('a'))\n decrypted_text += decrypted_char.upper() if char.isupper() else decrypted_char\n key_index += 1\n else:\n decrypted_text += char\n return decrypted_text",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.key"
],
"method_dependencies": []
}
},
{
"method_name": "rail_fence_decipher",
"method_description": "def rail_fence_decipher(self, encrypted_text, rails):\n \"\"\"\n Deciphers the given ciphertext using the Rail Fence cipher\n :param encrypted_text: The ciphertext to decipher,str.\n :param rails: The number of rails to use for decryption,int.\n :return: The deciphered plaintext,str.\n >>> d = DecryptionUtils('key')\n >>> d.rail_fence_decipher('Hoo!el,Wrdl l', 3)\n 'Hello, World!'\n\n \"\"\"",
"test_class": "DecryptionUtilsTestRailFenceDecipher",
"test_code": "class DecryptionUtilsTestRailFenceDecipher(unittest.TestCase):\n def test_rail_fence_decipher(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 3), 'Hello, World!')\n\n def test_rail_fence_decipher_2(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 4), 'H!W reoldll,o')\n\n def test_rail_fence_decipher_3(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 5), 'Holr d,!oeWll')\n\n def test_rail_fence_decipher_4(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 6), 'Holrll d,!oeW')\n\n def test_rail_fence_decipher_5(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 7), 'Hoe,rll dWl!o')",
"solution_code": "def rail_fence_decipher(self, encrypted_text, rails):\n fence = [['\\n' for _ in range(len(encrypted_text))] for _ in range(rails)]\n direction = -1\n row, col = 0, 0\n\n for _ in range(len(encrypted_text)):\n if row == 0 or row == rails - 1:\n direction = -direction\n\n fence[row][col] = ''\n col += 1\n row += direction\n\n index = 0\n for i in range(rails):\n for j in range(len(encrypted_text)):\n if fence[i][j] == '':\n fence[i][j] = encrypted_text[index]\n index += 1\n\n plain_text = ''\n direction = -1\n row, col = 0, 0\n for _ in range(len(encrypted_text)):\n if row == 0 or row == rails - 1:\n direction = -direction\n\n plain_text += fence[row][col]\n col += 1\n row += direction\n\n return plain_text",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | DecryptionUtils | [
"DecryptionUtilsTestCaesarDecipher",
"DecryptionUtilsTestVigenereDecipher",
"DecryptionUtilsTestRailFenceDecipher",
"DecryptionUtilsTestMain"
] | class DecryptionUtils:
def __init__(self, key):
"""
Initializes the decryption utility with a key.
:param key: The key to use for decryption,str.
"""
self.key = key
| [
"self.key"
] |
ClassEval_33 | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, and an optional promotion.
:param customer: dict, customer information
:param cart: list of dicts, a cart of items with details
:param promotion: function, optional promotion applied to the order
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
"""
self.customer = customer
self.cart = cart
self.promotion = promotion
self.total()
def total(self):
"""
Calculate the total cost of items in the cart.
:return: float, total cost of items
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart)
>>> ds.total()
329.0
"""
def due(self):
"""
Calculate the final amount to be paid after applying the discount.
:return: float, final amount to be paid
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> ds.due()
312.55
"""
@staticmethod
def FidelityPromo(order):
"""
Calculate the discount based on the fidelity points of the customer.Customers with over 1000 points can enjoy a 5% discount on the entire order.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> DiscountStrategy.FidelityPromo(order)
16.45
"""
@staticmethod
def BulkItemPromo(order):
"""
Calculate the discount based on bulk item quantity in the order.In the same order, if the quantity of a single item reaches 20 or more, each item will enjoy a 10% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 20, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
>>> DiscountStrategy.BulkItemPromo(order)
47.0
"""
@staticmethod
def LargeOrderPromo(order):
"""
Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
>>> DiscountStrategy.LargeOrderPromo(order)
0.0
""" | import unittest
class DiscountStrategyTestTotal(unittest.TestCase):
def test_total_1(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart)
expected_total = 250.0
actual_total = order.total()
self.assertEqual(actual_total, expected_total)
def test_total_2(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 10, 'price': 10.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart)
expected_total = 150.0
actual_total = order.total()
self.assertEqual(actual_total, expected_total)
def test_total_3(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 10, 'price': 200.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart)
expected_total = 2050.0
actual_total = order.total()
self.assertEqual(actual_total, expected_total)
def test_total_4(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 1, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart)
expected_total = 70.0
actual_total = order.total()
self.assertEqual(actual_total, expected_total)
def test_total_5(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = []
order = DiscountStrategy(customer, cart)
expected_total = 0
actual_total = order.total()
self.assertEqual(actual_total, expected_total)
class DiscountStrategyTestDue(unittest.TestCase):
def test_due_1(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart)
expected_due = 250.0
actual_due = order.due()
self.assertEqual(actual_due, expected_due)
def test_due_2(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
expected_due = 237.5
actual_due = order.due()
self.assertEqual(actual_due, expected_due)
def test_due_3(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 20, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
expected_due = 410.0
actual_due = order.due()
self.assertEqual(actual_due, expected_due)
def test_due_4(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(15)]
order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
expected_due = 139.5
actual_due = order.due()
self.assertEqual(actual_due, expected_due)
def test_due_5(self):
customer = {'name': 'John Doe', 'fidelity': 900}
cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
expected_due = 250.0
actual_due = order.due()
self.assertEqual(actual_due, expected_due)
class DiscountStrategyTestFidelityPromo(unittest.TestCase):
def test_fidelity_promo_1(self):
customer = {'name': 'John Doe', 'fidelity': 1000}
cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
expected_discount = 12.5
actual_discount = order.promotion(order)
self.assertEqual(actual_discount, expected_discount)
def test_fidelity_promo_2(self):
customer = {'name': 'John Doe', 'fidelity': 800}
cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
expected_discount = 0
actual_discount = order.promotion(order)
self.assertEqual(actual_discount, expected_discount)
def test_fidelity_promo_3(self):
customer = {'name': 'John Doe', 'fidelity': 0}
cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
expected_discount = 0
actual_discount = order.promotion(order)
self.assertEqual(actual_discount, expected_discount)
def test_fidelity_promo_4(self):
customer = {'name': 'John Doe', 'fidelity': 10000}
cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
expected_discount = 12.5
actual_discount = order.promotion(order)
self.assertEqual(actual_discount, expected_discount)
def test_fidelity_promo_5(self):
customer = {'name': 'John Doe', 'fidelity': 1800}
cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
expected_discount = 12.5
actual_discount = order.promotion(order)
self.assertEqual(actual_discount, expected_discount)
class DiscountStrategyTestBulkItemPromo(unittest.TestCase):
def test_bulk_item_promo_1(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 20, 'price': 10.0},
{'product': 'product2', 'quantity': 5, 'price': 5.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
expected_discount = 20.0
actual_discount = order.promotion(order)
self.assertEqual(actual_discount, expected_discount)
def test_bulk_item_promo_2(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 10, 'price': 10.0},
{'product': 'product2', 'quantity': 5, 'price': 5.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
expected_discount = 0
actual_discount = order.promotion(order)
self.assertEqual(actual_discount, expected_discount)
def test_bulk_item_promo_3(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 100, 'price': 10.0},
{'product': 'product2', 'quantity': 5, 'price': 5.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
expected_discount = 100.0
actual_discount = order.promotion(order)
self.assertEqual(actual_discount, expected_discount)
def test_bulk_item_promo_4(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 1, 'price': 10.0},
{'product': 'product2', 'quantity': 5, 'price': 5.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
expected_discount = 0.0
actual_discount = order.promotion(order)
self.assertEqual(actual_discount, expected_discount)
def test_bulk_item_promo_5(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 30, 'price': 10.0},
{'product': 'product2', 'quantity': 5, 'price': 5.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
expected_discount = 30.0
actual_discount = order.promotion(order)
self.assertEqual(actual_discount, expected_discount)
class DiscountStrategyTestLargeOrderPromo(unittest.TestCase):
def test_large_order_promo_1(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(10)]
order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
expected_discount = 7.0
actual_discount = order.promotion(order)
self.assertAlmostEqual(actual_discount, expected_discount)
def test_large_order_promo_2(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(5)]
order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
expected_discount = 0
actual_discount = order.promotion(order)
self.assertEqual(actual_discount, expected_discount)
def test_large_order_promo_3(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(100)]
order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
expected_discount = 70.0
actual_discount = order.promotion(order)
self.assertAlmostEqual(actual_discount, expected_discount)
def test_large_order_promo_4(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(1000)]
order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
expected_discount = 700.0
actual_discount = order.promotion(order)
self.assertAlmostEqual(actual_discount, expected_discount)
def test_large_order_promo_5(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(1)]
order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
expected_discount = 0.0
actual_discount = order.promotion(order)
self.assertAlmostEqual(actual_discount, expected_discount)
class DiscountStrategyTest(unittest.TestCase):
def test_DiscountStrategy(self):
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart)
expected_total = 250.0
actual_total = order.total()
self.assertEqual(actual_total, expected_total)
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart)
expected_due = 250.0
actual_due = order.due()
self.assertEqual(actual_due, expected_due)
customer = {'name': 'John Doe', 'fidelity': 1000}
cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},
{'product': 'product2', 'quantity': 5, 'price': 10.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
expected_discount = 12.5
actual_discount = order.promotion(order)
self.assertEqual(actual_discount, expected_discount)
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': 'product1', 'quantity': 20, 'price': 10.0},
{'product': 'product2', 'quantity': 5, 'price': 5.0}]
order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
expected_discount = 20.0
actual_discount = order.promotion(order)
self.assertEqual(actual_discount, expected_discount)
customer = {'name': 'John Doe', 'fidelity': 1200}
cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(10)]
order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
expected_discount = 7.0
actual_discount = order.promotion(order)
self.assertAlmostEqual(actual_discount, expected_discount) | class DiscountStrategy:
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = cart
self.promotion = promotion
self.__total = self.total()
def total(self):
self.__total = sum(item['quantity'] * item['price'] for item in self.cart)
return self.__total
def due(self):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.__total - discount
@staticmethod
def FidelityPromo(order):
return order.total() * 0.05 if order.customer['fidelity'] >= 1000 else 0
@staticmethod
def BulkItemPromo(order):
discount = 0
for item in order.cart:
if item['quantity'] >= 20:
discount += item['quantity'] * item['price'] * 0.1
return discount
@staticmethod
def LargeOrderPromo(order):
return order.total() * 0.07 if len({item['product'] for item in order.cart}) >= 10 else 0 | [] | """
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
| [
{
"method_name": "total",
"method_description": "def total(self):\n \"\"\"\n Calculate the total cost of items in the cart.\n :return: float, total cost of items\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> ds = DiscountStrategy(customer, cart)\n >>> ds.total()\n 329.0\n\n \"\"\"",
"test_class": "DiscountStrategyTestTotal",
"test_code": "class DiscountStrategyTestTotal(unittest.TestCase):\n def test_total_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_total = 250.0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n def test_total_2(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_total = 150.0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n def test_total_3(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 200.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_total = 2050.0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n def test_total_4(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 1, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_total = 70.0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n def test_total_5(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = []\n order = DiscountStrategy(customer, cart)\n expected_total = 0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)",
"solution_code": "def total(self):\n self.__total = sum(item['quantity'] * item['price'] for item in self.cart)\n return self.__total",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.cart"
],
"method_dependencies": []
}
},
{
"method_name": "due",
"method_description": "def due(self):\n \"\"\"\n Calculate the final amount to be paid after applying the discount.\n :return: float, final amount to be paid\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> ds = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n >>> ds.due()\n 312.55\n\n \"\"\"",
"test_class": "DiscountStrategyTestDue",
"test_code": "class DiscountStrategyTestDue(unittest.TestCase):\n def test_due_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_due = 250.0\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n def test_due_2(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_due = 237.5\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n def test_due_3(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 20, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_due = 410.0\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n def test_due_4(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(15)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_due = 139.5\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n def test_due_5(self):\n customer = {'name': 'John Doe', 'fidelity': 900}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_due = 250.0\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)",
"solution_code": "def due(self):\n if self.promotion is None:\n discount = 0\n else:\n discount = self.promotion(self)\n return self.__total - discount",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.promotion"
],
"method_dependencies": [
"total"
]
}
},
{
"method_name": "FidelityPromo",
"method_description": "@staticmethod\n def FidelityPromo(order):\n \"\"\"\n Calculate the discount based on the fidelity points of the customer.Customers with over 1000 points can enjoy a 5% discount on the entire order.\n :param order: object, the order to apply the discount to\n :return: float, discount amount\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n >>> DiscountStrategy.FidelityPromo(order)\n 16.45\n\n \"\"\"",
"test_class": "DiscountStrategyTestFidelityPromo",
"test_code": "class DiscountStrategyTestFidelityPromo(unittest.TestCase):\n def test_fidelity_promo_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1000}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 12.5\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_fidelity_promo_2(self):\n customer = {'name': 'John Doe', 'fidelity': 800}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_fidelity_promo_3(self):\n customer = {'name': 'John Doe', 'fidelity': 0}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_fidelity_promo_4(self):\n customer = {'name': 'John Doe', 'fidelity': 10000}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 12.5\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_fidelity_promo_5(self):\n customer = {'name': 'John Doe', 'fidelity': 1800}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 12.5\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)",
"solution_code": "@staticmethod\n def FidelityPromo(order):\n return order.total() * 0.05 if order.customer['fidelity'] >= 1000 else 0",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"total"
]
}
},
{
"method_name": "BulkItemPromo",
"method_description": "@staticmethod\n def BulkItemPromo(order):\n \"\"\"\n Calculate the discount based on bulk item quantity in the order.In the same order, if the quantity of a single item reaches 20 or more, each item will enjoy a 10% discount.\n :param order: object, the order to apply the discount to\n :return: float, discount amount\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 20, 'price': 23.5}]\n >>> order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n >>> DiscountStrategy.BulkItemPromo(order)\n 47.0\n\n \"\"\"",
"test_class": "DiscountStrategyTestBulkItemPromo",
"test_code": "class DiscountStrategyTestBulkItemPromo(unittest.TestCase):\n def test_bulk_item_promo_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 20, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 20.0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_bulk_item_promo_2(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_bulk_item_promo_3(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 100, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 100.0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_bulk_item_promo_4(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 1, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 0.0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_bulk_item_promo_5(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 30, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 30.0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)",
"solution_code": "@staticmethod\n def BulkItemPromo(order):\n discount = 0\n for item in order.cart:\n if item['quantity'] >= 20:\n discount += item['quantity'] * item['price'] * 0.1\n return discount",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "LargeOrderPromo",
"method_description": "@staticmethod\n def LargeOrderPromo(order):\n \"\"\"\n Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount.\n :param order: object, the order to apply the discount to\n :return: float, discount amount\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n >>> DiscountStrategy.LargeOrderPromo(order)\n 0.0\n\n \"\"\"",
"test_class": "DiscountStrategyTestLargeOrderPromo",
"test_code": "class DiscountStrategyTestLargeOrderPromo(unittest.TestCase):\n def test_large_order_promo_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(10)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 7.0\n actual_discount = order.promotion(order)\n self.assertAlmostEqual(actual_discount, expected_discount)\n\n def test_large_order_promo_2(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(5)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_large_order_promo_3(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(100)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 70.0\n actual_discount = order.promotion(order)\n self.assertAlmostEqual(actual_discount, expected_discount)\n\n def test_large_order_promo_4(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(1000)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 700.0\n actual_discount = order.promotion(order)\n self.assertAlmostEqual(actual_discount, expected_discount)\n\n def test_large_order_promo_5(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(1)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 0.0\n actual_discount = order.promotion(order)\n self.assertAlmostEqual(actual_discount, expected_discount)",
"solution_code": "@staticmethod\n def LargeOrderPromo(order):\n return order.total() * 0.07 if len({item['product'] for item in order.cart}) >= 10 else 0",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"total"
]
}
}
] | DiscountStrategy | [
"DiscountStrategyTestTotal",
"DiscountStrategyTestDue",
"DiscountStrategyTestFidelityPromo",
"DiscountStrategyTestBulkItemPromo",
"DiscountStrategyTestLargeOrderPromo",
"DiscountStrategyTest"
] | class DiscountStrategy:
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, and an optional promotion.
:param customer: dict, customer information
:param cart: list of dicts, a cart of items with details
:param promotion: function, optional promotion applied to the order
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
"""
self.customer = customer
self.cart = cart
self.promotion = promotion
self.total()
| [
"self.cart",
"self.customer",
"self.promotion"
] |
ClassEval_34 | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path):
"""
Initializes the DocFileHandler object with the specified file path.
:param file_path: str, the path to the Word document file.
"""
self.file_path = file_path
def read_text(self):
"""
Reads the content of a Word document and returns it as a string.
:return: str, the content of the Word document.
"""
def write_text(self, content, font_size=12, alignment='left'):
"""
Writes the specified content to a Word document.
:param content: str, the text content to write.
:param font_size: int, optional, the font size of the text (default is 12).
:param alignment: str, optional, the alignment of the text ('left', 'center', or 'right'; default is 'left').
:return: bool, True if the write operation is successful, False otherwise.
"""
def add_heading(self, heading, level=1):
"""
Adds a heading to the Word document.
:param heading: str, the text of the heading.
:param level: int, optional, the level of the heading (1, 2, 3, etc.; default is 1).
:return: bool, True if the heading is successfully added, False otherwise.
"""
def add_table(self, data):
"""
Adds a table to the Word document with the specified data.
:param data: list of lists, the data to populate the table.
:return: bool, True if the table is successfully added, False otherwise.
"""
def _get_alignment_value(self, alignment):
"""
Returns the alignment value corresponding to the given alignment string.
:param alignment: str, the alignment string ('left', 'center', or 'right').
:return: int, the alignment value.
""" | import unittest
import os
class DocFileHandlerTestReadText(unittest.TestCase):
def test_read_text_1(self):
self.file_path = "test_example.docx"
self.handler = DocFileHandler(self.file_path)
doc = Document()
doc.add_paragraph("Initial content")
doc.save(self.file_path)
text_content = self.handler.read_text()
expected_content = "Initial content"
self.assertEqual(text_content, expected_content)
if os.path.exists(self.file_path):
os.remove(self.file_path)
def test_read_text_2(self):
self.file_path = "test_example.docx"
self.handler = DocFileHandler(self.file_path)
doc = Document()
doc.add_paragraph("111")
doc.save(self.file_path)
text_content = self.handler.read_text()
expected_content = "111"
self.assertEqual(text_content, expected_content)
if os.path.exists(self.file_path):
os.remove(self.file_path)
def test_read_text_3(self):
self.file_path = "test_example.docx"
self.handler = DocFileHandler(self.file_path)
doc = Document()
doc.add_paragraph("aaa")
doc.save(self.file_path)
text_content = self.handler.read_text()
expected_content = "aaa"
self.assertEqual(text_content, expected_content)
if os.path.exists(self.file_path):
os.remove(self.file_path)
def test_read_text_4(self):
self.file_path = "test_example.docx"
self.handler = DocFileHandler(self.file_path)
doc = Document()
doc.add_paragraph("aaa\nbbb")
doc.save(self.file_path)
text_content = self.handler.read_text()
expected_content = "aaa\nbbb"
self.assertEqual(text_content, expected_content)
if os.path.exists(self.file_path):
os.remove(self.file_path)
def test_read_text_5(self):
self.file_path = "test_example.docx"
self.handler = DocFileHandler(self.file_path)
doc = Document()
doc.add_paragraph("")
doc.save(self.file_path)
text_content = self.handler.read_text()
expected_content = ""
self.assertEqual(text_content, expected_content)
if os.path.exists(self.file_path):
os.remove(self.file_path)
class DocFileHandlerTestWriteText(unittest.TestCase):
def setUp(self):
self.file_path = "test_example.docx"
self.handler = DocFileHandler(self.file_path)
doc = Document()
doc.add_paragraph("Initial content")
doc.save(self.file_path)
def tearDown(self):
if os.path.exists(self.file_path):
os.remove(self.file_path)
def test_write_text_1(self):
new_content = "New content 1"
self.handler.write_text(new_content)
text_content = self.handler.read_text()
self.assertEqual(text_content, new_content)
def test_write_text_2(self):
new_content = "New content 2"
self.handler.write_text(new_content)
text_content = self.handler.read_text()
self.assertEqual(text_content, new_content)
def test_write_text_3(self):
new_content = "New content 3"
self.handler.write_text(new_content)
text_content = self.handler.read_text()
self.assertEqual(text_content, new_content)
def test_write_text_4(self):
new_content = "New content 4"
self.handler.write_text(new_content)
text_content = self.handler.read_text()
self.assertEqual(text_content, new_content)
def test_write_text_5(self):
new_content = ""
self.handler.write_text(new_content)
text_content = self.handler.read_text()
self.assertEqual(text_content, new_content)
class DocFileHandlerTestAddHeading(unittest.TestCase):
def setUp(self):
self.file_path = "test_example.docx"
self.handler = DocFileHandler(self.file_path)
doc = Document()
doc.add_paragraph("Initial content")
doc.save(self.file_path)
def tearDown(self):
if os.path.exists(self.file_path):
os.remove(self.file_path)
def test_add_heading_1(self):
heading = "Test Heading 1"
self.handler.add_heading(heading)
doc = Document(self.file_path)
headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]
self.assertIn(heading, headings)
def test_add_heading_2(self):
heading = "Test Heading 2"
self.handler.add_heading(heading)
doc = Document(self.file_path)
headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]
self.assertIn(heading, headings)
def test_add_heading_3(self):
heading = "Test Heading 3"
self.handler.add_heading(heading)
doc = Document(self.file_path)
headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]
self.assertIn(heading, headings)
def test_add_heading_4(self):
heading = "Test Heading 4"
self.handler.add_heading(heading)
doc = Document(self.file_path)
headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]
self.assertIn(heading, headings)
def test_add_heading_5(self):
heading = "Test Heading 5"
self.handler.add_heading(heading)
doc = Document(self.file_path)
headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]
self.assertIn(heading, headings)
class DocFileHandlerTestAddTable(unittest.TestCase):
def setUp(self):
self.file_path = "test_example.docx"
self.handler = DocFileHandler(self.file_path)
doc = Document()
doc.add_paragraph("Initial content")
doc.save(self.file_path)
def tearDown(self):
if os.path.exists(self.file_path):
os.remove(self.file_path)
def test_add_table_1(self):
data = [['Name', 'Age']]
self.handler.add_table(data)
doc = Document(self.file_path)
table = doc.tables[0]
self.assertEqual(len(table.rows), 1)
self.assertEqual(len(table.columns), 2)
def test_add_table_2(self):
data = [['Name', 'Age'], ['John', '25']]
self.handler.add_table(data)
doc = Document(self.file_path)
table = doc.tables[0]
self.assertEqual(len(table.rows), 2)
self.assertEqual(len(table.columns), 2)
self.assertEqual(table.cell(1, 0).text, 'John')
def test_add_table_3(self):
data = [['Name', 'Age'], ['John', '25'], ['Emma', '30']]
self.handler.add_table(data)
doc = Document(self.file_path)
table = doc.tables[0]
self.assertEqual(len(table.rows), 3)
self.assertEqual(len(table.columns), 2)
self.assertEqual(table.cell(1, 0).text, 'John')
self.assertEqual(table.cell(2, 1).text, '30')
def test_add_table_4(self):
data = [['Name', 'Age'], ['aaa', '25'], ['Emma', '30']]
self.handler.add_table(data)
doc = Document(self.file_path)
table = doc.tables[0]
self.assertEqual(len(table.rows), 3)
self.assertEqual(len(table.columns), 2)
self.assertEqual(table.cell(1, 0).text, 'aaa')
self.assertEqual(table.cell(2, 1).text, '30')
def test_add_table_5(self):
data = [['Name', 'Age'], ['John', '25'], ['Emma', '90']]
self.handler.add_table(data)
doc = Document(self.file_path)
table = doc.tables[0]
self.assertEqual(len(table.rows), 3)
self.assertEqual(len(table.columns), 2)
self.assertEqual(table.cell(1, 0).text, 'John')
self.assertEqual(table.cell(2, 1).text, '90')
class DocFileHandlerTest(unittest.TestCase):
def test_DocFileHandler(self):
self.file_path = "test_example.docx"
self.handler = DocFileHandler(self.file_path)
doc = Document()
doc.add_paragraph("Initial content")
doc.save(self.file_path)
text_content = self.handler.read_text()
expected_content = "Initial content"
self.assertEqual(text_content, expected_content)
new_content = "New content 1"
self.handler.write_text(new_content)
text_content = self.handler.read_text()
self.assertEqual(text_content, new_content)
heading = "Test Heading 1"
self.handler.add_heading(heading)
doc = Document(self.file_path)
headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]
self.assertIn(heading, headings)
data = [['Name', 'Age']]
self.handler.add_table(data)
doc = Document(self.file_path)
table = doc.tables[0]
self.assertEqual(len(table.rows), 1)
self.assertEqual(len(table.columns), 2)
if os.path.exists(self.file_path):
os.remove(self.file_path) | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
def __init__(self, file_path):
self.file_path = file_path
def read_text(self):
doc = Document(self.file_path)
text = []
for paragraph in doc.paragraphs:
text.append(paragraph.text)
return "\n".join(text)
def write_text(self, content, font_size=12, alignment='left'):
try:
doc = Document()
paragraph = doc.add_paragraph()
run = paragraph.add_run(content)
font = run.font
font.size = Pt(font_size)
alignment_value = self._get_alignment_value(alignment)
paragraph.alignment = alignment_value
doc.save(self.file_path)
return True
except:
return False
def add_heading(self, heading, level=1):
try:
doc = Document(self.file_path)
doc.add_heading(heading, level)
doc.save(self.file_path)
return True
except:
return False
def add_table(self, data):
try:
doc = Document(self.file_path)
table = doc.add_table(rows=len(data), cols=len(data[0]))
for i, row in enumerate(data):
for j, cell_value in enumerate(row):
table.cell(i, j).text = str(cell_value)
doc.save(self.file_path)
return True
except:
return False
def _get_alignment_value(self, alignment):
alignment_options = {
'left': WD_PARAGRAPH_ALIGNMENT.LEFT,
'center': WD_PARAGRAPH_ALIGNMENT.CENTER,
'right': WD_PARAGRAPH_ALIGNMENT.RIGHT
}
return alignment_options.get(alignment.lower(), WD_PARAGRAPH_ALIGNMENT.LEFT) | [
"from docx import Document",
"from docx.shared import Pt",
"from docx.enum.text import WD_PARAGRAPH_ALIGNMENT"
] | """
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
| [
{
"method_name": "read_text",
"method_description": "def read_text(self):\n \"\"\"\n Reads the content of a Word document and returns it as a string.\n :return: str, the content of the Word document.\n \"\"\"",
"test_class": "DocFileHandlerTestReadText",
"test_code": "class DocFileHandlerTestReadText(unittest.TestCase):\n def test_read_text_1(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"Initial content\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_read_text_2(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"111\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"111\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_read_text_3(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"aaa\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"aaa\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_read_text_4(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"aaa\\nbbb\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"aaa\\nbbb\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_read_text_5(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)",
"solution_code": "def read_text(self):\n doc = Document(self.file_path)\n text = []\n for paragraph in doc.paragraphs:\n text.append(paragraph.text)\n return \"\\n\".join(text)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"Document"
],
"field_dependencies": [
"self.file_path"
],
"method_dependencies": []
}
},
{
"method_name": "write_text",
"method_description": "def write_text(self, content, font_size=12, alignment='left'):\n \"\"\"\n Writes the specified content to a Word document.\n :param content: str, the text content to write.\n :param font_size: int, optional, the font size of the text (default is 12).\n :param alignment: str, optional, the alignment of the text ('left', 'center', or 'right'; default is 'left').\n :return: bool, True if the write operation is successful, False otherwise.\n \"\"\"",
"test_class": "DocFileHandlerTestWriteText",
"test_code": "class DocFileHandlerTestWriteText(unittest.TestCase):\n def setUp(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_write_text_1(self):\n new_content = \"New content 1\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n def test_write_text_2(self):\n new_content = \"New content 2\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n def test_write_text_3(self):\n new_content = \"New content 3\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n def test_write_text_4(self):\n new_content = \"New content 4\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n def test_write_text_5(self):\n new_content = \"\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)",
"solution_code": "def write_text(self, content, font_size=12, alignment='left'):\n try:\n doc = Document()\n paragraph = doc.add_paragraph()\n run = paragraph.add_run(content)\n font = run.font\n font.size = Pt(font_size)\n alignment_value = self._get_alignment_value(alignment)\n paragraph.alignment = alignment_value\n doc.save(self.file_path)\n return True\n except:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"Document",
"Pt"
],
"field_dependencies": [
"self.file_path"
],
"method_dependencies": [
"_get_alignment_value"
]
}
},
{
"method_name": "add_heading",
"method_description": "def add_heading(self, heading, level=1):\n \"\"\"\n Adds a heading to the Word document.\n :param heading: str, the text of the heading.\n :param level: int, optional, the level of the heading (1, 2, 3, etc.; default is 1).\n :return: bool, True if the heading is successfully added, False otherwise.\n \"\"\"",
"test_class": "DocFileHandlerTestAddHeading",
"test_code": "class DocFileHandlerTestAddHeading(unittest.TestCase):\n def setUp(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_add_heading_1(self):\n heading = \"Test Heading 1\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n def test_add_heading_2(self):\n heading = \"Test Heading 2\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n def test_add_heading_3(self):\n heading = \"Test Heading 3\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n def test_add_heading_4(self):\n heading = \"Test Heading 4\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n def test_add_heading_5(self):\n heading = \"Test Heading 5\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)",
"solution_code": "def add_heading(self, heading, level=1):\n try:\n doc = Document(self.file_path)\n doc.add_heading(heading, level)\n doc.save(self.file_path)\n return True\n except:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"Document"
],
"field_dependencies": [
"self.file_path"
],
"method_dependencies": []
}
},
{
"method_name": "add_table",
"method_description": "def add_table(self, data):\n \"\"\"\n Adds a table to the Word document with the specified data.\n :param data: list of lists, the data to populate the table.\n :return: bool, True if the table is successfully added, False otherwise.\n \"\"\"",
"test_class": "DocFileHandlerTestAddTable",
"test_code": "class DocFileHandlerTestAddTable(unittest.TestCase):\n def setUp(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_add_table_1(self):\n data = [['Name', 'Age']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 1)\n self.assertEqual(len(table.columns), 2)\n\n def test_add_table_2(self):\n data = [['Name', 'Age'], ['John', '25']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 2)\n self.assertEqual(len(table.columns), 2)\n self.assertEqual(table.cell(1, 0).text, 'John')\n\n def test_add_table_3(self):\n data = [['Name', 'Age'], ['John', '25'], ['Emma', '30']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 3)\n self.assertEqual(len(table.columns), 2)\n self.assertEqual(table.cell(1, 0).text, 'John')\n self.assertEqual(table.cell(2, 1).text, '30')\n\n def test_add_table_4(self):\n data = [['Name', 'Age'], ['aaa', '25'], ['Emma', '30']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 3)\n self.assertEqual(len(table.columns), 2)\n self.assertEqual(table.cell(1, 0).text, 'aaa')\n self.assertEqual(table.cell(2, 1).text, '30')\n\n def test_add_table_5(self):\n data = [['Name', 'Age'], ['John', '25'], ['Emma', '90']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 3)\n self.assertEqual(len(table.columns), 2)\n self.assertEqual(table.cell(1, 0).text, 'John')\n self.assertEqual(table.cell(2, 1).text, '90')",
"solution_code": "def add_table(self, data):\n try:\n doc = Document(self.file_path)\n table = doc.add_table(rows=len(data), cols=len(data[0]))\n for i, row in enumerate(data):\n for j, cell_value in enumerate(row):\n table.cell(i, j).text = str(cell_value)\n doc.save(self.file_path)\n return True\n except:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"Document"
],
"field_dependencies": [
"self.file_path"
],
"method_dependencies": []
}
},
{
"method_name": "_get_alignment_value",
"method_description": "def _get_alignment_value(self, alignment):\n \"\"\"\n Returns the alignment value corresponding to the given alignment string.\n :param alignment: str, the alignment string ('left', 'center', or 'right').\n :return: int, the alignment value.\n \"\"\"",
"test_class": "DocFileHandlerTest",
"test_code": "class DocFileHandlerTest(unittest.TestCase):\n def test_DocFileHandler(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"Initial content\"\n self.assertEqual(text_content, expected_content)\n\n new_content = \"New content 1\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n heading = \"Test Heading 1\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n data = [['Name', 'Age']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 1)\n self.assertEqual(len(table.columns), 2)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)",
"solution_code": "def _get_alignment_value(self, alignment):\n alignment_options = {\n 'left': WD_PARAGRAPH_ALIGNMENT.LEFT,\n 'center': WD_PARAGRAPH_ALIGNMENT.CENTER,\n 'right': WD_PARAGRAPH_ALIGNMENT.RIGHT\n }\n return alignment_options.get(alignment.lower(), WD_PARAGRAPH_ALIGNMENT.LEFT)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"WD_PARAGRAPH_ALIGNMENT"
],
"field_dependencies": [],
"method_dependencies": []
}
}
] | DocFileHandler | [
"DocFileHandlerTestReadText",
"DocFileHandlerTestWriteText",
"DocFileHandlerTestAddHeading",
"DocFileHandlerTestAddTable",
"DocFileHandlerTest"
] | class DocFileHandler:
def __init__(self, file_path):
"""
Initializes the DocFileHandler object with the specified file path.
:param file_path: str, the path to the Word document file.
"""
self.file_path = file_path
| [
"self.file_path"
] |
ClassEval_35 | class EightPuzzle:
"""
This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.
"""
def __init__(self, initial_state):
"""
Initializing the initial state of Eight Puzzle Game, stores in attribute self.initial_state.
And set the goal state of this game, stores in self.goal_state. In this case, set the size as 3*3
:param initial_state: a 3*3 size list of Integer, stores the initial state
"""
self.initial_state = initial_state
self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
def find_blank(self, state):
"""
Find the blank position of current state, which is the 0 element.
:param state: a 3*3 size list of Integer, stores the current state.
:return i, j: two Integers, represent the coordinate of the blank block.
>>> eightPuzzle = EightPuzzle([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
>>> eightPuzzle.find_blank([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
(2, 1)
"""
def move(self, state, direction):
"""
Find the blank block, then makes the board moves forward the given direction.
:param state: a 3*3 size list of Integer, stores the state before moving.
:param direction: str, only has 4 direction 'up', 'down', 'left', 'right'
:return new_state: a 3*3 size list of Integer, stores the state after moving.
>>> eightPuzzle.move([[2, 3, 4], [5, 8, 1], [6, 0, 7]], 'left')
[[2, 3, 4], [5, 8, 1], [0, 6, 7]]
"""
def get_possible_moves(self, state):
"""
According the current state, find all the possible moving directions. Only has 4 direction 'up', 'down', 'left', 'right'.
:param state: a 3*3 size list of Integer, stores the current state.
:return moves: a list of str, store all the possible moving directions according to the current state.
>>> eightPuzzle.get_possible_moves([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
['up', 'left', 'right']
"""
def solve(self):
"""
Use BFS algorithm to find the path solution which makes the initial state to the goal method.
Maintain a list as a queue, named as open_list, append the initial state.
Always visit and pop the 0 index element, invoke get_possible_moves method find all the possible directions.
Traversal the possible_moves list and invoke move method to get several new states.Then append them.
redo the above steps until the open_list is empty or the state has changed to the goal state.
:return path: list of str, the solution to the goal state.
>>> eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])
>>> eightPuzzle.solve()
['right']
""" | import unittest
class EightPuzzleTestFindBlank(unittest.TestCase):
def test_find_blank_1(self):
state = [[2, 3, 4], [5, 8, 1], [6, 0, 7]]
eightPuzzle = EightPuzzle(state)
self.assertEqual(eightPuzzle.find_blank(state), (2, 1))
def test_find_blank_2(self):
state = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]
eightPuzzle = EightPuzzle(state)
self.assertEqual(eightPuzzle.find_blank(state), (1, 1))
def test_find_blank_3(self):
state = [[2, 3, 4], [5, 8, 1], [6, 8, 7]]
eightPuzzle = EightPuzzle(state)
self.assertEqual(eightPuzzle.find_blank(state), None)
def test_find_blank_4(self):
state = [[2, 3, 4], [5, 8, 1], [6, 8, 7]]
eightPuzzle = EightPuzzle(state)
self.assertEqual(eightPuzzle.find_blank(state), None)
def test_find_blank_5(self):
state = [[2, 3, 4], [5, 8, 1], [6, 8, 7]]
eightPuzzle = EightPuzzle(state)
self.assertEqual(eightPuzzle.find_blank(state), None)
class EightPuzzleTestMove(unittest.TestCase):
def setUp(self):
self.initial_state = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]
self.eightPuzzle = EightPuzzle(self.initial_state)
def test_move_1(self):
result = self.eightPuzzle.move(self.initial_state, 'up')
expected = [[2, 0, 4], [5, 3, 1], [6, 8, 7]]
self.assertEqual(result, expected)
def test_move_2(self):
result = self.eightPuzzle.move(self.initial_state, 'down')
expected = [[2, 3, 4], [5, 8, 1], [6, 0, 7]]
self.assertEqual(result, expected)
def test_move_3(self):
result = self.eightPuzzle.move(self.initial_state, 'left')
expected = [[2, 3, 4], [0, 5, 1], [6, 8, 7]]
self.assertEqual(result, expected)
def test_move_4(self):
result = self.eightPuzzle.move(self.initial_state, 'right')
expected = [[2, 3, 4], [5, 1, 0], [6, 8, 7]]
self.assertEqual(result, expected)
def test_move_5(self):
result = self.eightPuzzle.move(self.initial_state, '???')
expected = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]
self.assertEqual(result, expected)
class EightPuzzleTestGetPossibleMoves(unittest.TestCase):
def test_get_possible_moves_1(self):
eightPuzzle = EightPuzzle(None)
state = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]
result = eightPuzzle.get_possible_moves(state)
expected = ['up', 'down', 'left', 'right']
for direction in result:
self.assertIn(direction, expected)
def test_get_possible_moves_2(self):
eightPuzzle = EightPuzzle(None)
state = [[2, 3, 4], [5, 8, 1], [6, 0, 7]]
result = eightPuzzle.get_possible_moves(state)
expected = ['up', 'left', 'right']
for direction in result:
self.assertIn(direction, expected)
def test_get_possible_moves_3(self):
eightPuzzle = EightPuzzle(None)
state = [[2, 0, 4], [5, 3, 1], [6, 8, 7]]
result = eightPuzzle.get_possible_moves(state)
expected = ['down', 'left', 'right']
for direction in result:
self.assertIn(direction, expected)
def test_get_possible_moves_4(self):
eightPuzzle = EightPuzzle(None)
state = [[2, 3, 4], [5, 1, 0], [6, 8, 7]]
result = eightPuzzle.get_possible_moves(state)
expected = ['up', 'down', 'left']
for direction in result:
self.assertIn(direction, expected)
def test_get_possible_moves_5(self):
eightPuzzle = EightPuzzle(None)
state = [[2, 3, 4], [0, 5, 1], [6, 8, 7]]
result = eightPuzzle.get_possible_moves(state)
expected = ['up', 'down', 'right']
for direction in result:
self.assertIn(direction, expected)
class EightPuzzleTestSolve(unittest.TestCase):
def test_solve_1(self):
eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])
result = eightPuzzle.solve()
expected = ['right']
self.assertEqual(result, expected)
def test_solve_2(self):
eightPuzzle = EightPuzzle([[1, 2, 3], [4, 0, 6], [7, 5, 8]])
result = eightPuzzle.solve()
expected = ['down', 'right']
self.assertEqual(result, expected)
def test_solve_3(self):
eightPuzzle = EightPuzzle([[1, 2, 3], [0, 4, 5], [6, 7, 8]])
result = eightPuzzle.solve()
expected = ['right', 'right', 'down', 'left', 'left', 'up', 'right', 'down', 'right', 'up', 'left', 'left', 'down', 'right', 'right']
self.assertEqual(result, expected)
def test_solve_4(self):
eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 8, 0]])
result = eightPuzzle.solve()
expected = []
self.assertEqual(result, expected)
def test_solve_5(self):
eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [0, 7, 8]])
result = eightPuzzle.solve()
expected = ['right', 'right']
self.assertEqual(result, expected)
def test_solve_6(self):
eightPuzzle = EightPuzzle([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
result = eightPuzzle.solve()
expected = None
self.assertEqual(result, expected) | class EightPuzzle:
def __init__(self, initial_state):
self.initial_state = initial_state
self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
def find_blank(self, state):
for i in range(3):
for j in range(3):
if state[i][j] == 0:
return i, j
def move(self, state, direction):
i, j = self.find_blank(state)
new_state = [row[:] for row in state]
if direction == 'up':
new_state[i][j], new_state[i - 1][j] = new_state[i - 1][j], new_state[i][j]
elif direction == 'down':
new_state[i][j], new_state[i + 1][j] = new_state[i + 1][j], new_state[i][j]
elif direction == 'left':
new_state[i][j], new_state[i][j - 1] = new_state[i][j - 1], new_state[i][j]
elif direction == 'right':
new_state[i][j], new_state[i][j + 1] = new_state[i][j + 1], new_state[i][j]
return new_state
def get_possible_moves(self, state):
moves = []
i, j = self.find_blank(state)
if i > 0:
moves.append('up')
if i < 2:
moves.append('down')
if j > 0:
moves.append('left')
if j < 2:
moves.append('right')
return moves
def solve(self):
open_list = [(self.initial_state, [])]
closed_list = []
while open_list:
current_state, path = open_list.pop(0)
closed_list.append(current_state)
if current_state == self.goal_state:
return path
for move in self.get_possible_moves(current_state):
new_state = self.move(current_state, move)
if new_state not in closed_list:
open_list.append((new_state, path + [move]))
return None | [] | """
This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.
"""
| [
{
"method_name": "find_blank",
"method_description": "def find_blank(self, state):\n \"\"\"\n Find the blank position of current state, which is the 0 element.\n :param state: a 3*3 size list of Integer, stores the current state.\n :return i, j: two Integers, represent the coordinate of the blank block.\n >>> eightPuzzle = EightPuzzle([[2, 3, 4], [5, 8, 1], [6, 0, 7]])\n >>> eightPuzzle.find_blank([[2, 3, 4], [5, 8, 1], [6, 0, 7]])\n (2, 1)\n \"\"\"",
"test_class": "EightPuzzleTestFindBlank",
"test_code": "class EightPuzzleTestFindBlank(unittest.TestCase):\n def test_find_blank_1(self):\n state = [[2, 3, 4], [5, 8, 1], [6, 0, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), (2, 1))\n\n def test_find_blank_2(self):\n state = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), (1, 1))\n\n def test_find_blank_3(self):\n state = [[2, 3, 4], [5, 8, 1], [6, 8, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), None)\n\n def test_find_blank_4(self):\n state = [[2, 3, 4], [5, 8, 1], [6, 8, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), None)\n\n def test_find_blank_5(self):\n state = [[2, 3, 4], [5, 8, 1], [6, 8, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), None)",
"solution_code": "def find_blank(self, state):\n for i in range(3):\n for j in range(3):\n if state[i][j] == 0:\n return i, j",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "move",
"method_description": "def move(self, state, direction):\n \"\"\"\n Find the blank block, then makes the board moves forward the given direction.\n :param state: a 3*3 size list of Integer, stores the state before moving.\n :param direction: str, only has 4 direction 'up', 'down', 'left', 'right'\n :return new_state: a 3*3 size list of Integer, stores the state after moving.\n >>> eightPuzzle.move([[2, 3, 4], [5, 8, 1], [6, 0, 7]], 'left')\n [[2, 3, 4], [5, 8, 1], [0, 6, 7]]\n \"\"\"",
"test_class": "EightPuzzleTestMove",
"test_code": "class EightPuzzleTestMove(unittest.TestCase):\n def setUp(self):\n self.initial_state = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]\n self.eightPuzzle = EightPuzzle(self.initial_state)\n\n def test_move_1(self):\n result = self.eightPuzzle.move(self.initial_state, 'up')\n expected = [[2, 0, 4], [5, 3, 1], [6, 8, 7]]\n self.assertEqual(result, expected)\n\n def test_move_2(self):\n result = self.eightPuzzle.move(self.initial_state, 'down')\n expected = [[2, 3, 4], [5, 8, 1], [6, 0, 7]]\n self.assertEqual(result, expected)\n\n def test_move_3(self):\n result = self.eightPuzzle.move(self.initial_state, 'left')\n expected = [[2, 3, 4], [0, 5, 1], [6, 8, 7]]\n self.assertEqual(result, expected)\n\n def test_move_4(self):\n result = self.eightPuzzle.move(self.initial_state, 'right')\n expected = [[2, 3, 4], [5, 1, 0], [6, 8, 7]]\n self.assertEqual(result, expected)\n\n def test_move_5(self):\n result = self.eightPuzzle.move(self.initial_state, '???')\n expected = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]\n self.assertEqual(result, expected)",
"solution_code": "def move(self, state, direction):\n i, j = self.find_blank(state)\n new_state = [row[:] for row in state]\n\n if direction == 'up':\n new_state[i][j], new_state[i - 1][j] = new_state[i - 1][j], new_state[i][j]\n elif direction == 'down':\n new_state[i][j], new_state[i + 1][j] = new_state[i + 1][j], new_state[i][j]\n elif direction == 'left':\n new_state[i][j], new_state[i][j - 1] = new_state[i][j - 1], new_state[i][j]\n elif direction == 'right':\n new_state[i][j], new_state[i][j + 1] = new_state[i][j + 1], new_state[i][j]\n\n return new_state",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"find_blank"
]
}
},
{
"method_name": "get_possible_moves",
"method_description": "def get_possible_moves(self, state):\n \"\"\"\n According the current state, find all the possible moving directions. Only has 4 direction 'up', 'down', 'left', 'right'.\n :param state: a 3*3 size list of Integer, stores the current state.\n :return moves: a list of str, store all the possible moving directions according to the current state.\n >>> eightPuzzle.get_possible_moves([[2, 3, 4], [5, 8, 1], [6, 0, 7]])\n ['up', 'left', 'right']\n \"\"\"",
"test_class": "EightPuzzleTestGetPossibleMoves",
"test_code": "class EightPuzzleTestGetPossibleMoves(unittest.TestCase):\n def test_get_possible_moves_1(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['up', 'down', 'left', 'right']\n for direction in result:\n self.assertIn(direction, expected)\n\n def test_get_possible_moves_2(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 3, 4], [5, 8, 1], [6, 0, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['up', 'left', 'right']\n for direction in result:\n self.assertIn(direction, expected)\n\n def test_get_possible_moves_3(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 0, 4], [5, 3, 1], [6, 8, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['down', 'left', 'right']\n for direction in result:\n self.assertIn(direction, expected)\n\n def test_get_possible_moves_4(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 3, 4], [5, 1, 0], [6, 8, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['up', 'down', 'left']\n for direction in result:\n self.assertIn(direction, expected)\n\n def test_get_possible_moves_5(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 3, 4], [0, 5, 1], [6, 8, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['up', 'down', 'right']\n for direction in result:\n self.assertIn(direction, expected)",
"solution_code": "def get_possible_moves(self, state):\n moves = []\n i, j = self.find_blank(state)\n\n if i > 0:\n moves.append('up')\n if i < 2:\n moves.append('down')\n if j > 0:\n moves.append('left')\n if j < 2:\n moves.append('right')\n\n return moves",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"find_blank",
"move"
]
}
},
{
"method_name": "solve",
"method_description": "def solve(self):\n \"\"\"\n Use BFS algorithm to find the path solution which makes the initial state to the goal method.\n Maintain a list as a queue, named as open_list, append the initial state.\n Always visit and pop the 0 index element, invoke get_possible_moves method find all the possible directions.\n Traversal the possible_moves list and invoke move method to get several new states.Then append them.\n redo the above steps until the open_list is empty or the state has changed to the goal state.\n :return path: list of str, the solution to the goal state.\n >>> eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])\n >>> eightPuzzle.solve()\n ['right']\n \"\"\"",
"test_class": "EightPuzzleTestSolve",
"test_code": "class EightPuzzleTestSolve(unittest.TestCase):\n def test_solve_1(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])\n result = eightPuzzle.solve()\n expected = ['right']\n self.assertEqual(result, expected)\n\n def test_solve_2(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [4, 0, 6], [7, 5, 8]])\n result = eightPuzzle.solve()\n expected = ['down', 'right']\n self.assertEqual(result, expected)\n\n def test_solve_3(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [0, 4, 5], [6, 7, 8]])\n result = eightPuzzle.solve()\n expected = ['right', 'right', 'down', 'left', 'left', 'up', 'right', 'down', 'right', 'up', 'left', 'left', 'down', 'right', 'right']\n self.assertEqual(result, expected)\n\n def test_solve_4(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 8, 0]])\n result = eightPuzzle.solve()\n expected = []\n self.assertEqual(result, expected)\n\n def test_solve_5(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [0, 7, 8]])\n result = eightPuzzle.solve()\n expected = ['right', 'right']\n self.assertEqual(result, expected)\n\n def test_solve_6(self):\n eightPuzzle = EightPuzzle([[0, 0, 0], [0, 0, 0], [0, 0, 0]])\n result = eightPuzzle.solve()\n expected = None\n self.assertEqual(result, expected)",
"solution_code": "def solve(self):\n open_list = [(self.initial_state, [])]\n closed_list = []\n\n while open_list:\n current_state, path = open_list.pop(0)\n closed_list.append(current_state)\n\n if current_state == self.goal_state:\n return path\n\n for move in self.get_possible_moves(current_state):\n new_state = self.move(current_state, move)\n if new_state not in closed_list:\n open_list.append((new_state, path + [move]))\n\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.goal_state",
"self.initial_state"
],
"method_dependencies": [
"move",
"get_possible_moves"
]
}
}
] | EightPuzzle | [
"EightPuzzleTestFindBlank",
"EightPuzzleTestMove",
"EightPuzzleTestGetPossibleMoves",
"EightPuzzleTestSolve"
] | class EightPuzzle:
def __init__(self, initial_state):
"""
Initializing the initial state of Eight Puzzle Game, stores in attribute self.initial_state.
And set the goal state of this game, stores in self.goal_state. In this case, set the size as 3*3
:param initial_state: a 3*3 size list of Integer, stores the initial state
"""
self.initial_state = initial_state
self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
| [
"self.goal_state",
"self.initial_state"
] |
ClassEval_36 | from datetime import datetime
class EmailClient:
"""
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
def __init__(self, addr, capacity) -> None:
"""
Initializes the EmailClient class with the email address and the capacity of the email box.
:param addr: The email address, str.
:param capacity: The capacity of the email box, float.
"""
self.addr = addr
self.capacity = capacity
self.inbox = []
def send_to(self, recv, content, size):
"""
Sends an email to the given email address.
:param recv: The email address of the receiver, str.
:param content: The content of the email, str.
:param size: The size of the email, float.
:return: True if the email is sent successfully, False if the receiver's email box is full.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.send_to(receiver, 'Hello', 10)
True
>>> receiver.inbox
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}
"""
def fetch(self):
"""
Retrieves the first unread email in the email box and marks it as read.
:return: The first unread email in the email box, dict.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}]
>>> receiver.fetch()
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'read'}
"""
def is_full_with_one_more_email(self, size):
"""
Determines whether the email box is full after adding an email of the given size.
:param size: The size of the email, float.
:return: True if the email box is full, False otherwise.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.is_full_with_one_more_email(10)
False
"""
def get_occupied_size(self):
"""
Gets the total size of the emails in the email box.
:return: The total size of the emails in the email box, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]
>>> sender.get_occupied_size()
10
"""
def clear_inbox(self, size):
"""
Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size.
:param size: The size of the email, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]
>>> receiver.clear_inbox(30)
>>> receiver.inbox
[{'size': 15}]
""" | import unittest
class EmailClientTestSendTo(unittest.TestCase):
def test_send_to(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.assertTrue(sender.send_to(receiver, 'Hello', 10))
self.assertEqual(receiver.inbox[0], {"sender": '[email protected]','receiver': '[email protected]','content': 'Hello','size': 10,'time': timestamp,'state': 'unread'})
def test_send_to_2(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 0)
self.assertFalse(sender.send_to(receiver, 'Hello', 10))
def test_send_to_3(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
receiver.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 50, 'time': '2021-01-01 00:00:00', 'state': 'unread'}]
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.assertFalse(sender.send_to(receiver, 'Hello', 10))
self.assertEqual(receiver.inbox, [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 50, 'time': '2021-01-01 00:00:00', 'state': 'unread'}])
def test_send_to_4(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 30)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.assertTrue(sender.send_to(receiver, 'Hello', 20))
self.assertEqual(receiver.inbox, [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 20, 'time': timestamp, 'state': 'unread'}])
def test_send_to_5(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 30)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.assertTrue(sender.send_to(receiver, 'bye', 20))
self.assertEqual(receiver.inbox, [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'bye', 'size': 20, 'time': timestamp, 'state': 'unread'}])
class EmailClientTestFetch(unittest.TestCase):
def test_fetch(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
receiver.inbox = [
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,
'time': timestamp, 'state': 'unread'}]
self.assertEqual(receiver.fetch(), {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time':timestamp, 'state': 'read'})
def test_fetch_2(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.assertEqual(receiver.fetch(),None)
def test_fetch_3(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
receiver.inbox = [
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,
'time': timestamp, 'state': 'read'}]
self.assertEqual(receiver.fetch(), None)
def test_fetch_4(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
receiver.inbox = [
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,
'time': '2021-01-01 00:00:00', 'state': 'unread'},
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,
'time': timestamp, 'state': 'unread'}]
self.assertEqual(receiver.fetch(), {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,
'time': '2021-01-01 00:00:00', 'state': 'read'})
def test_fetch_5(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
receiver.inbox = [
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,
'time': '2021-01-01 00:00:00', 'state': 'read'},
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,
'time': timestamp, 'state': 'unread'}]
self.assertEqual(receiver.fetch(), {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,
'time': timestamp, 'state': 'read'})
class EmailClientTestIsFullWithOneMoreEmail(unittest.TestCase):
def test_is_full_with_one_more_email(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
self.assertFalse(receiver.is_full_with_one_more_email(10))
def test_is_full_with_one_more_email_2(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 0)
self.assertTrue(receiver.is_full_with_one_more_email(10))
def test_is_full_with_one_more_email_3(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 10)
self.assertFalse(receiver.is_full_with_one_more_email(10))
def test_is_full_with_one_more_email_4(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 10)
self.assertTrue(receiver.is_full_with_one_more_email(20))
def test_is_full_with_one_more_email_5(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 20)
self.assertFalse(receiver.is_full_with_one_more_email(20))
class EmailClientTestGetOccupiedSize(unittest.TestCase):
def test_get_occupied_size(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
sender.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]
self.assertEqual(sender.get_occupied_size(), 10)
def test_get_occupied_size_2(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
sender.inbox =[]
self.assertEqual(sender.get_occupied_size(), 0)
def test_get_occupied_size_3(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
sender.inbox = [
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 20,
'time': datetime.now, 'state': 'unread'}]
self.assertEqual(sender.get_occupied_size(), 20)
def test_get_occupied_size_4(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
sender.inbox = [
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 20,
'time': datetime.now, 'state': 'unread'},
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 30,
'time': datetime.now, 'state': 'unread'}]
self.assertEqual(sender.get_occupied_size(), 50)
def test_get_occupied_size_5(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
sender.inbox = [
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 20,
'time': datetime.now, 'state': 'unread'},
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 60,
'time': datetime.now, 'state': 'unread'}]
self.assertEqual(sender.get_occupied_size(), 80)
class EmailClientTestClearInbox(unittest.TestCase):
def test_clear_inbox(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]
receiver.clear_inbox(30)
self.assertEqual(receiver.inbox, [{'size': 15}])
def test_clear_inbox_2(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('', 50)
receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]
self.assertEqual(receiver.clear_inbox(30),None)
self.assertEqual(receiver.inbox, [{'size': 10},{'size': 20},{'size': 15}])
def test_clear_inbox_3(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
receiver.inbox = [{'size': 10}, {'size': 20}, {'size': 15}]
self.assertEqual(receiver.clear_inbox(50), None)
def test_clear_inbox_4(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
receiver.inbox = [{'size': 10}, {'size': 20}, {'size': 15}]
receiver.clear_inbox(45)
self.assertEqual(receiver.inbox, [])
def test_clear_inbox_5(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
receiver.inbox = [{'size': 10}, {'size': 20}, {'size': 15}]
receiver.clear_inbox(10)
self.assertEqual(receiver.inbox, [{'size': 20}, {'size': 15}])
class EmailClientTestMain(unittest.TestCase):
def test_main(self):
sender = EmailClient('[email protected]', 100)
receiver = EmailClient('[email protected]', 50)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.assertTrue(sender.send_to(receiver, 'Hello', 10))
self.assertEqual(receiver.inbox[0], {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': timestamp, 'state': 'unread'})
self.assertEqual(receiver.fetch(), {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': timestamp, 'state': 'read'})
self.assertFalse(receiver.is_full_with_one_more_email(10))
self.assertEqual(receiver.get_occupied_size(), 10)
receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]
receiver.clear_inbox(30)
self.assertEqual(receiver.inbox, [{'size': 15}]) | from datetime import datetime
class EmailClient:
def __init__(self, addr, capacity) -> None:
self.addr = addr
self.capacity = capacity
self.inbox = []
def send_to(self, recv, content, size):
if not recv.is_full_with_one_more_email(size):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
email = {
"sender": self.addr,
"receiver": recv.addr,
"content": content,
"size": size,
"time": timestamp,
"state": "unread"
}
recv.inbox.append(email)
return True
else:
self.clear_inbox(size)
return False
def fetch(self):
if len(self.inbox) == 0:
return None
for i in range(len(self.inbox)):
if self.inbox[i]['state'] == "unread":
self.inbox[i]['state'] = "read"
return self.inbox[i]
return None
def is_full_with_one_more_email(self, size):
occupied_size = self.get_occupied_size()
return True if occupied_size + size > self.capacity else False
def get_occupied_size(self):
occupied_size = 0
for email in self.inbox:
occupied_size += email["size"]
return occupied_size
def clear_inbox(self, size):
if len(self.addr) == 0:
return
freed_space = 0
while freed_space < size and self.inbox:
email = self.inbox[0]
freed_space += email['size']
del self.inbox[0] | [
"from datetime import datetime"
] | """
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
| [
{
"method_name": "send_to",
"method_description": "def send_to(self, recv, content, size):\n \"\"\"\n Sends an email to the given email address.\n :param recv: The email address of the receiver, str.\n :param content: The content of the email, str.\n :param size: The size of the email, float.\n :return: True if the email is sent successfully, False if the receiver's email box is full.\n >>> sender = EmailClient('[email protected]', 100)\n >>> receiver = EmailClient('[email protected]', 50)\n >>> sender.send_to(receiver, 'Hello', 10)\n True\n >>> receiver.inbox\n {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}\n\n \"\"\"",
"test_class": "EmailClientTestSendTo",
"test_code": "class EmailClientTestSendTo(unittest.TestCase):\n def test_send_to(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertTrue(sender.send_to(receiver, 'Hello', 10))\n self.assertEqual(receiver.inbox[0], {\"sender\": '[email protected]','receiver': '[email protected]','content': 'Hello','size': 10,'time': timestamp,'state': 'unread'})\n\n def test_send_to_2(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 0)\n self.assertFalse(sender.send_to(receiver, 'Hello', 10))\n\n def test_send_to_3(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n receiver.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 50, 'time': '2021-01-01 00:00:00', 'state': 'unread'}]\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertFalse(sender.send_to(receiver, 'Hello', 10))\n self.assertEqual(receiver.inbox, [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 50, 'time': '2021-01-01 00:00:00', 'state': 'unread'}])\n\n def test_send_to_4(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 30)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertTrue(sender.send_to(receiver, 'Hello', 20))\n self.assertEqual(receiver.inbox, [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 20, 'time': timestamp, 'state': 'unread'}])\n\n def test_send_to_5(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 30)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertTrue(sender.send_to(receiver, 'bye', 20))\n self.assertEqual(receiver.inbox, [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'bye', 'size': 20, 'time': timestamp, 'state': 'unread'}])",
"solution_code": "def send_to(self, recv, content, size):\n if not recv.is_full_with_one_more_email(size):\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n email = {\n \"sender\": self.addr,\n \"receiver\": recv.addr,\n \"content\": content,\n \"size\": size,\n \"time\": timestamp,\n \"state\": \"unread\"\n }\n recv.inbox.append(email)\n return True\n else:\n self.clear_inbox(size)\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"datetime"
],
"field_dependencies": [
"self.addr"
],
"method_dependencies": [
"is_full_with_one_more_email",
"clear_inbox"
]
}
},
{
"method_name": "fetch",
"method_description": "def fetch(self):\n \"\"\"\n Retrieves the first unread email in the email box and marks it as read.\n :return: The first unread email in the email box, dict.\n >>> sender = EmailClient('[email protected]', 100)\n >>> receiver = EmailClient('[email protected]', 50)\n >>> receiver.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}]\n >>> receiver.fetch()\n {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'read'}\n\n \"\"\"",
"test_class": "EmailClientTestFetch",
"test_code": "class EmailClientTestFetch(unittest.TestCase):\n def test_fetch(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n receiver.inbox = [\n {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'unread'}]\n self.assertEqual(receiver.fetch(), {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time':timestamp, 'state': 'read'})\n\n def test_fetch_2(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertEqual(receiver.fetch(),None)\n\n def test_fetch_3(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n receiver.inbox = [\n {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'read'}]\n self.assertEqual(receiver.fetch(), None)\n\n def test_fetch_4(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n receiver.inbox = [\n {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,\n 'time': '2021-01-01 00:00:00', 'state': 'unread'},\n {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'unread'}]\n self.assertEqual(receiver.fetch(), {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,\n 'time': '2021-01-01 00:00:00', 'state': 'read'})\n\n def test_fetch_5(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n receiver.inbox = [\n {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,\n 'time': '2021-01-01 00:00:00', 'state': 'read'},\n {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'unread'}]\n self.assertEqual(receiver.fetch(), {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'read'})",
"solution_code": "def fetch(self):\n if len(self.inbox) == 0:\n return None\n for i in range(len(self.inbox)):\n if self.inbox[i]['state'] == \"unread\":\n self.inbox[i]['state'] = \"read\"\n return self.inbox[i]\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.inbox"
],
"method_dependencies": []
}
},
{
"method_name": "is_full_with_one_more_email",
"method_description": "def is_full_with_one_more_email(self, size):\n \"\"\"\n Determines whether the email box is full after adding an email of the given size.\n :param size: The size of the email, float.\n :return: True if the email box is full, False otherwise.\n >>> sender = EmailClient('[email protected]', 100)\n >>> receiver = EmailClient('[email protected]', 50)\n >>> receiver.is_full_with_one_more_email(10)\n False\n\n \"\"\"",
"test_class": "EmailClientTestIsFullWithOneMoreEmail",
"test_code": "class EmailClientTestIsFullWithOneMoreEmail(unittest.TestCase):\n def test_is_full_with_one_more_email(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n self.assertFalse(receiver.is_full_with_one_more_email(10))\n\n def test_is_full_with_one_more_email_2(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 0)\n self.assertTrue(receiver.is_full_with_one_more_email(10))\n\n def test_is_full_with_one_more_email_3(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 10)\n self.assertFalse(receiver.is_full_with_one_more_email(10))\n\n def test_is_full_with_one_more_email_4(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 10)\n self.assertTrue(receiver.is_full_with_one_more_email(20))\n\n def test_is_full_with_one_more_email_5(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 20)\n self.assertFalse(receiver.is_full_with_one_more_email(20))",
"solution_code": "def is_full_with_one_more_email(self, size):\n occupied_size = self.get_occupied_size()\n return True if occupied_size + size > self.capacity else False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.capacity"
],
"method_dependencies": [
"get_occupied_size"
]
}
},
{
"method_name": "get_occupied_size",
"method_description": "def get_occupied_size(self):\n \"\"\"\n Gets the total size of the emails in the email box.\n :return: The total size of the emails in the email box, float.\n >>> sender = EmailClient('[email protected]', 100)\n >>> receiver = EmailClient('[email protected]', 50)\n >>> sender.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]\n >>> sender.get_occupied_size()\n 10\n\n \"\"\"",
"test_class": "EmailClientTestGetOccupiedSize",
"test_code": "class EmailClientTestGetOccupiedSize(unittest.TestCase):\n def test_get_occupied_size(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n sender.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]\n self.assertEqual(sender.get_occupied_size(), 10)\n\n def test_get_occupied_size_2(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n sender.inbox =[]\n self.assertEqual(sender.get_occupied_size(), 0)\n\n def test_get_occupied_size_3(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n sender.inbox = [\n {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 20,\n 'time': datetime.now, 'state': 'unread'}]\n self.assertEqual(sender.get_occupied_size(), 20)\n\n def test_get_occupied_size_4(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n sender.inbox = [\n {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 20,\n 'time': datetime.now, 'state': 'unread'},\n {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 30,\n 'time': datetime.now, 'state': 'unread'}]\n self.assertEqual(sender.get_occupied_size(), 50)\n\n def test_get_occupied_size_5(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n sender.inbox = [\n {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 20,\n 'time': datetime.now, 'state': 'unread'},\n {'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 60,\n 'time': datetime.now, 'state': 'unread'}]\n self.assertEqual(sender.get_occupied_size(), 80)",
"solution_code": "def get_occupied_size(self):\n occupied_size = 0\n for email in self.inbox:\n occupied_size += email[\"size\"]\n return occupied_size",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.inbox"
],
"method_dependencies": []
}
},
{
"method_name": "clear_inbox",
"method_description": "def clear_inbox(self, size):\n \"\"\"\n Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size.\n :param size: The size of the email, float.\n >>> sender = EmailClient('[email protected]', 100)\n >>> receiver = EmailClient('[email protected]', 50)\n >>> receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]\n >>> receiver.clear_inbox(30)\n >>> receiver.inbox\n [{'size': 15}]\n\n \"\"\"",
"test_class": "EmailClientTestClearInbox",
"test_code": "class EmailClientTestClearInbox(unittest.TestCase):\n def test_clear_inbox(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]\n receiver.clear_inbox(30)\n self.assertEqual(receiver.inbox, [{'size': 15}])\n\n def test_clear_inbox_2(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('', 50)\n receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]\n self.assertEqual(receiver.clear_inbox(30),None)\n self.assertEqual(receiver.inbox, [{'size': 10},{'size': 20},{'size': 15}])\n\n def test_clear_inbox_3(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n receiver.inbox = [{'size': 10}, {'size': 20}, {'size': 15}]\n self.assertEqual(receiver.clear_inbox(50), None)\n\n def test_clear_inbox_4(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n receiver.inbox = [{'size': 10}, {'size': 20}, {'size': 15}]\n receiver.clear_inbox(45)\n self.assertEqual(receiver.inbox, [])\n def test_clear_inbox_5(self):\n sender = EmailClient('[email protected]', 100)\n receiver = EmailClient('[email protected]', 50)\n receiver.inbox = [{'size': 10}, {'size': 20}, {'size': 15}]\n receiver.clear_inbox(10)\n self.assertEqual(receiver.inbox, [{'size': 20}, {'size': 15}])",
"solution_code": "def clear_inbox(self, size):\n if len(self.addr) == 0:\n return\n freed_space = 0\n while freed_space < size and self.inbox:\n email = self.inbox[0]\n freed_space += email['size']\n del self.inbox[0]",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.addr",
"self.inbox"
],
"method_dependencies": []
}
}
] | EmailClient | [
"EmailClientTestSendTo",
"EmailClientTestFetch",
"EmailClientTestIsFullWithOneMoreEmail",
"EmailClientTestGetOccupiedSize",
"EmailClientTestClearInbox",
"EmailClientTestMain"
] | class EmailClient:
def __init__(self, addr, capacity) -> None:
"""
Initializes the EmailClient class with the email address and the capacity of the email box.
:param addr: The email address, str.
:param capacity: The capacity of the email box, float.
"""
self.addr = addr
self.capacity = capacity
self.inbox = []
| [
"self.addr",
"self.capacity",
"self.inbox"
] |
ClassEval_37 | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the class with a key.
:param key: The key to use for encryption, str.
"""
self.key = key
def caesar_cipher(self, plaintext, shift):
"""
Encrypts the plaintext using the Caesar cipher.
:param plaintext: The plaintext to encrypt, str.
:param shift: The number of characters to shift each character in the plaintext, int.
:return: The ciphertext, str.
>>> e = EncryptionUtils("key")
>>> e.caesar_cipher("abc", 1)
'bcd'
"""
def vigenere_cipher(self, plaintext):
"""
Encrypts the plaintext using the Vigenere cipher.
:param plaintext: The plaintext to encrypt, str.
:return: The ciphertext, str.
>>> e = EncryptionUtils("key")
>>> e.vigenere_cipher("abc")
'kfa'
"""
def rail_fence_cipher(self,plain_text, rails):
"""
Encrypts the plaintext using the Rail Fence cipher.
:param plaintext: The plaintext to encrypt, str.
:return: The ciphertext, str.
>>> e = EncryptionUtils("key")
>>> e.rail_fence_cipher("abc", 2)
'acb'
""" | import unittest
class EncryptionUtilsTestCaesarCipher(unittest.TestCase):
def test_caesar_cipher(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.caesar_cipher("abc", 1), "bcd")
def test_caesar_cipher_2(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.caesar_cipher("WORLD", -2), "UMPJB")
def test_caesar_cipher_3(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.caesar_cipher("", 4), "")
def test_caesar_cipher_4(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.caesar_cipher("abcxyz", 26), "abcxyz")
def test_caesar_cipher_5(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.caesar_cipher("abcxyz", 27), "bcdyza")
def test_caesar_cipher_6(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.caesar_cipher("123", 27), "123")
class EncryptionUtilsTestVigenereCipher(unittest.TestCase):
def test_vigenere_cipher(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.vigenere_cipher("abc"), "kfa")
def test_vigenere_cipher_2(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.vigenere_cipher("hello"), "rijvs")
def test_vigenere_cipher_3(self):
encryption_utils = EncryptionUtils("longkey")
self.assertEqual(encryption_utils.vigenere_cipher("AbCdEfG"), "LpPjOjE")
def test_vigenere_cipher_4(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.vigenere_cipher("Hello, World! 123"), "Rijvs, Uyvjn! 123")
def test_vigenere_cipher_5(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.vigenere_cipher(""), "")
class EncryptionUtilsTestRailFenceCipher(unittest.TestCase):
def test_rail_fence_cipher(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.rail_fence_cipher("abc", 2), "acb")
def test_rail_fence_cipher_2(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.rail_fence_cipher("hello", 2), "hloel")
def test_rail_fence_cipher_3(self):
encryption_utils = EncryptionUtils("longkey")
self.assertEqual(encryption_utils.rail_fence_cipher("AbCdEfG", 2), "ACEGbdf")
def test_rail_fence_cipher_4(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.rail_fence_cipher("Hello, World! 123", 2), "Hlo ol!13el,Wrd 2")
def test_rail_fence_cipher_5(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.rail_fence_cipher("", 2), "")
def test_rail_fence_cipher_6(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.rail_fence_cipher("abcdefg", 3), "aebdfcg")
class EncryptionUtilsTestMain(unittest.TestCase):
def test_main(self):
encryption_utils = EncryptionUtils("key")
self.assertEqual(encryption_utils.caesar_cipher("abc", 1), "bcd")
self.assertEqual(encryption_utils.vigenere_cipher("abc"), "kfa")
self.assertEqual(encryption_utils.rail_fence_cipher("abc", 2), "acb") | class EncryptionUtils:
def __init__(self, key):
self.key = key
def caesar_cipher(self, plaintext, shift):
ciphertext = ""
for char in plaintext:
if char.isalpha():
if char.isupper():
ascii_offset = 65
else:
ascii_offset = 97
shifted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
ciphertext += shifted_char
else:
ciphertext += char
return ciphertext
def vigenere_cipher(self, plain_text):
encrypted_text = ""
key_index = 0
for char in plain_text:
if char.isalpha():
shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')
encrypted_char = chr((ord(char.lower()) - ord('a') + shift) % 26 + ord('a'))
encrypted_text += encrypted_char.upper() if char.isupper() else encrypted_char
key_index += 1
else:
encrypted_text += char
return encrypted_text
def rail_fence_cipher(self, plain_text, rails):
fence = [['\n' for _ in range(len(plain_text))] for _ in range(rails)]
direction = -1
row, col = 0, 0
for char in plain_text:
if row == 0 or row == rails-1:
direction = -direction
fence[row][col] = char
col += 1
row += direction
encrypted_text = ''
for i in range(rails):
for j in range(len(plain_text)):
if fence[i][j] != '\n':
encrypted_text += fence[i][j]
return encrypted_text | [] | """
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
| [
{
"method_name": "caesar_cipher",
"method_description": "def caesar_cipher(self, plaintext, shift):\n \"\"\"\n Encrypts the plaintext using the Caesar cipher.\n :param plaintext: The plaintext to encrypt, str.\n :param shift: The number of characters to shift each character in the plaintext, int.\n :return: The ciphertext, str.\n >>> e = EncryptionUtils(\"key\")\n >>> e.caesar_cipher(\"abc\", 1)\n 'bcd'\n\n \"\"\"",
"test_class": "EncryptionUtilsTestCaesarCipher",
"test_code": "class EncryptionUtilsTestCaesarCipher(unittest.TestCase):\n def test_caesar_cipher(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"abc\", 1), \"bcd\")\n\n def test_caesar_cipher_2(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"WORLD\", -2), \"UMPJB\")\n\n def test_caesar_cipher_3(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"\", 4), \"\")\n\n def test_caesar_cipher_4(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"abcxyz\", 26), \"abcxyz\")\n\n def test_caesar_cipher_5(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"abcxyz\", 27), \"bcdyza\")\n\n def test_caesar_cipher_6(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"123\", 27), \"123\")",
"solution_code": "def caesar_cipher(self, plaintext, shift):\n ciphertext = \"\"\n for char in plaintext:\n if char.isalpha():\n if char.isupper():\n ascii_offset = 65\n else:\n ascii_offset = 97\n shifted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)\n ciphertext += shifted_char\n else:\n ciphertext += char\n return ciphertext",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "vigenere_cipher",
"method_description": "def vigenere_cipher(self, plaintext):\n \"\"\"\n Encrypts the plaintext using the Vigenere cipher.\n :param plaintext: The plaintext to encrypt, str.\n :return: The ciphertext, str.\n >>> e = EncryptionUtils(\"key\")\n >>> e.vigenere_cipher(\"abc\")\n 'kfa'\n\n \"\"\"",
"test_class": "EncryptionUtilsTestVigenereCipher",
"test_code": "class EncryptionUtilsTestVigenereCipher(unittest.TestCase):\n def test_vigenere_cipher(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"abc\"), \"kfa\")\n\n def test_vigenere_cipher_2(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"hello\"), \"rijvs\")\n\n def test_vigenere_cipher_3(self):\n encryption_utils = EncryptionUtils(\"longkey\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"AbCdEfG\"), \"LpPjOjE\")\n\n def test_vigenere_cipher_4(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"Hello, World! 123\"), \"Rijvs, Uyvjn! 123\")\n\n def test_vigenere_cipher_5(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"\"), \"\")",
"solution_code": "def vigenere_cipher(self, plain_text):\n encrypted_text = \"\"\n key_index = 0\n for char in plain_text:\n if char.isalpha():\n shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')\n encrypted_char = chr((ord(char.lower()) - ord('a') + shift) % 26 + ord('a'))\n encrypted_text += encrypted_char.upper() if char.isupper() else encrypted_char\n key_index += 1\n else:\n encrypted_text += char\n return encrypted_text",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.key"
],
"method_dependencies": []
}
},
{
"method_name": "rail_fence_cipher",
"method_description": "def rail_fence_cipher(self,plain_text, rails):\n \"\"\"\n Encrypts the plaintext using the Rail Fence cipher.\n :param plaintext: The plaintext to encrypt, str.\n :return: The ciphertext, str.\n >>> e = EncryptionUtils(\"key\")\n >>> e.rail_fence_cipher(\"abc\", 2)\n 'acb'\n\n \"\"\"",
"test_class": "EncryptionUtilsTestRailFenceCipher",
"test_code": "class EncryptionUtilsTestRailFenceCipher(unittest.TestCase):\n def test_rail_fence_cipher(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"abc\", 2), \"acb\")\n\n def test_rail_fence_cipher_2(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"hello\", 2), \"hloel\")\n\n def test_rail_fence_cipher_3(self):\n encryption_utils = EncryptionUtils(\"longkey\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"AbCdEfG\", 2), \"ACEGbdf\")\n\n def test_rail_fence_cipher_4(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"Hello, World! 123\", 2), \"Hlo ol!13el,Wrd 2\")\n\n def test_rail_fence_cipher_5(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"\", 2), \"\")\n\n def test_rail_fence_cipher_6(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"abcdefg\", 3), \"aebdfcg\")",
"solution_code": "def rail_fence_cipher(self, plain_text, rails):\n fence = [['\\n' for _ in range(len(plain_text))] for _ in range(rails)]\n direction = -1\n row, col = 0, 0\n\n for char in plain_text:\n if row == 0 or row == rails-1:\n direction = -direction\n\n fence[row][col] = char\n col += 1\n row += direction\n\n encrypted_text = ''\n for i in range(rails):\n for j in range(len(plain_text)):\n if fence[i][j] != '\\n':\n encrypted_text += fence[i][j]\n\n return encrypted_text",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | EncryptionUtils | [
"EncryptionUtilsTestCaesarCipher",
"EncryptionUtilsTestVigenereCipher",
"EncryptionUtilsTestRailFenceCipher",
"EncryptionUtilsTestMain"
] | class EncryptionUtils:
def __init__(self, key):
"""
Initializes the class with a key.
:param key: The key to use for encryption, str.
"""
self.key = key
| [
"self.key"
] |
ClassEval_38 | import openpyxl
class ExcelProcessor:
"""
This is a class for processing excel files, including readring and writing excel data, as well as processing specific operations and saving as a new excel file.
"""
def __init__(self):
pass
def read_excel(self, file_name):
"""
Reading data from Excel files
:param file_name:str, Excel file name to read
:return:list of data, Data in Excel
"""
def write_excel(self, data, file_name):
"""
Write data to the specified Excel file
:param data: list, Data to be written
:param file_name: str, Excel file name to write to
:return: 0 or 1, 1 represents successful writing, 0 represents failed writing
>>> processor = ExcelProcessor()
>>> new_data = [
>>> ('Name', 'Age', 'Country'),
>>> ('John', 25, 'USA'),
>>> ('Alice', 30, 'Canada'),
>>> ('Bob', 35, 'Australia'),
>>> ('Julia', 28, 'Germany')
>>> ]
>>> data = processor.write_excel(new_data, 'test_data.xlsx')
"""
def process_excel_data(self, N, save_file_name):
"""
Change the specified column in the Excel file to uppercase
:param N: int, The serial number of the column that want to change
:param save_file_name: str, source file name
:return:(int, str), The former is the return value of write_excel, while the latter is the saved file name of the processed data
>>> processor = ExcelProcessor()
>>> success, output_file = processor.process_excel_data(1, 'test_data.xlsx')
""" | import unittest
import os
class ExcelProcessorTestReadExcel(unittest.TestCase):
def test_read_excel_1(self):
self.test_file_name = 'test_data.xlsx'
data = [['Name', 'Age', 'Country'],
['John', 25, 'USA'],
['Alice', 30, 'Canada'],
['Bob', 35, 'Australia']]
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(self.test_file_name)
workbook.close()
processor = ExcelProcessor()
data = processor.read_excel(self.test_file_name)
expected_data = [
('Name', 'Age', 'Country'),
('John', 25, 'USA'),
('Alice', 30, 'Canada'),
('Bob', 35, 'Australia')
]
self.assertEqual(data, expected_data)
def test_read_excel_2(self):
self.test_file_name = 'test_data.xlsx'
data = [['Name', 'Age'],
['John', 25],
['Alice', 30],
['Bob', 35]]
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(self.test_file_name)
workbook.close()
processor = ExcelProcessor()
data = processor.read_excel(self.test_file_name)
expected_data = [
('Name', 'Age'),
('John', 25),
('Alice', 30),
('Bob', 35)
]
self.assertEqual(data, expected_data)
def test_read_excel_3(self):
self.test_file_name = 'test_data.xlsx'
data = [['Name'],
['John'],
['Alice'],
['Bob']]
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(self.test_file_name)
workbook.close()
processor = ExcelProcessor()
data = processor.read_excel(self.test_file_name)
expected_data = [
('Name',),
('John',),
('Alice',),
('Bob',)
]
self.assertEqual(data, expected_data)
def test_read_excel_4(self):
self.test_file_name = 'test_data.xlsx'
data = [['Name', 'Country'],
['John', 'USA'],
['Alice', 'Canada'],
['Bob', 'Australia']]
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(self.test_file_name)
workbook.close()
processor = ExcelProcessor()
data = processor.read_excel(self.test_file_name)
expected_data = [
('Name', 'Country'),
('John', 'USA'),
('Alice', 'Canada'),
('Bob', 'Australia')
]
self.assertEqual(data, expected_data)
def test_read_excel_5(self):
self.test_file_name = 'test_data.xlsx'
data = [['Name', 'Country'],
['John', 'USA']]
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(self.test_file_name)
workbook.close()
processor = ExcelProcessor()
data = processor.read_excel(self.test_file_name)
expected_data = [
('Name', 'Country'),
('John', 'USA')
]
self.assertEqual(data, expected_data)
def test_read_excel_6(self):
self.test_file_name = ''
processor = ExcelProcessor()
res = processor.read_excel(self.test_file_name)
self.assertEqual(res, None)
class ExcelProcessorTestWriteExcel(unittest.TestCase):
def test_write_excel_1(self):
processor = ExcelProcessor()
new_data = [
('Name', 'Age', 'Country'),
('John', 25, 'USA'),
('Alice', 30, 'Canada'),
('Bob', 35, 'Australia'),
('Julia', 28, 'Germany')
]
save_file_name = 'test_output.xlsx'
success = processor.write_excel(new_data, save_file_name)
self.assertTrue(success)
self.assertTrue(os.path.exists(save_file_name))
saved_data = processor.read_excel(save_file_name)
self.assertEqual(saved_data, new_data)
os.remove(save_file_name)
def test_write_excel_2(self):
processor = ExcelProcessor()
new_data = [
('Name', 'Age'),
('John', 25),
('Alice', 30),
('Bob', 35),
('Julia', 28)
]
save_file_name = 'test_output.xlsx'
success = processor.write_excel(new_data, save_file_name)
self.assertTrue(success)
self.assertTrue(os.path.exists(save_file_name))
saved_data = processor.read_excel(save_file_name)
self.assertEqual(saved_data, new_data)
os.remove(save_file_name)
def test_write_excel_3(self):
processor = ExcelProcessor()
new_data = [
('Name', 'Age', 'Country'),
('John', 25, 'USA'),
('Alice', 30, 'Canada'),
('Bob', 35, 'Australia')
]
save_file_name = 'test_output.xlsx'
success = processor.write_excel(new_data, save_file_name)
self.assertTrue(success)
self.assertTrue(os.path.exists(save_file_name))
saved_data = processor.read_excel(save_file_name)
self.assertEqual(saved_data, new_data)
os.remove(save_file_name)
def test_write_excel_4(self):
processor = ExcelProcessor()
new_data = [
('Name', 'Age', 'Country'),
('John', 25, 'USA'),
('Alice', 30, 'Canada')
]
save_file_name = 'test_output.xlsx'
success = processor.write_excel(new_data, save_file_name)
self.assertTrue(success)
self.assertTrue(os.path.exists(save_file_name))
saved_data = processor.read_excel(save_file_name)
self.assertEqual(saved_data, new_data)
os.remove(save_file_name)
def test_write_excel_5(self):
processor = ExcelProcessor()
new_data = [
('Name', 'Age', 'Country'),
('John', 25, 'USA')
]
save_file_name = 'test_output.xlsx'
success = processor.write_excel(new_data, save_file_name)
self.assertTrue(success)
self.assertTrue(os.path.exists(save_file_name))
saved_data = processor.read_excel(save_file_name)
self.assertEqual(saved_data, new_data)
os.remove(save_file_name)
def test_write_excel_6(self):
processor = ExcelProcessor()
new_data = [
('Name', 'Age', 'Country'),
('John', 25, 'USA')
]
save_file_name = ''
success = processor.write_excel(new_data, save_file_name)
self.assertEqual(success, 0)
class ExcelProcessorTestProcessExcelData(unittest.TestCase):
def test_process_excel_data_1(self):
self.test_file_name = 'test_data.xlsx'
data = [['Name', 'Age', 'Country'],
['John', 25, 'USA'],
['Alice', 30, 'Canada'],
['Bob', 35, 'Australia']]
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(self.test_file_name)
workbook.close()
processor = ExcelProcessor()
N = 1
success, output_file = processor.process_excel_data(N, self.test_file_name)
self.assertTrue(success)
self.assertTrue(os.path.isfile(output_file))
processed_data = processor.read_excel(output_file)
expected_processed_data = [
('Name', 'Age', 'Country', 'AGE'),
('John', 25, 'USA', 25),
('Alice', 30, 'Canada', 30),
('Bob', 35, 'Australia', 35)
]
self.assertEqual(processed_data, expected_processed_data)
os.remove(output_file)
def test_process_excel_data_2(self):
self.test_file_name = 'test_data.xlsx'
data = [['Name', 'Age', 'Country'],
['John', 25, 'USA'],
['Alice', 30, 'Canada'],
['Bob', 35, 'Australia']]
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(self.test_file_name)
workbook.close()
processor = ExcelProcessor()
N = 0
success, output_file = processor.process_excel_data(N, self.test_file_name)
self.assertTrue(success)
self.assertTrue(os.path.isfile(output_file))
processed_data = processor.read_excel(output_file)
expected_processed_data = [
('Name', 'Age', 'Country', 'NAME'),
('John', 25, 'USA', 'JOHN'),
('Alice', 30, 'Canada', 'ALICE'),
('Bob', 35, 'Australia', 'BOB')
]
self.assertEqual(processed_data, expected_processed_data)
os.remove(output_file)
def test_process_excel_data_3(self):
self.test_file_name = 'test_data.xlsx'
data = [['Name', 'Age', 'Country'],
['John', 25, 'USA'],
['Alice', 30, 'Canada'],
['Bob', 35, 'Australia']]
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(self.test_file_name)
workbook.close()
processor = ExcelProcessor()
N = 2
success, output_file = processor.process_excel_data(N, self.test_file_name)
self.assertTrue(success)
self.assertTrue(os.path.isfile(output_file))
processed_data = processor.read_excel(output_file)
expected_processed_data = [
('Name', 'Age', 'Country', 'COUNTRY'),
('John', 25, 'USA', 'USA'),
('Alice', 30, 'Canada', 'CANADA'),
('Bob', 35, 'Australia', 'AUSTRALIA')
]
self.assertEqual(processed_data, expected_processed_data)
os.remove(output_file)
def test_process_excel_data_4(self):
self.test_file_name = 'test_data.xlsx'
data = [['Name', 'Age', 'COUNTRY'],
['John', 25, 'USA'],
['Alice', 30, 'CANADA'],
['Bob', 35, 'AUSTRALIA']]
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(self.test_file_name)
workbook.close()
processor = ExcelProcessor()
N = 2
success, output_file = processor.process_excel_data(N, self.test_file_name)
self.assertTrue(success)
self.assertTrue(os.path.isfile(output_file))
processed_data = processor.read_excel(output_file)
expected_processed_data = [
('Name', 'Age', 'COUNTRY', 'COUNTRY'),
('John', 25, 'USA', 'USA'),
('Alice', 30, 'CANADA', 'CANADA'),
('Bob', 35, 'AUSTRALIA', 'AUSTRALIA')
]
self.assertEqual(processed_data, expected_processed_data)
os.remove(output_file)
def test_process_excel_data_5(self):
self.test_file_name = 'test_data.xlsx'
data = [['Name', 'AGE', 'COUNTRY'],
['John', 25, 'USA'],
['Alice', 30, 'CANADA'],
['Bob', 35, 'AUSTRALIA']]
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(self.test_file_name)
workbook.close()
processor = ExcelProcessor()
N = 1
success, output_file = processor.process_excel_data(N, self.test_file_name)
self.assertTrue(success)
self.assertTrue(os.path.isfile(output_file))
processed_data = processor.read_excel(output_file)
expected_processed_data = [
('Name', 'AGE', 'COUNTRY', 'AGE'),
('John', 25, 'USA', 25),
('Alice', 30, 'CANADA', 30),
('Bob', 35, 'AUSTRALIA', 35)
]
self.assertEqual(processed_data, expected_processed_data)
os.remove(output_file)
def test_process_excel_data_6(self):
self.test_file_name = 'test_data.xlsx'
data = [['Name', 'AGE', 'COUNTRY'],
['John', 25, 'USA'],
['Alice', 30, 'CANADA'],
['Bob', 35, 'AUSTRALIA']]
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(self.test_file_name)
workbook.close()
processor = ExcelProcessor()
res = processor.process_excel_data(100, self.test_file_name)
self.assertEqual(res, 0)
class ExcelProcessorTest(unittest.TestCase):
def test_ExcelProcessor(self):
self.test_file_name = 'test_data.xlsx'
data = [['Name', 'Age', 'Country'],
['John', 25, 'USA'],
['Alice', 30, 'Canada'],
['Bob', 35, 'Australia']]
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(self.test_file_name)
workbook.close()
processor = ExcelProcessor()
data = processor.read_excel(self.test_file_name)
expected_data = [
('Name', 'Age', 'Country'),
('John', 25, 'USA'),
('Alice', 30, 'Canada'),
('Bob', 35, 'Australia')
]
self.assertEqual(data, expected_data)
processor = ExcelProcessor()
new_data = [
('Name', 'Age', 'Country'),
('John', 25, 'USA'),
('Alice', 30, 'Canada'),
('Bob', 35, 'Australia'),
('Julia', 28, 'Germany')
]
save_file_name = 'test_output.xlsx'
success = processor.write_excel(new_data, save_file_name)
self.assertTrue(success)
self.assertTrue(os.path.exists(save_file_name))
saved_data = processor.read_excel(save_file_name)
self.assertEqual(saved_data, new_data)
os.remove(save_file_name)
self.test_file_name = 'test_data.xlsx'
data = [['Name', 'Age', 'Country'],
['John', 25, 'USA'],
['Alice', 30, 'Canada'],
['Bob', 35, 'Australia']]
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(self.test_file_name)
workbook.close()
processor = ExcelProcessor()
N = 1
success, output_file = processor.process_excel_data(N, self.test_file_name)
self.assertTrue(success)
self.assertTrue(os.path.isfile(output_file))
processed_data = processor.read_excel(output_file)
expected_processed_data = [
('Name', 'Age', 'Country', 'AGE'),
('John', 25, 'USA', 25),
('Alice', 30, 'Canada', 30),
('Bob', 35, 'Australia', 35)
]
self.assertEqual(processed_data, expected_processed_data)
os.remove(output_file) | import openpyxl
class ExcelProcessor:
def __init__(self):
pass
def read_excel(self, file_name):
data = []
try:
workbook = openpyxl.load_workbook(file_name)
sheet = workbook.active
for row in sheet.iter_rows(values_only=True):
data.append(row)
workbook.close()
return data
except:
return None
def write_excel(self, data, file_name):
try:
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(file_name)
workbook.close()
return 1
except:
return 0
def process_excel_data(self, N, save_file_name):
data = self.read_excel(save_file_name)
if data is None or N >= len(data[0]):
return 0
new_data = []
for row in data:
new_row = list(row[:])
if not str(row[N]).isdigit():
new_row.append(str(row[N]).upper())
else:
new_row.append(row[N])
new_data.append(new_row)
new_file_name = save_file_name.split('.')[0] + '_process.xlsx'
success = self.write_excel(new_data, new_file_name)
return success, new_file_name | [
"import openpyxl"
] | """
This is a class for processing excel files, including readring and writing excel data, as well as processing specific operations and saving as a new excel file.
"""
| [
{
"method_name": "read_excel",
"method_description": "def read_excel(self, file_name):\n \"\"\"\n Reading data from Excel files\n :param file_name:str, Excel file name to read\n :return:list of data, Data in Excel\n \"\"\"",
"test_class": "ExcelProcessorTestReadExcel",
"test_code": "class ExcelProcessorTestReadExcel(unittest.TestCase):\n def test_read_excel_1(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada'),\n ('Bob', 35, 'Australia')\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_2(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age'],\n ['John', 25],\n ['Alice', 30],\n ['Bob', 35]]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name', 'Age'),\n ('John', 25),\n ('Alice', 30),\n ('Bob', 35)\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_3(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name'],\n ['John'],\n ['Alice'],\n ['Bob']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name',),\n ('John',),\n ('Alice',),\n ('Bob',)\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_4(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Country'],\n ['John', 'USA'],\n ['Alice', 'Canada'],\n ['Bob', 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name', 'Country'),\n ('John', 'USA'),\n ('Alice', 'Canada'),\n ('Bob', 'Australia')\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_5(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Country'],\n ['John', 'USA']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name', 'Country'),\n ('John', 'USA')\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_6(self):\n self.test_file_name = ''\n processor = ExcelProcessor()\n res = processor.read_excel(self.test_file_name)\n self.assertEqual(res, None)",
"solution_code": "def read_excel(self, file_name):\n data = []\n try:\n workbook = openpyxl.load_workbook(file_name)\n sheet = workbook.active\n for row in sheet.iter_rows(values_only=True):\n data.append(row)\n workbook.close()\n return data\n except:\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"openpyxl"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "write_excel",
"method_description": "def write_excel(self, data, file_name):\n \"\"\"\n Write data to the specified Excel file\n :param data: list, Data to be written\n :param file_name: str, Excel file name to write to\n :return: 0 or 1, 1 represents successful writing, 0 represents failed writing\n >>> processor = ExcelProcessor()\n >>> new_data = [\n >>> ('Name', 'Age', 'Country'),\n >>> ('John', 25, 'USA'),\n >>> ('Alice', 30, 'Canada'),\n >>> ('Bob', 35, 'Australia'),\n >>> ('Julia', 28, 'Germany')\n >>> ]\n >>> data = processor.write_excel(new_data, 'test_data.xlsx')\n \"\"\"",
"test_class": "ExcelProcessorTestWriteExcel",
"test_code": "class ExcelProcessorTestWriteExcel(unittest.TestCase):\n def test_write_excel_1(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada'),\n ('Bob', 35, 'Australia'),\n ('Julia', 28, 'Germany')\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_2(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age'),\n ('John', 25),\n ('Alice', 30),\n ('Bob', 35),\n ('Julia', 28)\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_3(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada'),\n ('Bob', 35, 'Australia')\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_4(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada')\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_5(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA')\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_6(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA')\n ]\n save_file_name = ''\n success = processor.write_excel(new_data, save_file_name)\n self.assertEqual(success, 0)",
"solution_code": "def write_excel(self, data, file_name):\n try:\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(file_name)\n workbook.close()\n return 1\n except:\n return 0",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"openpyxl"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "process_excel_data",
"method_description": "def process_excel_data(self, N, save_file_name):\n \"\"\"\n Change the specified column in the Excel file to uppercase\n :param N: int, The serial number of the column that want to change\n :param save_file_name: str, source file name\n :return:(int, str), The former is the return value of write_excel, while the latter is the saved file name of the processed data\n >>> processor = ExcelProcessor()\n >>> success, output_file = processor.process_excel_data(1, 'test_data.xlsx')\n \"\"\"",
"test_class": "ExcelProcessorTestProcessExcelData",
"test_code": "class ExcelProcessorTestProcessExcelData(unittest.TestCase):\n def test_process_excel_data_1(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 1\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'Age', 'Country', 'AGE'),\n ('John', 25, 'USA', 25),\n ('Alice', 30, 'Canada', 30),\n ('Bob', 35, 'Australia', 35)\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_2(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 0\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'Age', 'Country', 'NAME'),\n ('John', 25, 'USA', 'JOHN'),\n ('Alice', 30, 'Canada', 'ALICE'),\n ('Bob', 35, 'Australia', 'BOB')\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_3(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 2\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'Age', 'Country', 'COUNTRY'),\n ('John', 25, 'USA', 'USA'),\n ('Alice', 30, 'Canada', 'CANADA'),\n ('Bob', 35, 'Australia', 'AUSTRALIA')\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_4(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'COUNTRY'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'CANADA'],\n ['Bob', 35, 'AUSTRALIA']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 2\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'Age', 'COUNTRY', 'COUNTRY'),\n ('John', 25, 'USA', 'USA'),\n ('Alice', 30, 'CANADA', 'CANADA'),\n ('Bob', 35, 'AUSTRALIA', 'AUSTRALIA')\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_5(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'AGE', 'COUNTRY'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'CANADA'],\n ['Bob', 35, 'AUSTRALIA']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 1\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'AGE', 'COUNTRY', 'AGE'),\n ('John', 25, 'USA', 25),\n ('Alice', 30, 'CANADA', 30),\n ('Bob', 35, 'AUSTRALIA', 35)\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_6(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'AGE', 'COUNTRY'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'CANADA'],\n ['Bob', 35, 'AUSTRALIA']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n res = processor.process_excel_data(100, self.test_file_name)\n self.assertEqual(res, 0)",
"solution_code": "def process_excel_data(self, N, save_file_name):\n data = self.read_excel(save_file_name)\n if data is None or N >= len(data[0]):\n return 0\n new_data = []\n for row in data:\n new_row = list(row[:])\n if not str(row[N]).isdigit():\n new_row.append(str(row[N]).upper())\n else:\n new_row.append(row[N])\n new_data.append(new_row)\n new_file_name = save_file_name.split('.')[0] + '_process.xlsx'\n success = self.write_excel(new_data, new_file_name)\n return success, new_file_name",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"read_excel",
"write_excel"
]
}
}
] | ExcelProcessor | [
"ExcelProcessorTestReadExcel",
"ExcelProcessorTestWriteExcel",
"ExcelProcessorTestProcessExcelData",
"ExcelProcessorTest"
] | class ExcelProcessor:
def __init__(self):
pass
| [] |
ClassEval_39 | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def calculate(self, expression):
"""
Calculate the result of the given postfix expression
:param expression: string, the postfix expression to be calculated
:return: float, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.calculate("2 + 3 * 4")
14.0
"""
def prepare(self, expression):
"""
Prepare the infix expression for conversion to postfix notation
:param expression: string, the infix expression to be prepared
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.prepare("2+3*4")
expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']
"""
@staticmethod
def is_operator(c):
"""
Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}
:param c: string, the character to be checked
:return: bool, True if the character is an operator, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.is_operator("+")
True
"""
def compare(self, cur, peek):
"""
Compare the precedence of two operators
:param cur: string, the current operator
:param peek: string, the operator at the top of the operator stack
:return: bool, True if the current operator has higher or equal precedence, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.compare("+", "-")
True
"""
@staticmethod
def _calculate(first_value, second_value, current_op):
"""
Perform the mathematical calculation based on the given operands and operator
:param first_value: string, the first operand
:param second_value: string, the second operand
:param current_op: string, the operator
:return: decimal.Decimal, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator._calculate("2", "3", "+")
5.0
"""
@staticmethod
def transform(expression):
"""
Transform the infix expression to a format suitable for conversion
:param expression: string, the infix expression to be transformed
:return: string, the transformed expression
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.transform("2 + 3 * 4")
"2+3*4"
""" | import unittest
class ExpressionCalculatorTestCalculate(unittest.TestCase):
def setUp(self):
self.expression_calculator = ExpressionCalculator()
def test_calculate_1(self):
result = self.expression_calculator.calculate("2 + 3 * 4")
self.assertEqual(result, 14.0)
def test_calculate_2(self):
result = self.expression_calculator.calculate("2 + 3 + 4")
self.assertEqual(result, 9.0)
def test_calculate_3(self):
result = self.expression_calculator.calculate("2 * 3 * 4")
self.assertEqual(result, 24.0)
def test_calculate_4(self):
result = self.expression_calculator.calculate("2 + 4 / 4")
self.assertEqual(result, 3.0)
def test_calculate_5(self):
result = self.expression_calculator.calculate("(2 + 3) * 4")
self.assertEqual(result, 20.0)
class ExpressionCalculatorTestPrepare(unittest.TestCase):
def setUp(self):
self.expression_calculator = ExpressionCalculator()
def test_prepare_1(self):
self.expression_calculator.prepare("2+3*4")
self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '*', '+']))
def test_prepare_2(self):
self.expression_calculator.prepare("2+3/4")
self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '/', '+']))
def test_prepare_3(self):
self.expression_calculator.prepare("2-3*4")
self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '*', '-']))
def test_prepare_4(self):
self.expression_calculator.prepare("1+3*4")
self.assertEqual(self.expression_calculator.postfix_stack, deque(['1', '3', '4', '*', '+']))
def test_prepare_5(self):
self.expression_calculator.prepare("(2+3)*4")
self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '+', '4', '*']))
def test_prepare_6(self):
self.expression_calculator.prepare("")
self.assertEqual(self.expression_calculator.postfix_stack, deque([]))
class ExpressionCalculatorTestIsOperator(unittest.TestCase):
def setUp(self):
self.expression_calculator = ExpressionCalculator()
def test_is_operator_1(self):
self.assertTrue(self.expression_calculator.is_operator("+"))
def test_is_operator_2(self):
self.assertTrue(self.expression_calculator.is_operator("-"))
def test_is_operator_3(self):
self.assertTrue(self.expression_calculator.is_operator("*"))
def test_is_operator_4(self):
self.assertTrue(self.expression_calculator.is_operator("/"))
def test_is_operator_5(self):
self.assertFalse(self.expression_calculator.is_operator("5"))
class ExpressionCalculatorTestCompare(unittest.TestCase):
def setUp(self):
self.expression_calculator = ExpressionCalculator()
def test_compare_1(self):
result = self.expression_calculator.compare("+", "-")
self.assertTrue(result)
def test_compare_2(self):
result = self.expression_calculator.compare("*", "/")
self.assertTrue(result)
def test_compare_3(self):
result = self.expression_calculator.compare("+", "*")
self.assertTrue(result)
def test_compare_4(self):
result = self.expression_calculator.compare("*", "+")
self.assertFalse(result)
def test_compare_5(self):
result = self.expression_calculator.compare("/", "+")
self.assertFalse(result)
def test_compare_6(self):
result = self.expression_calculator.compare("%", "+")
self.assertFalse(result)
def test_compare_7(self):
result = self.expression_calculator.compare("+", "%")
self.assertTrue(result)
class ExpressionCalculatorTestCalculateMethod(unittest.TestCase):
def setUp(self):
self.expression_calculator = ExpressionCalculator()
def test_calculate_method_1(self):
result = self.expression_calculator._calculate("2", "3", "+")
self.assertEqual(result, Decimal(5.0))
def test_calculate_method_2(self):
result = self.expression_calculator._calculate("3", "2", "-")
self.assertEqual(result, Decimal(1.0))
def test_calculate_method_3(self):
result = self.expression_calculator._calculate("2", "3", "*")
self.assertEqual(result, Decimal(6.0))
def test_calculate_method_4(self):
result = self.expression_calculator._calculate("3", "3", "/")
self.assertEqual(result, Decimal(1.0))
def test_calculate_method_5(self):
result = self.expression_calculator._calculate("6", "2", "/")
self.assertEqual(result, Decimal(3.0))
def test_calculate_method_6(self):
result = self.expression_calculator._calculate("6", "2", "%")
self.assertEqual(result, Decimal(0.0))
def test_calculate_method_7(self):
try:
self.expression_calculator._calculate("6", "2", "??")
except:
pass
class ExpressionCalculatorTestTransform(unittest.TestCase):
def setUp(self):
self.expression_calculator = ExpressionCalculator()
def test_transform_1(self):
result = self.expression_calculator.transform("2 + 3 * 4")
self.assertEqual(result, "2+3*4")
def test_transform_2(self):
result = self.expression_calculator.transform("2 + 3 / 4")
self.assertEqual(result, "2+3/4")
def test_transform_3(self):
result = self.expression_calculator.transform("2 - 3 * 4")
self.assertEqual(result, "2-3*4")
def test_transform_4(self):
result = self.expression_calculator.transform("1 + 3 * 4")
self.assertEqual(result, "1+3*4")
def test_transform_5(self):
result = self.expression_calculator.transform("-2 + (-3) * 4")
self.assertEqual(result, "~2+(~3)*4")
def test_transform_6(self):
result = self.expression_calculator.transform("~(1 + 1)")
self.assertEqual(result, "0-(1+1)")
class ExpressionCalculatorTest(unittest.TestCase):
def setUp(self):
self.expression_calculator = ExpressionCalculator()
def test_ExpressionCalculator(self):
result = self.expression_calculator.calculate("2 + 3 * 4")
self.assertEqual(result, 14.0)
self.expression_calculator.prepare("2+3*4")
self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '*', '+']))
self.assertTrue(self.expression_calculator.is_operator("+"))
result = self.expression_calculator.compare("+", "-")
self.assertTrue(result)
result = self.expression_calculator._calculate("2", "3", "+")
self.assertEqual(result, Decimal(5.0))
result = self.expression_calculator.transform("2 + 3 * 4")
self.assertEqual(result, "2+3*4") | import re
from collections import deque
from decimal import Decimal
class ExpressionCalculator:
def __init__(self):
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def calculate(self, expression):
self.prepare(self.transform(expression))
result_stack = deque()
self.postfix_stack.reverse()
while self.postfix_stack:
current_op = self.postfix_stack.pop()
if not self.is_operator(current_op):
current_op = current_op.replace("~", "-")
result_stack.append(current_op)
else:
second_value = result_stack.pop()
first_value = result_stack.pop()
first_value = first_value.replace("~", "-")
second_value = second_value.replace("~", "-")
temp_result = self._calculate(first_value, second_value, current_op)
result_stack.append(str(temp_result))
return float(eval("*".join(result_stack)))
def prepare(self, expression):
op_stack = deque([','])
arr = list(expression)
current_index = 0
count = 0
for i, current_op in enumerate(arr):
if self.is_operator(current_op):
if count > 0:
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
peek_op = op_stack[-1]
if current_op == ')':
while op_stack[-1] != '(':
self.postfix_stack.append(str(op_stack.pop()))
op_stack.pop()
else:
while current_op != '(' and peek_op != ',' and self.compare(current_op, peek_op):
self.postfix_stack.append(str(op_stack.pop()))
peek_op = op_stack[-1]
op_stack.append(current_op)
count = 0
current_index = i + 1
else:
count += 1
if count > 1 or (count == 1 and not self.is_operator(arr[current_index])):
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
while op_stack[-1] != ',':
self.postfix_stack.append(str(op_stack.pop()))
@staticmethod
def is_operator(c):
return c in {'+', '-', '*', '/', '(', ')', '%'}
def compare(self, cur, peek):
if cur == '%':
cur = '/'
if peek == '%':
peek = '/'
return self.operat_priority[ord(peek) - 40] >= self.operat_priority[ord(cur) - 40]
@staticmethod
def _calculate(first_value, second_value, current_op):
if current_op == '+':
return Decimal(first_value) + Decimal(second_value)
elif current_op == '-':
return Decimal(first_value) - Decimal(second_value)
elif current_op == '*':
return Decimal(first_value) * Decimal(second_value)
elif current_op == '/':
return Decimal(first_value) / Decimal(second_value)
elif current_op == '%':
return Decimal(first_value) % Decimal(second_value)
else:
raise ValueError("Unexpected operator: {}".format(current_op))
@staticmethod
def transform(expression):
expression = re.sub(r"\s+", "", expression)
expression = re.sub(r"=$", "", expression)
arr = list(expression)
for i, c in enumerate(arr):
if c == '-':
if i == 0:
arr[i] = '~'
else:
prev_c = arr[i - 1]
if prev_c in {'+', '-', '*', '/', '(', 'E', 'e'}:
arr[i] = '~'
if arr[0] == '~' and (len(arr) > 1 and arr[1] == '('):
arr[0] = '-'
return "0" + "".join(arr)
else:
return "".join(arr) | [
"import re",
"from collections import deque",
"from decimal import Decimal"
] | """
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
| [
{
"method_name": "calculate",
"method_description": "def calculate(self, expression):\n \"\"\"\n Calculate the result of the given postfix expression\n :param expression: string, the postfix expression to be calculated\n :return: float, the calculated result\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.calculate(\"2 + 3 * 4\")\n 14.0\n\n \"\"\"",
"test_class": "ExpressionCalculatorTestCalculate",
"test_code": "class ExpressionCalculatorTestCalculate(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_calculate_1(self):\n result = self.expression_calculator.calculate(\"2 + 3 * 4\")\n self.assertEqual(result, 14.0)\n\n def test_calculate_2(self):\n result = self.expression_calculator.calculate(\"2 + 3 + 4\")\n self.assertEqual(result, 9.0)\n\n def test_calculate_3(self):\n result = self.expression_calculator.calculate(\"2 * 3 * 4\")\n self.assertEqual(result, 24.0)\n\n def test_calculate_4(self):\n result = self.expression_calculator.calculate(\"2 + 4 / 4\")\n self.assertEqual(result, 3.0)\n\n def test_calculate_5(self):\n result = self.expression_calculator.calculate(\"(2 + 3) * 4\")\n self.assertEqual(result, 20.0)",
"solution_code": "def calculate(self, expression):\n self.prepare(self.transform(expression))\n\n result_stack = deque()\n self.postfix_stack.reverse()\n\n while self.postfix_stack:\n current_op = self.postfix_stack.pop()\n if not self.is_operator(current_op):\n current_op = current_op.replace(\"~\", \"-\")\n result_stack.append(current_op)\n else:\n second_value = result_stack.pop()\n first_value = result_stack.pop()\n\n first_value = first_value.replace(\"~\", \"-\")\n second_value = second_value.replace(\"~\", \"-\")\n\n temp_result = self._calculate(first_value, second_value, current_op)\n result_stack.append(str(temp_result))\n\n return float(eval(\"*\".join(result_stack)))",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"re",
"deque"
],
"field_dependencies": [
"self.postfix_stack"
],
"method_dependencies": [
"prepare",
"is_operator",
"_calculate",
"transform"
]
}
},
{
"method_name": "prepare",
"method_description": "def prepare(self, expression):\n \"\"\"\n Prepare the infix expression for conversion to postfix notation\n :param expression: string, the infix expression to be prepared\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.prepare(\"2+3*4\")\n\n expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']\n \"\"\"",
"test_class": "ExpressionCalculatorTestPrepare",
"test_code": "class ExpressionCalculatorTestPrepare(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_prepare_1(self):\n self.expression_calculator.prepare(\"2+3*4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '*', '+']))\n\n def test_prepare_2(self):\n self.expression_calculator.prepare(\"2+3/4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '/', '+']))\n\n def test_prepare_3(self):\n self.expression_calculator.prepare(\"2-3*4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '*', '-']))\n\n def test_prepare_4(self):\n self.expression_calculator.prepare(\"1+3*4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['1', '3', '4', '*', '+']))\n\n def test_prepare_5(self):\n self.expression_calculator.prepare(\"(2+3)*4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '+', '4', '*']))\n\n def test_prepare_6(self):\n self.expression_calculator.prepare(\"\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque([]))",
"solution_code": "def prepare(self, expression):\n op_stack = deque([','])\n arr = list(expression)\n current_index = 0\n count = 0\n\n for i, current_op in enumerate(arr):\n if self.is_operator(current_op):\n if count > 0:\n self.postfix_stack.append(\"\".join(arr[current_index: current_index + count]))\n peek_op = op_stack[-1]\n if current_op == ')':\n while op_stack[-1] != '(':\n self.postfix_stack.append(str(op_stack.pop()))\n op_stack.pop()\n else:\n while current_op != '(' and peek_op != ',' and self.compare(current_op, peek_op):\n self.postfix_stack.append(str(op_stack.pop()))\n peek_op = op_stack[-1]\n op_stack.append(current_op)\n\n count = 0\n current_index = i + 1\n else:\n count += 1\n\n if count > 1 or (count == 1 and not self.is_operator(arr[current_index])):\n self.postfix_stack.append(\"\".join(arr[current_index: current_index + count]))\n\n while op_stack[-1] != ',':\n self.postfix_stack.append(str(op_stack.pop()))",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"re",
"deque"
],
"field_dependencies": [
"self.postfix_stack"
],
"method_dependencies": [
"is_operator",
"compare"
]
}
},
{
"method_name": "is_operator",
"method_description": "@staticmethod\n def is_operator(c):\n \"\"\"\n Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}\n :param c: string, the character to be checked\n :return: bool, True if the character is an operator, False otherwise\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.is_operator(\"+\")\n True\n\n \"\"\"",
"test_class": "ExpressionCalculatorTestIsOperator",
"test_code": "class ExpressionCalculatorTestIsOperator(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_is_operator_1(self):\n self.assertTrue(self.expression_calculator.is_operator(\"+\"))\n\n def test_is_operator_2(self):\n self.assertTrue(self.expression_calculator.is_operator(\"-\"))\n\n def test_is_operator_3(self):\n self.assertTrue(self.expression_calculator.is_operator(\"*\"))\n\n def test_is_operator_4(self):\n self.assertTrue(self.expression_calculator.is_operator(\"/\"))\n\n def test_is_operator_5(self):\n self.assertFalse(self.expression_calculator.is_operator(\"5\"))",
"solution_code": "@staticmethod\n def is_operator(c):\n return c in {'+', '-', '*', '/', '(', ')', '%'}",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "compare",
"method_description": "def compare(self, cur, peek):\n \"\"\"\n Compare the precedence of two operators\n :param cur: string, the current operator\n :param peek: string, the operator at the top of the operator stack\n :return: bool, True if the current operator has higher or equal precedence, False otherwise\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.compare(\"+\", \"-\")\n True\n\n \"\"\"",
"test_class": "ExpressionCalculatorTestCompare",
"test_code": "class ExpressionCalculatorTestCompare(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_compare_1(self):\n result = self.expression_calculator.compare(\"+\", \"-\")\n self.assertTrue(result)\n\n def test_compare_2(self):\n result = self.expression_calculator.compare(\"*\", \"/\")\n self.assertTrue(result)\n\n def test_compare_3(self):\n result = self.expression_calculator.compare(\"+\", \"*\")\n self.assertTrue(result)\n\n def test_compare_4(self):\n result = self.expression_calculator.compare(\"*\", \"+\")\n self.assertFalse(result)\n\n def test_compare_5(self):\n result = self.expression_calculator.compare(\"/\", \"+\")\n self.assertFalse(result)\n\n def test_compare_6(self):\n result = self.expression_calculator.compare(\"%\", \"+\")\n self.assertFalse(result)\n\n def test_compare_7(self):\n result = self.expression_calculator.compare(\"+\", \"%\")\n self.assertTrue(result)",
"solution_code": "def compare(self, cur, peek):\n if cur == '%':\n cur = '/'\n if peek == '%':\n peek = '/'\n return self.operat_priority[ord(peek) - 40] >= self.operat_priority[ord(cur) - 40]",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.operat_priority"
],
"method_dependencies": []
}
},
{
"method_name": "_calculate",
"method_description": "@staticmethod\n def _calculate(first_value, second_value, current_op):\n \"\"\"\n Perform the mathematical calculation based on the given operands and operator\n :param first_value: string, the first operand\n :param second_value: string, the second operand\n :param current_op: string, the operator\n :return: decimal.Decimal, the calculated result\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator._calculate(\"2\", \"3\", \"+\")\n 5.0\n\n \"\"\"",
"test_class": "ExpressionCalculatorTestCalculateMethod",
"test_code": "class ExpressionCalculatorTestCalculateMethod(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_calculate_method_1(self):\n result = self.expression_calculator._calculate(\"2\", \"3\", \"+\")\n self.assertEqual(result, Decimal(5.0))\n\n def test_calculate_method_2(self):\n result = self.expression_calculator._calculate(\"3\", \"2\", \"-\")\n self.assertEqual(result, Decimal(1.0))\n\n def test_calculate_method_3(self):\n result = self.expression_calculator._calculate(\"2\", \"3\", \"*\")\n self.assertEqual(result, Decimal(6.0))\n\n def test_calculate_method_4(self):\n result = self.expression_calculator._calculate(\"3\", \"3\", \"/\")\n self.assertEqual(result, Decimal(1.0))\n\n def test_calculate_method_5(self):\n result = self.expression_calculator._calculate(\"6\", \"2\", \"/\")\n self.assertEqual(result, Decimal(3.0))\n\n def test_calculate_method_6(self):\n result = self.expression_calculator._calculate(\"6\", \"2\", \"%\")\n self.assertEqual(result, Decimal(0.0))\n\n def test_calculate_method_7(self):\n try:\n self.expression_calculator._calculate(\"6\", \"2\", \"??\")\n except:\n pass",
"solution_code": "@staticmethod\n def _calculate(first_value, second_value, current_op):\n if current_op == '+':\n return Decimal(first_value) + Decimal(second_value)\n elif current_op == '-':\n return Decimal(first_value) - Decimal(second_value)\n elif current_op == '*':\n return Decimal(first_value) * Decimal(second_value)\n elif current_op == '/':\n return Decimal(first_value) / Decimal(second_value)\n elif current_op == '%':\n return Decimal(first_value) % Decimal(second_value)\n else:\n raise ValueError(\"Unexpected operator: {}\".format(current_op))",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"Decimal"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "transform",
"method_description": "@staticmethod\n def transform(expression):\n \"\"\"\n Transform the infix expression to a format suitable for conversion\n :param expression: string, the infix expression to be transformed\n :return: string, the transformed expression\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.transform(\"2 + 3 * 4\")\n \"2+3*4\"\n\n \"\"\"",
"test_class": "ExpressionCalculatorTestTransform",
"test_code": "class ExpressionCalculatorTestTransform(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_transform_1(self):\n result = self.expression_calculator.transform(\"2 + 3 * 4\")\n self.assertEqual(result, \"2+3*4\")\n\n def test_transform_2(self):\n result = self.expression_calculator.transform(\"2 + 3 / 4\")\n self.assertEqual(result, \"2+3/4\")\n\n def test_transform_3(self):\n result = self.expression_calculator.transform(\"2 - 3 * 4\")\n self.assertEqual(result, \"2-3*4\")\n\n def test_transform_4(self):\n result = self.expression_calculator.transform(\"1 + 3 * 4\")\n self.assertEqual(result, \"1+3*4\")\n\n def test_transform_5(self):\n result = self.expression_calculator.transform(\"-2 + (-3) * 4\")\n self.assertEqual(result, \"~2+(~3)*4\")\n\n def test_transform_6(self):\n result = self.expression_calculator.transform(\"~(1 + 1)\")\n self.assertEqual(result, \"0-(1+1)\")",
"solution_code": "@staticmethod\n def transform(expression):\n expression = re.sub(r\"\\s+\", \"\", expression)\n expression = re.sub(r\"=$\", \"\", expression)\n arr = list(expression)\n\n for i, c in enumerate(arr):\n if c == '-':\n if i == 0:\n arr[i] = '~'\n else:\n prev_c = arr[i - 1]\n if prev_c in {'+', '-', '*', '/', '(', 'E', 'e'}:\n arr[i] = '~'\n\n if arr[0] == '~' and (len(arr) > 1 and arr[1] == '('):\n arr[0] = '-'\n return \"0\" + \"\".join(arr)\n else:\n return \"\".join(arr)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"re"
],
"field_dependencies": [],
"method_dependencies": []
}
}
] | ExpressionCalculator | [
"ExpressionCalculatorTestCalculate",
"ExpressionCalculatorTestPrepare",
"ExpressionCalculatorTestIsOperator",
"ExpressionCalculatorTestCompare",
"ExpressionCalculatorTestCalculateMethod",
"ExpressionCalculatorTestTransform",
"ExpressionCalculatorTest"
] | class ExpressionCalculator:
def __init__(self):
"""
Initialize the expression calculator
"""
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
| [
"self.operat_priority",
"self.postfix_stack"
] |
ClassEval_40 | class FitnessTracker:
"""
This is a class as fitness tracker that implements to calculate BMI (Body Mass Index) and calorie intake based on the user's height, weight, age, and sex.
"""
def __init__(self, height, weight, age, sex) -> None:
"""
Initialize the class with height, weight, age, and sex, and calculate the BMI standard based on sex, and male is 20-25, female is 19-24.
"""
self.height = height
self.weight = weight
self.age = age
self.sex = sex
self.BMI_std = [
{"male": [20, 25]},
{"female": [19, 24]}
]
def get_BMI(self):
"""
Calculate the BMI based on the height and weight.
:return: BMI,which is the weight divide by the square of height, float.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.get_BMI()
21.604938271604937
"""
def condition_judge(self):
"""
Judge the condition of the user based on the BMI standard.
:return: 1 if the user is too fat, -1 if the user is too thin, 0 if the user is normal, int.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.condition_judge()
-1
"""
def calculate_calorie_intake(self):
"""
Calculate the calorie intake based on the user's condition and BMR (Basal Metabolic Rate),BMR is calculated based on the user's height, weight, age, and sex,male is10 * self.weight + 6.25 * self.height - 5 * self.age + 5,female is 10 * self.weight + 6.25 * self.height - 5 * self.age - 161, and the calorie intake is calculated based on the BMR and the user's condition,if the user is too fat, the calorie intake is BMR * 1.2, if the user is too thin, the calorie intake is BMR * 1.6, if the user is normal, the calorie intake is BMR * 1.4.
:return: calorie intake, float.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.calculate_calorie_intake()
986.0
""" | import unittest
class FitnessTrackerTestGetBMI(unittest.TestCase):
def test_get_BMI(self):
fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
self.assertEqual(fitnessTracker.get_BMI(), 21.604938271604937)
def test_get_BMI_2(self):
fitnessTracker = FitnessTracker(1.8, 50, 20, "male")
self.assertEqual(fitnessTracker.get_BMI(), 15.432098765432098)
def test_get_BMI_3(self):
fitnessTracker = FitnessTracker(1.72, 53, 20, "male")
self.assertEqual(fitnessTracker.get_BMI(), 17.915089237425637)
def test_get_BMI_4(self):
fitnessTracker = FitnessTracker(1.72, 60, 20, "male")
self.assertEqual(fitnessTracker.get_BMI(), 20.281233098972418)
def test_get_BMI_5(self):
fitnessTracker = FitnessTracker(1.72, 65, 20, "male")
self.assertEqual(fitnessTracker.get_BMI(), 21.971335857220122)
class FitnessTrackerTestConditionJudge(unittest.TestCase):
def test_condition_judge(self):
fitnessTracker = FitnessTracker(1.8, 45, 20, "female")
self.assertEqual(fitnessTracker.condition_judge(), -1)
def test_condition_judge_2(self):
fitnessTracker = FitnessTracker(1.72, 80, 22, "female")
self.assertEqual(fitnessTracker.condition_judge(), 1)
def test_condition_judge_3(self):
fitnessTracker = FitnessTracker(1.72, 53, 22, "male")
self.assertEqual(fitnessTracker.condition_judge(), -1)
def test_condition_judge_4(self):
fitnessTracker = FitnessTracker(1.72, 60, 22, "male")
self.assertEqual(fitnessTracker.condition_judge(), 0)
def test_condition_judge_5(self):
fitnessTracker = FitnessTracker(1.72, 75, 22, "male")
self.assertEqual(fitnessTracker.condition_judge(), 1)
class FitnessTrackerTestCaculateCalorieIntake(unittest.TestCase):
def test_calculate_calorie_intake(self):
fitnessTracker = FitnessTracker(1.8, 70, 20, "female")
self.assertEqual(fitnessTracker.calculate_calorie_intake(), 630.3499999999999)
def test_calculate_calorie_intake_2(self):
fitnessTracker = FitnessTracker(1.72, 80, 22, "female")
self.assertEqual(fitnessTracker.calculate_calorie_intake(), 647.6999999999999)
def test_calculate_calorie_intake_3(self):
fitnessTracker = FitnessTracker(1.72, 53, 22, "male")
self.assertEqual(fitnessTracker.calculate_calorie_intake(), 697.2)
def test_calculate_calorie_intake_4(self):
fitnessTracker = FitnessTracker(1.72, 60, 22, "male")
self.assertEqual(fitnessTracker.calculate_calorie_intake(), 708.05)
def test_calculate_calorie_intake_5(self):
fitnessTracker = FitnessTracker(1.72, 75, 22, "male")
self.assertEqual(fitnessTracker.calculate_calorie_intake(), 786.9)
class FitnessTrackerTestMain(unittest.TestCase):
def test_main(self):
fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
self.assertEqual(fitnessTracker.get_BMI(), 21.604938271604937)
self.assertEqual(fitnessTracker.condition_judge(), 0)
self.assertEqual(fitnessTracker.calculate_calorie_intake(), 862.75) | class FitnessTracker:
def __init__(self, height, weight, age, sex) -> None:
self.height = height
self.weight = weight
self.age = age
self.sex = sex
self.BMI_std = [
{"male": [20, 25]},
{"female": [19, 24]}
]
def get_BMI(self):
return self.weight / self.height ** 2
def condition_judge(self):
BMI = self.get_BMI()
if self.sex == "male":
BMI_range = self.BMI_std[0]["male"]
else:
BMI_range = self.BMI_std[1]["female"]
if BMI > BMI_range[1]:
# too fat
return 1
elif BMI < BMI_range[0]:
# too thin
return -1
else:
# normal
return 0
def calculate_calorie_intake(self):
if self.sex == "male":
BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age + 5
else:
BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age - 161
if self.condition_judge() == 1:
calorie_intake = BMR * 1.2 # Sedentary lifestyle
elif self.condition_judge() == -1:
calorie_intake = BMR * 1.6 # Active lifestyle
else:
calorie_intake = BMR * 1.4 # Moderate lifestyle
return calorie_intake | [] | """
This is a class as fitness tracker that implements to calculate BMI (Body Mass Index) and calorie intake based on the user's height, weight, age, and sex.
"""
| [
{
"method_name": "get_BMI",
"method_description": "def get_BMI(self):\n \"\"\"\n Calculate the BMI based on the height and weight.\n :return: BMI,which is the weight divide by the square of height, float.\n >>> fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n >>> fitnessTracker.get_BMI()\n 21.604938271604937\n\n \"\"\"",
"test_class": "FitnessTrackerTestGetBMI",
"test_code": "class FitnessTrackerTestGetBMI(unittest.TestCase):\n def test_get_BMI(self):\n fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 21.604938271604937)\n\n def test_get_BMI_2(self):\n fitnessTracker = FitnessTracker(1.8, 50, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 15.432098765432098)\n\n def test_get_BMI_3(self):\n fitnessTracker = FitnessTracker(1.72, 53, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 17.915089237425637)\n\n def test_get_BMI_4(self):\n fitnessTracker = FitnessTracker(1.72, 60, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 20.281233098972418)\n\n def test_get_BMI_5(self):\n fitnessTracker = FitnessTracker(1.72, 65, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 21.971335857220122)",
"solution_code": "def get_BMI(self):\n return self.weight / self.height ** 2",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.height",
"self.weight"
],
"method_dependencies": []
}
},
{
"method_name": "condition_judge",
"method_description": "def condition_judge(self):\n \"\"\"\n Judge the condition of the user based on the BMI standard.\n :return: 1 if the user is too fat, -1 if the user is too thin, 0 if the user is normal, int.\n >>> fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n >>> fitnessTracker.condition_judge()\n -1\n\n \"\"\"",
"test_class": "FitnessTrackerTestConditionJudge",
"test_code": "class FitnessTrackerTestConditionJudge(unittest.TestCase):\n def test_condition_judge(self):\n fitnessTracker = FitnessTracker(1.8, 45, 20, \"female\")\n self.assertEqual(fitnessTracker.condition_judge(), -1)\n\n def test_condition_judge_2(self):\n fitnessTracker = FitnessTracker(1.72, 80, 22, \"female\")\n self.assertEqual(fitnessTracker.condition_judge(), 1)\n\n def test_condition_judge_3(self):\n fitnessTracker = FitnessTracker(1.72, 53, 22, \"male\")\n self.assertEqual(fitnessTracker.condition_judge(), -1)\n\n def test_condition_judge_4(self):\n fitnessTracker = FitnessTracker(1.72, 60, 22, \"male\")\n self.assertEqual(fitnessTracker.condition_judge(), 0)\n\n def test_condition_judge_5(self):\n fitnessTracker = FitnessTracker(1.72, 75, 22, \"male\")\n self.assertEqual(fitnessTracker.condition_judge(), 1)",
"solution_code": "def condition_judge(self):\n BMI = self.get_BMI()\n if self.sex == \"male\":\n BMI_range = self.BMI_std[0][\"male\"]\n else:\n BMI_range = self.BMI_std[1][\"female\"]\n if BMI > BMI_range[1]:\n # too fat\n return 1\n elif BMI < BMI_range[0]:\n # too thin\n return -1\n else:\n # normal\n return 0",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.BMI_std",
"self.sex"
],
"method_dependencies": [
"get_BMI"
]
}
},
{
"method_name": "calculate_calorie_intake",
"method_description": "def calculate_calorie_intake(self):\n \"\"\"\n Calculate the calorie intake based on the user's condition and BMR (Basal Metabolic Rate),BMR is calculated based on the user's height, weight, age, and sex,male is10 * self.weight + 6.25 * self.height - 5 * self.age + 5,female is 10 * self.weight + 6.25 * self.height - 5 * self.age - 161, and the calorie intake is calculated based on the BMR and the user's condition,if the user is too fat, the calorie intake is BMR * 1.2, if the user is too thin, the calorie intake is BMR * 1.6, if the user is normal, the calorie intake is BMR * 1.4.\n :return: calorie intake, float.\n >>> fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n >>> fitnessTracker.calculate_calorie_intake()\n 986.0\n\n \"\"\"",
"test_class": "FitnessTrackerTestCaculateCalorieIntake",
"test_code": "class FitnessTrackerTestCaculateCalorieIntake(unittest.TestCase):\n def test_calculate_calorie_intake(self):\n fitnessTracker = FitnessTracker(1.8, 70, 20, \"female\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 630.3499999999999)\n\n def test_calculate_calorie_intake_2(self):\n fitnessTracker = FitnessTracker(1.72, 80, 22, \"female\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 647.6999999999999)\n\n def test_calculate_calorie_intake_3(self):\n fitnessTracker = FitnessTracker(1.72, 53, 22, \"male\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 697.2)\n\n def test_calculate_calorie_intake_4(self):\n fitnessTracker = FitnessTracker(1.72, 60, 22, \"male\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 708.05)\n\n def test_calculate_calorie_intake_5(self):\n fitnessTracker = FitnessTracker(1.72, 75, 22, \"male\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 786.9)",
"solution_code": "def calculate_calorie_intake(self):\n if self.sex == \"male\":\n BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age + 5\n else:\n BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age - 161\n if self.condition_judge() == 1:\n calorie_intake = BMR * 1.2 # Sedentary lifestyle\n elif self.condition_judge() == -1:\n calorie_intake = BMR * 1.6 # Active lifestyle\n else:\n calorie_intake = BMR * 1.4 # Moderate lifestyle\n return calorie_intake",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.age",
"self.height",
"self.sex",
"self.weight"
],
"method_dependencies": [
"condition_judge"
]
}
}
] | FitnessTracker | [
"FitnessTrackerTestGetBMI",
"FitnessTrackerTestConditionJudge",
"FitnessTrackerTestCaculateCalorieIntake",
"FitnessTrackerTestMain"
] | class FitnessTracker:
def __init__(self, height, weight, age, sex) -> None:
"""
Initialize the class with height, weight, age, and sex, and calculate the BMI standard based on sex, and male is 20-25, female is 19-24.
"""
self.height = height
self.weight = weight
self.age = age
self.sex = sex
self.BMI_std = [
{"male": [20, 25]},
{"female": [19, 24]}
]
| [
"self.BMI_std",
"self.age",
"self.height",
"self.sex",
"self.weight"
] |
ClassEval_41 | class GomokuGame:
"""
This class is an implementation of a Gomoku game, supporting for making moves, checking for a winner, and checking if there are five consecutive symbols on the game board.
"""
def __init__(self, board_size):
"""
Initializes the game with a given board size.
It initializes the board with empty spaces and sets the current player symble as 'X'.
"""
self.board_size = board_size
self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)]
self.current_player = 'X'
def make_move(self, row, col):
"""
Makes a move at the given row and column.
If the move is valid, it places the current player's symbol on the board
and changes the current player to the other player (if the current player is 'X', then it becomes 'O' and vice versa).
:param row: int, the row index of this move
:param col: int, the column index
return: True if the move is valid, or False otherwise.
>>> gomokuGame = GomokuGame(10)
>>> gomokuGame.make_move(5, 5)
True
>>> gomokuGame.make_move(5, 5)
False
"""
def check_winner(self):
"""
Checks if there is a winner by looking for five in a row in all directions (horizontal, vertical, diagonal).
return: the symbol of the winning player (either 'X' or 'O') if there is a winner, or None otherwise.
>>> gomokuGame = GomokuGame(10)
>>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
>>> for move in moves:
... gomokuGame.make_move(move[0], move[1])
>>> gomokuGame.check_winner()
'X'
"""
def _check_five_in_a_row(self, row, col, direction):
"""
checks if there are five consecutive symbols of the same player in a row starting from a given cell in a given direction (horizontal, vertical, diagonal).
Counts the number of consecutive symbols in that direction starting from the given cell,
:param row: int, row of the given cell
:param col: int, column of the given cell
:param direction: tuple, (int, int), named as (dx, dy). Row and col will plus several dx and dy repectively.
:return: True if there are five consecutive symbols of the same player, and False otherwise.
>>> gomokuGame = GomokuGame(10)
>>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
>>> for move in moves:
... gomokuGame.make_move(move[0], move[1])
>>> gomokuGame._check_five_in_a_row(5, 1, (0, 1))
True
>>> gomokuGame._check_five_in_a_row(5, 1, (1, 1))
False
""" | import unittest
class GomokuGameTestMakeMove(unittest.TestCase):
def setUp(self) -> None:
self.board_size = 10
self.gomokuGame = GomokuGame(self.board_size)
def test_make_move_1(self):
board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]
self.assertEqual(True, self.gomokuGame.make_move(0, 0))
board[0][0] = 'X'
self.assertEqual(board, self.gomokuGame.board)
# same position
def test_make_move_2(self):
board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]
self.assertEqual(True, self.gomokuGame.make_move(0, 0))
self.assertEqual(False, self.gomokuGame.make_move(0, 0))
board[0][0] = 'X'
self.assertEqual(board, self.gomokuGame.board)
def test_make_move_3(self):
board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]
self.assertEqual(True, self.gomokuGame.make_move(0, 0))
self.assertEqual(True, self.gomokuGame.make_move(0, 1))
board[0][0] = 'X'
board[0][1] = 'O'
self.assertEqual(board, self.gomokuGame.board)
def test_make_move_4(self):
board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]
self.assertEqual(True, self.gomokuGame.make_move(0, 0))
self.assertEqual(True, self.gomokuGame.make_move(0, 1))
self.assertEqual(False, self.gomokuGame.make_move(0, 0))
board[0][0] = 'X'
board[0][1] = 'O'
self.assertEqual(board, self.gomokuGame.board)
def test_make_move_5(self):
board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]
self.assertEqual(True, self.gomokuGame.make_move(0, 0))
self.assertEqual(True, self.gomokuGame.make_move(0, 1))
self.assertEqual(False, self.gomokuGame.make_move(0, 1))
board[0][0] = 'X'
board[0][1] = 'O'
self.assertEqual(board, self.gomokuGame.board)
class GomokuGameTestCheckWinner(unittest.TestCase):
def test_check_winner_1(self):
gomokuGame = GomokuGame(10)
self.assertEqual(None, gomokuGame.check_winner())
def test_check_winner_2(self):
gomokuGame = GomokuGame(10)
moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
for move in moves:
gomokuGame.make_move(move[0], move[1])
self.assertEqual('X', gomokuGame.check_winner())
def test_check_winner_3(self):
gomokuGame = GomokuGame(10)
moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 0), (0, 4)]
for move in moves:
gomokuGame.make_move(move[0], move[1])
self.assertEqual('O', gomokuGame.check_winner())
def test_check_winner_4(self):
gomokuGame = GomokuGame(10)
moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1), (0, 4)]
for move in moves:
gomokuGame.make_move(move[0], move[1])
self.assertEqual(gomokuGame.check_winner(), 'O')
def test_check_winner_5(self):
gomokuGame = GomokuGame(10)
moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1), (0, 4), (5, 0)]
for move in moves:
gomokuGame.make_move(move[0], move[1])
self.assertEqual('O', gomokuGame.check_winner())
class GomokuGameTestCheckFiveInARow(unittest.TestCase):
def setUp(self) -> None:
self.gomokuGame = GomokuGame(10)
moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
for move in moves:
self.gomokuGame.make_move(move[0], move[1])
def test_check_five_in_a_row_1(self):
self.assertEqual(True, self.gomokuGame._check_five_in_a_row(5, 5, (0, -1)))
def test_check_five_in_a_row_2(self):
self.assertEqual(True, self.gomokuGame._check_five_in_a_row(5, 1, (0, 1)))
def test_check_five_in_a_row_3(self):
self.assertEqual(False, self.gomokuGame._check_five_in_a_row(0, 0, (0, 1)))
def test_check_five_in_a_row_4(self):
self.assertEqual(False, self.gomokuGame._check_five_in_a_row(0, 0, (1, 0)))
def test_check_five_in_a_row_5(self):
self.assertEqual(False, self.gomokuGame._check_five_in_a_row(5, 5, (1, 0)))
class GomokuGameTestMain(unittest.TestCase):
def test_main(self):
gomokuGame = GomokuGame(10)
moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
self.assertEqual(None, gomokuGame.check_winner())
for move in moves:
self.assertEqual(True, gomokuGame.make_move(move[0], move[1]))
self.assertEqual(False, gomokuGame.make_move(0, 0))
self.assertEqual(True, gomokuGame._check_five_in_a_row(5, 5, (0, -1)))
self.assertEqual('X', gomokuGame.check_winner()) | class GomokuGame:
def __init__(self, board_size):
self.board_size = board_size
self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)]
self.current_player = 'X'
def make_move(self, row, col):
if self.board[row][col] == ' ':
self.board[row][col] = self.current_player
self.current_player = 'O' if self.current_player == 'X' else 'X'
return True
return False
def check_winner(self):
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
for row in range(self.board_size):
for col in range(self.board_size):
if self.board[row][col] != ' ':
for direction in directions:
if self._check_five_in_a_row(row, col, direction):
return self.board[row][col]
return None
def _check_five_in_a_row(self, row, col, direction):
dx, dy = direction
count = 1
symbol = self.board[row][col]
for i in range(1, 5):
new_row = row + dx * i
new_col = col + dy * i
if not (0 <= new_row < self.board_size and 0 <= new_col < self.board_size):
return False
if self.board[new_row][new_col] != symbol:
return False
count += 1
return count == 5 | [] | """
This class is an implementation of a Gomoku game, supporting for making moves, checking for a winner, and checking if there are five consecutive symbols on the game board.
"""
| [
{
"method_name": "make_move",
"method_description": "def make_move(self, row, col):\n \"\"\"\n Makes a move at the given row and column.\n If the move is valid, it places the current player's symbol on the board\n and changes the current player to the other player (if the current player is 'X', then it becomes 'O' and vice versa).\n :param row: int, the row index of this move\n :param col: int, the column index\n return: True if the move is valid, or False otherwise.\n >>> gomokuGame = GomokuGame(10)\n >>> gomokuGame.make_move(5, 5)\n True\n >>> gomokuGame.make_move(5, 5)\n False\n \"\"\"",
"test_class": "GomokuGameTestMakeMove",
"test_code": "class GomokuGameTestMakeMove(unittest.TestCase):\n def setUp(self) -> None:\n self.board_size = 10\n self.gomokuGame = GomokuGame(self.board_size)\n\n def test_make_move_1(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n board[0][0] = 'X'\n self.assertEqual(board, self.gomokuGame.board)\n\n # same position\n def test_make_move_2(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n self.assertEqual(False, self.gomokuGame.make_move(0, 0))\n board[0][0] = 'X'\n self.assertEqual(board, self.gomokuGame.board)\n\n def test_make_move_3(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n self.assertEqual(True, self.gomokuGame.make_move(0, 1))\n board[0][0] = 'X'\n board[0][1] = 'O'\n self.assertEqual(board, self.gomokuGame.board)\n\n def test_make_move_4(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n self.assertEqual(True, self.gomokuGame.make_move(0, 1))\n self.assertEqual(False, self.gomokuGame.make_move(0, 0))\n board[0][0] = 'X'\n board[0][1] = 'O'\n self.assertEqual(board, self.gomokuGame.board)\n\n def test_make_move_5(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n self.assertEqual(True, self.gomokuGame.make_move(0, 1))\n self.assertEqual(False, self.gomokuGame.make_move(0, 1))\n board[0][0] = 'X'\n board[0][1] = 'O'\n self.assertEqual(board, self.gomokuGame.board)",
"solution_code": "def make_move(self, row, col):\n if self.board[row][col] == ' ':\n self.board[row][col] = self.current_player\n self.current_player = 'O' if self.current_player == 'X' else 'X'\n return True\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.board",
"self.current_player"
],
"method_dependencies": []
}
},
{
"method_name": "check_winner",
"method_description": "def check_winner(self):\n \"\"\"\n Checks if there is a winner by looking for five in a row in all directions (horizontal, vertical, diagonal).\n return: the symbol of the winning player (either 'X' or 'O') if there is a winner, or None otherwise.\n >>> gomokuGame = GomokuGame(10)\n >>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]\n >>> for move in moves:\n ... gomokuGame.make_move(move[0], move[1])\n >>> gomokuGame.check_winner()\n 'X'\n \"\"\"",
"test_class": "GomokuGameTestCheckWinner",
"test_code": "class GomokuGameTestCheckWinner(unittest.TestCase):\n def test_check_winner_1(self):\n gomokuGame = GomokuGame(10)\n self.assertEqual(None, gomokuGame.check_winner())\n\n def test_check_winner_2(self):\n gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]\n for move in moves:\n gomokuGame.make_move(move[0], move[1])\n self.assertEqual('X', gomokuGame.check_winner())\n\n def test_check_winner_3(self):\n gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 0), (0, 4)]\n for move in moves:\n gomokuGame.make_move(move[0], move[1])\n self.assertEqual('O', gomokuGame.check_winner())\n\n def test_check_winner_4(self):\n gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1), (0, 4)]\n for move in moves:\n gomokuGame.make_move(move[0], move[1])\n self.assertEqual(gomokuGame.check_winner(), 'O')\n\n def test_check_winner_5(self):\n gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1), (0, 4), (5, 0)]\n for move in moves:\n gomokuGame.make_move(move[0], move[1])\n self.assertEqual('O', gomokuGame.check_winner())",
"solution_code": "def check_winner(self):\n directions = [(0, 1), (1, 0), (1, 1), (1, -1)]\n for row in range(self.board_size):\n for col in range(self.board_size):\n if self.board[row][col] != ' ':\n for direction in directions:\n if self._check_five_in_a_row(row, col, direction):\n return self.board[row][col]\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.board",
"self.board_size"
],
"method_dependencies": [
"_check_five_in_a_row"
]
}
},
{
"method_name": "_check_five_in_a_row",
"method_description": "def _check_five_in_a_row(self, row, col, direction):\n \"\"\"\n checks if there are five consecutive symbols of the same player in a row starting from a given cell in a given direction (horizontal, vertical, diagonal).\n Counts the number of consecutive symbols in that direction starting from the given cell,\n :param row: int, row of the given cell\n :param col: int, column of the given cell\n :param direction: tuple, (int, int), named as (dx, dy). Row and col will plus several dx and dy repectively.\n :return: True if there are five consecutive symbols of the same player, and False otherwise.\n >>> gomokuGame = GomokuGame(10)\n >>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]\n >>> for move in moves:\n ... gomokuGame.make_move(move[0], move[1])\n >>> gomokuGame._check_five_in_a_row(5, 1, (0, 1))\n True\n >>> gomokuGame._check_five_in_a_row(5, 1, (1, 1))\n False\n \"\"\"",
"test_class": "GomokuGameTestCheckFiveInARow",
"test_code": "class GomokuGameTestCheckFiveInARow(unittest.TestCase):\n def setUp(self) -> None:\n self.gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]\n for move in moves:\n self.gomokuGame.make_move(move[0], move[1])\n\n def test_check_five_in_a_row_1(self):\n self.assertEqual(True, self.gomokuGame._check_five_in_a_row(5, 5, (0, -1)))\n\n def test_check_five_in_a_row_2(self):\n self.assertEqual(True, self.gomokuGame._check_five_in_a_row(5, 1, (0, 1)))\n\n def test_check_five_in_a_row_3(self):\n self.assertEqual(False, self.gomokuGame._check_five_in_a_row(0, 0, (0, 1)))\n\n def test_check_five_in_a_row_4(self):\n self.assertEqual(False, self.gomokuGame._check_five_in_a_row(0, 0, (1, 0)))\n\n def test_check_five_in_a_row_5(self):\n self.assertEqual(False, self.gomokuGame._check_five_in_a_row(5, 5, (1, 0)))",
"solution_code": "def _check_five_in_a_row(self, row, col, direction):\n dx, dy = direction\n count = 1\n symbol = self.board[row][col]\n for i in range(1, 5):\n new_row = row + dx * i\n new_col = col + dy * i\n if not (0 <= new_row < self.board_size and 0 <= new_col < self.board_size):\n return False\n if self.board[new_row][new_col] != symbol:\n return False\n count += 1\n return count == 5",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.board",
"self.board_size"
],
"method_dependencies": []
}
}
] | GomokuGame | [
"GomokuGameTestMakeMove",
"GomokuGameTestCheckWinner",
"GomokuGameTestCheckFiveInARow",
"GomokuGameTestMain"
] | class GomokuGame:
def __init__(self, board_size):
"""
Initializes the game with a given board size.
It initializes the board with empty spaces and sets the current player symble as 'X'.
"""
self.board_size = board_size
self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)]
self.current_player = 'X'
| [
"self.board",
"self.board_size",
"self.current_player"
] |
ClassEval_42 | class Hotel:
"""
This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.
"""
def __init__(self, name, rooms):
"""
Initialize the three fields in Hotel System.
name is the hotel name.
available_rooms stores the remaining rooms in the hotel
booked_rooms stores the rooms that have been booked and the person's name who booked rooms.
>>> hotel.name
'peace hotel'
>>> hotel.available_rooms
available_rooms = {'single': 5, 'double': 3}
>>> hotel.booked_rooms
{'single': {'guest 1': 2, 'guest 2':1}, 'double': {'guest1': 1}}
"""
self.name = name
self.available_rooms = rooms
self.booked_rooms = {}
def book_room(self, room_type, room_number, name):
"""
Check if there are any rooms of the specified type available.
if rooms are adequate, modify available_rooms and booked_rooms and finish booking, or fail to book otherwise.
:param room_type: str
:param room_number: int, the expected number of specified type rooms to be booked
:param name: str, guest name
:return: if number of rooms about to be booked doesn't exceed the remaining rooms, return str 'Success!'
if exceeds but quantity of available rooms is not equal to zero, return int(the remaining quantity of this room type).
if exceeds and quantity is zero or the room_type isn't in available_room, return False.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.book_room('single', 5, 'guest 1')
4
>>> hotel.book_room('single', 4, 'guest 1')
'Success!'
>>> hotel.book_room('single', 1, 'guest 1')
False
>>> hotel.book_room('triple', 1, 'guest 1')
False
"""
def check_in(self, room_type, room_number, name):
"""
Check if the room of the specified type and number is booked by the person named name.
Remove this name when check in successfuly(room_number is equal to specific person's booked_rooms. When the actual check in quantity (room_number) is less than the booked quantity, number in booked_rooms will be booked quantity minus actual quantity
:param room_type: str, check in room type
:param room_number: int, check in room number
:param name: str, person name
:return False: only if the room_type is not in the booked_rooms or room_number is higher than quantity in booked rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.check_in('single', 2, 'guest 1')
False
>>> hotel.check_in('single', 1, 'guest 1')
>>> hotel.booked_rooms
{'single': {}}
"""
def check_out(self, room_type, room_number):
"""
Check out rooms, add number for specific type in available_rooms.
If room_type is new, add new type in available_rooms.
:param room_type: str, check out room type
:param room_number: int, check out room number
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.check_out('single', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3}
>>> hotel.check_out('triple', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3, 'triple': 2}
"""
def get_available_rooms(self, room_type):
"""
Get the number of specific type of available rooms.
:param room_type: str, the room type that want to know
:return: int, the remaining number of this type rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.get_available_rooms('single')
5
""" | import unittest
class HotelTestBookRoom(unittest.TestCase):
def setUp(self):
self.hotel = Hotel('peace hotel', {'single': 3, 'double': 2})
def test_book_room_1(self):
result = self.hotel.book_room('single', 2, 'guest 1')
self.assertEqual(result, 'Success!')
self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})
self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})
def test_book_room_2(self):
result = self.hotel.book_room('triple', 2, 'guest 1')
self.assertFalse(result)
self.assertEqual(self.hotel.booked_rooms, {})
self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 2})
def test_book_room_3(self):
self.hotel.book_room('single', 2, 'guest 1')
result = self.hotel.book_room('single', 2, 'guest 2')
self.assertEqual(result, 1)
self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})
self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})
def test_book_room_4(self):
self.hotel.book_room('single', 2, 'guest 1')
result = self.hotel.book_room('single', 1, 'guest 2')
self.assertEqual(result, 'Success!')
self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2, 'guest 2': 1}})
self.assertEqual(self.hotel.available_rooms, {'double': 2, 'single': 0})
def test_book_room_5(self):
self.hotel.book_room('single', 2, 'guest 1')
result = self.hotel.book_room('single', 3, 'guest 2')
self.assertEqual(result, 1)
self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})
self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})
def test_book_room_6(self):
self.hotel.book_room('single', 3, 'guest 1')
result = self.hotel.book_room('single', 100, 'guest 1')
self.assertFalse(result)
class HotelTestCheckIn(unittest.TestCase):
def setUp(self):
self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2})
self.hotel.booked_rooms = {'single': {'guest 1': 2}, 'double': {'guest 2': 1}}
def test_check_in_1(self):
self.hotel.check_in('single', 1, 'guest 1')
self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 1}, 'double': {'guest 2': 1}})
def test_check_in_2(self):
self.assertFalse(self.hotel.check_in('single', 3, 'guest 1'))
self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})
def test_check_in_3(self):
self.assertFalse(self.hotel.check_in('double', 1, 'guest 1'))
self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})
def test_check_in_4(self):
self.hotel.check_in('double', 1, 'guest 2')
self.assertEqual(self.hotel.booked_rooms, {'double': {}, 'single': {'guest 1': 2}})
def test_check_in_5(self):
self.hotel.check_in('double', 2, 'guest 2')
self.assertEqual(self.hotel.booked_rooms, {'double': {'guest 2': 1}, 'single': {'guest 1': 2}})
def test_check_in_6(self):
res = self.hotel.check_in('abc', 1, 'guest 1')
self.assertFalse(res)
class HotelTestCheckOut(unittest.TestCase):
def setUp(self):
self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2})
self.hotel.booked_rooms = {'single': {'guest 1': 2}, 'double': {'guest 2': 1}}
def test_check_out_1(self):
self.hotel.check_out('single', 1)
self.assertEqual(self.hotel.available_rooms, {'single': 4, 'double': 2})
self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})
def test_check_out_2(self):
self.hotel.check_out('single', 3)
self.assertEqual(self.hotel.available_rooms, {'single': 6, 'double': 2})
self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})
def test_check_out_3(self):
self.hotel.check_out('triple', 2)
self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 2, 'triple': 2})
self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})
def test_check_out_4(self):
self.hotel.check_out('double', 1)
self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 3})
self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})
def test_check_out_5(self):
self.hotel.check_out('double', 2)
self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 4})
self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})
class HotelTestAvailableRooms(unittest.TestCase):
def setUp(self):
self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2, 'triple': 2})
def test_get_available_rooms(self):
result = self.hotel.get_available_rooms('single')
self.assertEqual(result, 3)
def test_get_available_rooms_2(self):
self.hotel.book_room('single', 2, 'guest 1')
result = self.hotel.get_available_rooms('single')
self.assertEqual(result, 1)
def test_get_available_rooms_3(self):
self.hotel.book_room('single', 3, 'guest 1')
result = self.hotel.get_available_rooms('single')
self.assertEqual(result, 0)
def test_get_available_rooms_4(self):
self.hotel.book_room('single', 3, 'guest 1')
result = self.hotel.get_available_rooms('double')
self.assertEqual(result, 2)
def test_get_available_rooms_5(self):
self.hotel.book_room('single', 3, 'guest 1')
result = self.hotel.get_available_rooms('triple')
self.assertEqual(result, 2)
class HotelTestMain(unittest.TestCase):
def setUp(self) -> None:
self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2})
def test_main(self):
result = self.hotel.book_room('single', 2, 'guest 1')
self.assertEqual(result, 'Success!')
self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})
self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})
self.hotel.check_in('single', 2, 'guest 1')
self.assertEqual(self.hotel.booked_rooms, {'single': {}})
self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})
self.hotel.check_out('single', 2)
self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 2})
self.assertEqual(self.hotel.get_available_rooms('single'), 3) | class Hotel:
def __init__(self, name, rooms):
self.name = name
self.available_rooms = rooms
# available_rooms = {room_type1: room_number1, room_type2: room_number2, ...}
# available_rooms = {'single': 5, 'double': 3}
self.booked_rooms = {}
# booked_rooms = {room_type1: {name1: room_number1, name2: room_number2, ...}, room_type2: {...}, ...}
# booked_rooms = {'single': {'name1': 2, 'name2':1}, 'double': {}}
def book_room(self, room_type, room_number, name):
# Check if there are any rooms of the specified type available
if room_type not in self.available_rooms.keys():
return False
if room_number <= self.available_rooms[room_type]:
# Book the room by adding it to the booked_rooms dictionary
if room_type not in self.booked_rooms.keys():
self.booked_rooms[room_type] = {}
self.booked_rooms[room_type][name] = room_number
self.available_rooms[room_type] -= room_number
return "Success!"
elif self.available_rooms[room_type] != 0:
return self.available_rooms[room_type]
else:
return False
def check_in(self, room_type, room_number, name):
# Check if the room of the specified type and number is booked
if room_type not in self.booked_rooms.keys():
return False
if name in self.booked_rooms[room_type]:
if room_number > self.booked_rooms[room_type][name]:
return False
elif room_number == self.booked_rooms[room_type][name]:
# Check in the room by removing it from the booked_rooms dictionary
self.booked_rooms[room_type].pop(name)
else:
self.booked_rooms[room_type][name] -= room_number
def check_out(self, room_type, room_number):
if room_type in self.available_rooms:
self.available_rooms[room_type] += room_number
else:
self.available_rooms[room_type] = room_number
def get_available_rooms(self, room_type):
return self.available_rooms[room_type] | [] | """
This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.
"""
| [
{
"method_name": "book_room",
"method_description": "def book_room(self, room_type, room_number, name):\n \"\"\"\n Check if there are any rooms of the specified type available.\n if rooms are adequate, modify available_rooms and booked_rooms and finish booking, or fail to book otherwise.\n :param room_type: str\n :param room_number: int, the expected number of specified type rooms to be booked\n :param name: str, guest name\n :return: if number of rooms about to be booked doesn't exceed the remaining rooms, return str 'Success!'\n if exceeds but quantity of available rooms is not equal to zero, return int(the remaining quantity of this room type).\n if exceeds and quantity is zero or the room_type isn't in available_room, return False.\n >>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})\n >>> hotel.book_room('single', 1, 'guest 1')\n 'Success!'\n >>> hotel.book_room('single', 5, 'guest 1')\n 4\n >>> hotel.book_room('single', 4, 'guest 1')\n 'Success!'\n >>> hotel.book_room('single', 1, 'guest 1')\n False\n >>> hotel.book_room('triple', 1, 'guest 1')\n False\n \"\"\"",
"test_class": "HotelTestBookRoom",
"test_code": "class HotelTestBookRoom(unittest.TestCase):\n def setUp(self):\n self.hotel = Hotel('peace hotel', {'single': 3, 'double': 2})\n\n def test_book_room_1(self):\n result = self.hotel.book_room('single', 2, 'guest 1')\n self.assertEqual(result, 'Success!')\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})\n self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})\n\n def test_book_room_2(self):\n result = self.hotel.book_room('triple', 2, 'guest 1')\n self.assertFalse(result)\n self.assertEqual(self.hotel.booked_rooms, {})\n self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 2})\n\n def test_book_room_3(self):\n self.hotel.book_room('single', 2, 'guest 1')\n result = self.hotel.book_room('single', 2, 'guest 2')\n self.assertEqual(result, 1)\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})\n self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})\n\n def test_book_room_4(self):\n self.hotel.book_room('single', 2, 'guest 1')\n result = self.hotel.book_room('single', 1, 'guest 2')\n self.assertEqual(result, 'Success!')\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2, 'guest 2': 1}})\n self.assertEqual(self.hotel.available_rooms, {'double': 2, 'single': 0})\n\n def test_book_room_5(self):\n self.hotel.book_room('single', 2, 'guest 1')\n result = self.hotel.book_room('single', 3, 'guest 2')\n self.assertEqual(result, 1)\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})\n self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})\n\n def test_book_room_6(self):\n self.hotel.book_room('single', 3, 'guest 1')\n result = self.hotel.book_room('single', 100, 'guest 1')\n self.assertFalse(result)",
"solution_code": "def book_room(self, room_type, room_number, name):\n # Check if there are any rooms of the specified type available\n if room_type not in self.available_rooms.keys():\n return False\n\n if room_number <= self.available_rooms[room_type]:\n # Book the room by adding it to the booked_rooms dictionary\n if room_type not in self.booked_rooms.keys():\n self.booked_rooms[room_type] = {}\n self.booked_rooms[room_type][name] = room_number\n self.available_rooms[room_type] -= room_number\n return \"Success!\"\n elif self.available_rooms[room_type] != 0:\n return self.available_rooms[room_type]\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.available_rooms",
"self.booked_rooms"
],
"method_dependencies": []
}
},
{
"method_name": "check_in",
"method_description": "def check_in(self, room_type, room_number, name):\n \"\"\"\n Check if the room of the specified type and number is booked by the person named name.\n Remove this name when check in successfuly(room_number is equal to specific person's booked_rooms. When the actual check in quantity (room_number) is less than the booked quantity, number in booked_rooms will be booked quantity minus actual quantity\n :param room_type: str, check in room type\n :param room_number: int, check in room number\n :param name: str, person name\n :return False: only if the room_type is not in the booked_rooms or room_number is higher than quantity in booked rooms.\n >>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})\n >>> hotel.book_room('single', 1, 'guest 1')\n 'Success!'\n >>> hotel.check_in('single', 2, 'guest 1')\n False\n >>> hotel.check_in('single', 1, 'guest 1')\n >>> hotel.booked_rooms\n {'single': {}}\n \"\"\"",
"test_class": "HotelTestCheckIn",
"test_code": "class HotelTestCheckIn(unittest.TestCase):\n def setUp(self):\n self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2})\n self.hotel.booked_rooms = {'single': {'guest 1': 2}, 'double': {'guest 2': 1}}\n\n def test_check_in_1(self):\n self.hotel.check_in('single', 1, 'guest 1')\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 1}, 'double': {'guest 2': 1}})\n\n def test_check_in_2(self):\n self.assertFalse(self.hotel.check_in('single', 3, 'guest 1'))\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_in_3(self):\n self.assertFalse(self.hotel.check_in('double', 1, 'guest 1'))\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_in_4(self):\n self.hotel.check_in('double', 1, 'guest 2')\n self.assertEqual(self.hotel.booked_rooms, {'double': {}, 'single': {'guest 1': 2}})\n\n def test_check_in_5(self):\n self.hotel.check_in('double', 2, 'guest 2')\n self.assertEqual(self.hotel.booked_rooms, {'double': {'guest 2': 1}, 'single': {'guest 1': 2}})\n\n def test_check_in_6(self):\n res = self.hotel.check_in('abc', 1, 'guest 1')\n self.assertFalse(res)",
"solution_code": "def check_in(self, room_type, room_number, name):\n # Check if the room of the specified type and number is booked\n if room_type not in self.booked_rooms.keys():\n return False\n if name in self.booked_rooms[room_type]:\n if room_number > self.booked_rooms[room_type][name]:\n return False\n elif room_number == self.booked_rooms[room_type][name]:\n # Check in the room by removing it from the booked_rooms dictionary\n self.booked_rooms[room_type].pop(name)\n else:\n self.booked_rooms[room_type][name] -= room_number",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.booked_rooms"
],
"method_dependencies": []
}
},
{
"method_name": "check_out",
"method_description": "def check_out(self, room_type, room_number):\n \"\"\"\n Check out rooms, add number for specific type in available_rooms.\n If room_type is new, add new type in available_rooms.\n :param room_type: str, check out room type\n :param room_number: int, check out room number\n >>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})\n >>> hotel.check_out('single', 2)\n >>> hotel.available_rooms\n {'single': 7, 'double': 3}\n >>> hotel.check_out('triple', 2)\n >>> hotel.available_rooms\n {'single': 7, 'double': 3, 'triple': 2}\n \"\"\"",
"test_class": "HotelTestCheckOut",
"test_code": "class HotelTestCheckOut(unittest.TestCase):\n def setUp(self):\n self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2})\n self.hotel.booked_rooms = {'single': {'guest 1': 2}, 'double': {'guest 2': 1}}\n\n def test_check_out_1(self):\n self.hotel.check_out('single', 1)\n self.assertEqual(self.hotel.available_rooms, {'single': 4, 'double': 2})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_out_2(self):\n self.hotel.check_out('single', 3)\n self.assertEqual(self.hotel.available_rooms, {'single': 6, 'double': 2})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_out_3(self):\n self.hotel.check_out('triple', 2)\n self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 2, 'triple': 2})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_out_4(self):\n self.hotel.check_out('double', 1)\n self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 3})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_out_5(self):\n self.hotel.check_out('double', 2)\n self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 4})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})",
"solution_code": "def check_out(self, room_type, room_number):\n if room_type in self.available_rooms:\n self.available_rooms[room_type] += room_number\n else:\n self.available_rooms[room_type] = room_number",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.available_rooms"
],
"method_dependencies": []
}
},
{
"method_name": "get_available_rooms",
"method_description": "def get_available_rooms(self, room_type):\n \"\"\"\n Get the number of specific type of available rooms.\n :param room_type: str, the room type that want to know\n :return: int, the remaining number of this type rooms.\n >>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})\n >>> hotel.get_available_rooms('single')\n 5\n \"\"\"",
"test_class": "HotelTestAvailableRooms",
"test_code": "class HotelTestAvailableRooms(unittest.TestCase):\n def setUp(self):\n self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2, 'triple': 2})\n\n def test_get_available_rooms(self):\n result = self.hotel.get_available_rooms('single')\n self.assertEqual(result, 3)\n\n def test_get_available_rooms_2(self):\n self.hotel.book_room('single', 2, 'guest 1')\n result = self.hotel.get_available_rooms('single')\n self.assertEqual(result, 1)\n\n def test_get_available_rooms_3(self):\n self.hotel.book_room('single', 3, 'guest 1')\n result = self.hotel.get_available_rooms('single')\n self.assertEqual(result, 0)\n\n def test_get_available_rooms_4(self):\n self.hotel.book_room('single', 3, 'guest 1')\n result = self.hotel.get_available_rooms('double')\n self.assertEqual(result, 2)\n\n def test_get_available_rooms_5(self):\n self.hotel.book_room('single', 3, 'guest 1')\n result = self.hotel.get_available_rooms('triple')\n self.assertEqual(result, 2)",
"solution_code": "def get_available_rooms(self, room_type):\n return self.available_rooms[room_type]",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.available_rooms"
],
"method_dependencies": []
}
}
] | Hotel | [
"HotelTestBookRoom",
"HotelTestCheckIn",
"HotelTestCheckOut",
"HotelTestAvailableRooms",
"HotelTestMain"
] | class Hotel:
def __init__(self, name, rooms):
"""
Initialize the three fields in Hotel System.
name is the hotel name.
available_rooms stores the remaining rooms in the hotel
booked_rooms stores the rooms that have been booked and the person's name who booked rooms.
>>> hotel.name
'peace hotel'
>>> hotel.available_rooms
available_rooms = {'single': 5, 'double': 3}
>>> hotel.booked_rooms
{'single': {'guest 1': 2, 'guest 2':1}, 'double': {'guest1': 1}}
"""
self.name = name
self.available_rooms = rooms
self.booked_rooms = {}
| [
"self.available_rooms",
"self.booked_rooms",
"self.name"
] |
ClassEval_43 | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
"""
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
"""
Add a new employee to the HRManagementSystem.
:param employee_id: The employee's id, int.
:param name: The employee's name, str.
:param position: The employee's position, str.
:param department: The employee's department, str.
:param salary: The employee's salary, int.
:return: If the employee is already in the HRManagementSystem, returns False, otherwise, returns True.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
True
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
False
"""
def remove_employee(self, employee_id):
"""
Remove an employee from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.remove_employee(1)
True
>>> hrManagementSystem.remove_employee(2)
False
"""
def update_employee(self, employee_id: int, employee_info: dict):
"""
Update an employee's information in the HRManagementSystem.
:param employee_id: The employee's id, int.
:param employee_info: The employee's information, dict.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
True
>>> hrManagementSystem.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
False
"""
def get_employee(self, employee_id):
"""
Get an employee's information from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns the employee's information, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.get_employee(1)
{'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}
>>> hrManagementSystem.get_employee(2)
False
"""
def list_employees(self):
“”“
List all employees' information in the HRManagementSystem.
:return: A list of all employees' information,dict.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.list_employees()
{1: {'employee_ID': 1, 'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
""" | import unittest
class HRManagementSystemTestAddEmployee(unittest.TestCase):
def test_add_employee(self):
hr_system = HRManagementSystem()
self.assertEqual(hr_system.add_employee(1, "John Doe", "Manager", "HR", 5000), True)
self.assertEqual(hr_system.employees[1], {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000})
def test_add_employee_2(self):
hr_system = HRManagementSystem()
self.assertEqual(hr_system.add_employee(1, "John Doe", "Manager", "HR", 5000), True)
self.assertEqual(hr_system.add_employee(1, "John Doe", "Manager", "HR", 5000), False)
self.assertEqual(hr_system.employees[1], {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000})
def test_add_employee_3(self):
hr_system = HRManagementSystem()
self.assertEqual(hr_system.add_employee(1, "John Doe", "Manager", "HR", 5000), True)
self.assertEqual(hr_system.add_employee(2, "John Doe", "Manager", "HR", 5000), True)
self.assertEqual(hr_system.employees,{1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})
def test_add_employee_4(self):
hr_system = HRManagementSystem()
self.assertEqual(hr_system.add_employee(1, "John Doe", "Manager", "HR", 5000), True)
self.assertEqual(hr_system.add_employee(2, "John Doe", "Manager", "HR", 5000), True)
self.assertEqual(hr_system.add_employee(1, "John Doe", "Manager", "HR", 5000), False)
self.assertEqual(hr_system.employees,{1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})
def test_add_employee_5(self):
hr_system = HRManagementSystem()
self.assertEqual(hr_system.add_employee(1, "John Doe", "Manager", "HR", 5000), True)
self.assertEqual(hr_system.add_employee(2, "John Doe", "Manager", "HR", 5000), True)
self.assertEqual(hr_system.add_employee(1, "John Doe", "Manager", "HR", 5000), False)
self.assertEqual(hr_system.add_employee(2, "John Doe", "Manager", "HR", 5000), False)
self.assertEqual(hr_system.employees,{1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})
class HRManagementSystemTestRemoveEmployee(unittest.TestCase):
def test_remove_employee(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.remove_employee(1), True)
self.assertEqual(hr_system.employees, {})
def test_remove_employee_2(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.remove_employee(1), True)
self.assertEqual(hr_system.remove_employee(1), False)
self.assertEqual(hr_system.employees, {})
def test_remove_employee_3(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.remove_employee(1), True)
self.assertEqual(hr_system.employees, {2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})
def test_remove_employee_4(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.remove_employee(1), True)
self.assertEqual(hr_system.remove_employee(2), True)
self.assertEqual(hr_system.employees, {})
def test_remove_employee_5(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.remove_employee(1), True)
self.assertEqual(hr_system.remove_employee(2), True)
self.assertEqual(hr_system.remove_employee(1), False)
self.assertEqual(hr_system.remove_employee(2), False)
self.assertEqual(hr_system.employees, {})
class HRManagementSystemTestUpdateEmployee(unittest.TestCase):
def test_update_employee(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)
self.assertEqual(hr_system.employees[1], {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
def test_update_employee_2(self):
hr_system = HRManagementSystem()
hr_system.employees = {}
self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), False)
self.assertEqual(hr_system.employees, {})
def test_update_employee_3(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), False)
self.assertEqual(hr_system.employees, {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})
def test_update_employee_4(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)
self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)
self.assertEqual(hr_system.employees[1], {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
def test_update_employee_5(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)
self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)
self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}), True)
self.assertEqual(hr_system.employees[1], {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})
def test_update_employee_6(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.update_employee(1, {'Name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), False)
class HRManagementSystemTestGetEmployee(unittest.TestCase):
def test_get_employee(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})
def test_get_employee_2(self):
hr_system = HRManagementSystem()
hr_system.employees = {}
self.assertEqual(hr_system.get_employee(1), False)
def test_get_employee_3(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.get_employee(2), False)
def test_get_employee_4(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})
self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})
def test_get_employee_5(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})
self.assertEqual(hr_system.get_employee(2), {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})
class HRManagementSystemTestListEmployees(unittest.TestCase):
def test_list_employees(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})
def test_list_employees_2(self):
hr_system = HRManagementSystem()
hr_system.employees = {}
self.assertEqual(hr_system.list_employees(), {})
def test_list_employees_3(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'employee_ID':2,'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})
def test_list_employees_4(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'employee_ID':2,'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})
def test_list_employees_5(self):
hr_system = HRManagementSystem()
hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'employee_ID':2,'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})
hr_system.employees = {}
self.assertEqual(hr_system.list_employees(), {})
class HRManagementSystemTestMain(unittest.TestCase):
def test_main(self):
hr_system = HRManagementSystem()
hr_system.add_employee(1, "John Doe", "Manager", "HR", 5000)
hr_system.add_employee(2, "Jane Smith", "Developer", "IT", 4000)
self.assertEqual(hr_system.list_employees(), {1: {'employee_ID': 1, 'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'employee_ID': 2, 'name': 'Jane Smith', 'position': 'Developer', 'department': 'IT', 'salary': 4000}})
hr_system.remove_employee(2)
self.assertEqual(hr_system.list_employees(), {1: {'employee_ID': 1, 'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})
self.assertEqual(hr_system.remove_employee(2), False)
self.assertEqual(hr_system.update_employee(1, {'name': 'John Doe Jr.', 'salary': 5500}), True)
self.assertEqual(hr_system.employees[1], {'name': 'John Doe Jr.', 'position': 'Manager', 'department': 'HR', 'salary': 5500})
self.assertEqual(hr_system.update_employee(3, {'name': 'Invalid Employee'}), False)
self.assertEqual(hr_system.get_employee(1), {'name': 'John Doe Jr.', 'position': 'Manager', 'department': 'HR', 'salary': 5500})
self.assertEqual(hr_system.get_employee(2), False)
self.assertEqual(hr_system.list_employees(), {1: {'employee_ID': 1, 'name': 'John Doe Jr.', 'position': 'Manager', 'department': 'HR', 'salary': 5500}})
def test_main_2(self):
hr_system = HRManagementSystem()
self.assertEqual(hr_system.remove_employee(2), False)
self.assertEqual(hr_system.update_employee(1, {'name': 'John Doe Jr.', 'salary': 5500}), False)
hr_system.add_employee(1, "John Doe", "Manager", "HR", 5000)
hr_system.add_employee(2, "Jane Smith", "Developer", "IT", 4000)
self.assertEqual(hr_system.list_employees(), {
1: {'employee_ID': 1, 'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000},
2: {'employee_ID': 2, 'name': 'Jane Smith', 'position': 'Developer', 'department': 'IT', 'salary': 4000}})
self.assertEqual(hr_system.remove_employee(2), True)
self.assertEqual(hr_system.employees, {1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})
self.assertEqual(hr_system.list_employees(), {1: {'employee_ID': 1, 'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})
self.assertEqual(hr_system.update_employee(1, {'name': 'John Doe Jr.', 'salary': 5500}), True)
self.assertEqual(hr_system.employees[1], {'name': 'John Doe Jr.', 'position': 'Manager', 'department': 'HR', 'salary': 5500})
self.assertEqual(hr_system.get_employee(1), {'name': 'John Doe Jr.', 'position': 'Manager', 'department': 'HR', 'salary': 5500})
self.assertEqual(hr_system.get_employee(2), False) | class HRManagementSystem:
def __init__(self):
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
if employee_id in self.employees:
return False
else:
self.employees[employee_id] = {
'name': name,
'position': position,
'department': department,
'salary': salary
}
return True
def remove_employee(self, employee_id):
if employee_id in self.employees:
del self.employees[employee_id]
return True
else:
return False
def update_employee(self, employee_id: int, employee_info: dict):
employee = self.get_employee(employee_id)
if employee == False:
return False
else:
for key, value in employee_info.items():
if key not in employee:
return False
for key, value in employee_info.items():
employee[key] = value
return True
def get_employee(self, employee_id):
if employee_id in self.employees:
return self.employees[employee_id]
else:
return False
def list_employees(self):
employee_data = {}
if self.employees:
for employee_id, employee_info in self.employees.items():
employee_details = {}
employee_details["employee_ID"] = employee_id
for key, value in employee_info.items():
employee_details[key] = value
employee_data[employee_id] = employee_details
return employee_data | [] | """
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
| [
{
"method_name": "add_employee",
"method_description": "def add_employee(self, employee_id, name, position, department, salary):\n \"\"\"\n Add a new employee to the HRManagementSystem.\n :param employee_id: The employee's id, int.\n :param name: The employee's name, str.\n :param position: The employee's position, str.\n :param department: The employee's department, str.\n :param salary: The employee's salary, int.\n :return: If the employee is already in the HRManagementSystem, returns False, otherwise, returns True.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)\n True\n >>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)\n False\n\n \"\"\"",
"test_class": "HRManagementSystemTestAddEmployee",
"test_code": "class HRManagementSystemTestAddEmployee(unittest.TestCase):\n def test_add_employee(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000})\n\n def test_add_employee_2(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), False)\n self.assertEqual(hr_system.employees[1], {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000})\n\n def test_add_employee_3(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(2, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.employees,{1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})\n\n def test_add_employee_4(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(2, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), False)\n self.assertEqual(hr_system.employees,{1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})\n\n def test_add_employee_5(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(2, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), False)\n self.assertEqual(hr_system.add_employee(2, \"John Doe\", \"Manager\", \"HR\", 5000), False)\n self.assertEqual(hr_system.employees,{1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})",
"solution_code": "def add_employee(self, employee_id, name, position, department, salary):\n if employee_id in self.employees:\n return False\n else:\n self.employees[employee_id] = {\n 'name': name,\n 'position': position,\n 'department': department,\n 'salary': salary\n }\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.employees"
],
"method_dependencies": []
}
},
{
"method_name": "remove_employee",
"method_description": "def remove_employee(self, employee_id):\n \"\"\"\n Remove an employee from the HRManagementSystem.\n :param employee_id: The employee's id, int.\n :return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n >>> hrManagementSystem.remove_employee(1)\n True\n >>> hrManagementSystem.remove_employee(2)\n False\n\n \"\"\"",
"test_class": "HRManagementSystemTestRemoveEmployee",
"test_code": "class HRManagementSystemTestRemoveEmployee(unittest.TestCase):\n def test_remove_employee(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.employees, {})\n\n def test_remove_employee_2(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.remove_employee(1), False)\n self.assertEqual(hr_system.employees, {})\n\n def test_remove_employee_3(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.employees, {2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_remove_employee_4(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.remove_employee(2), True)\n self.assertEqual(hr_system.employees, {})\n\n def test_remove_employee_5(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.remove_employee(2), True)\n self.assertEqual(hr_system.remove_employee(1), False)\n self.assertEqual(hr_system.remove_employee(2), False)\n self.assertEqual(hr_system.employees, {})",
"solution_code": "def remove_employee(self, employee_id):\n if employee_id in self.employees:\n del self.employees[employee_id]\n return True\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.employees"
],
"method_dependencies": []
}
},
{
"method_name": "update_employee",
"method_description": "def update_employee(self, employee_id: int, employee_info: dict):\n \"\"\"\n Update an employee's information in the HRManagementSystem.\n :param employee_id: The employee's id, int.\n :param employee_info: The employee's information, dict.\n :return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n >>> hrManagementSystem.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})\n True\n >>> hrManagementSystem.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})\n False\n\n \"\"\"",
"test_class": "HRManagementSystemTestUpdateEmployee",
"test_code": "class HRManagementSystemTestUpdateEmployee(unittest.TestCase):\n def test_update_employee(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})\n\n def test_update_employee_2(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {}\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), False)\n self.assertEqual(hr_system.employees, {})\n\n def test_update_employee_3(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), False)\n self.assertEqual(hr_system.employees, {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_update_employee_4(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})\n\n def test_update_employee_5(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n\n def test_update_employee_6(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(1, {'Name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), False)",
"solution_code": "def update_employee(self, employee_id: int, employee_info: dict):\n employee = self.get_employee(employee_id)\n if employee == False:\n return False\n else:\n for key, value in employee_info.items():\n if key not in employee:\n return False\n for key, value in employee_info.items():\n employee[key] = value\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"get_employee"
]
}
},
{
"method_name": "get_employee",
"method_description": "def get_employee(self, employee_id):\n \"\"\"\n Get an employee's information from the HRManagementSystem.\n :param employee_id: The employee's id, int.\n :return: If the employee is already in the HRManagementSystem, returns the employee's information, otherwise, returns False.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n >>> hrManagementSystem.get_employee(1)\n {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}\n >>> hrManagementSystem.get_employee(2)\n False\n\n \"\"\"",
"test_class": "HRManagementSystemTestGetEmployee",
"test_code": "class HRManagementSystemTestGetEmployee(unittest.TestCase):\n def test_get_employee(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n\n def test_get_employee_2(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {}\n self.assertEqual(hr_system.get_employee(1), False)\n\n def test_get_employee_3(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.get_employee(2), False)\n\n def test_get_employee_4(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n\n def test_get_employee_5(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n self.assertEqual(hr_system.get_employee(2), {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})",
"solution_code": "def get_employee(self, employee_id):\n if employee_id in self.employees:\n return self.employees[employee_id]\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.employees"
],
"method_dependencies": []
}
},
{
"method_name": "list_employees",
"method_description": "def list_employees(self):\n “”“\n List all employees' information in the HRManagementSystem.\n :return: A list of all employees' information,dict.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n >>> hrManagementSystem.list_employees()\n {1: {'employee_ID': 1, 'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n\n \"\"\"",
"test_class": "HRManagementSystemTestListEmployees",
"test_code": "class HRManagementSystemTestListEmployees(unittest.TestCase):\n def test_list_employees(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_list_employees_2(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {}\n self.assertEqual(hr_system.list_employees(), {})\n\n def test_list_employees_3(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'employee_ID':2,'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_list_employees_4(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'employee_ID':2,'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_list_employees_5(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'employee_ID':2,'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n hr_system.employees = {}\n self.assertEqual(hr_system.list_employees(), {})",
"solution_code": "def list_employees(self):\n employee_data = {}\n if self.employees:\n for employee_id, employee_info in self.employees.items():\n employee_details = {}\n employee_details[\"employee_ID\"] = employee_id\n for key, value in employee_info.items():\n employee_details[key] = value\n employee_data[employee_id] = employee_details\n return employee_data",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.employees"
],
"method_dependencies": []
}
}
] | HRManagementSystem | [
"HRManagementSystemTestAddEmployee",
"HRManagementSystemTestRemoveEmployee",
"HRManagementSystemTestUpdateEmployee",
"HRManagementSystemTestGetEmployee",
"HRManagementSystemTestListEmployees",
"HRManagementSystemTestMain"
] | class HRManagementSystem:
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
"""
self.employees = {}
| [
"self.employees"
] |
ClassEval_44 | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
This is a class as util for html, supporting for formatting and extracting code from HTML text, including cleaning up the text and converting certain elements into specific marks.
"""
def __init__(self):
"""
Initialize a series of labels
"""
self.SPACE_MARK = '-SPACE-'
self.JSON_MARK = '-JSON-'
self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-'
self.URL_MARK = '-URL-'
self.NUMBER_MARK = '-NUMBER-'
self.TRACE_MARK = '-TRACE-'
self.COMMAND_MARK = '-COMMAND-'
self.COMMENT_MARK = '-COMMENT-'
self.CODE_MARK = '-CODE-'
@staticmethod
def __format_line_feed(text):
"""
Replace consecutive line breaks with a single line break
:param text: string with consecutive line breaks
:return:string, replaced text with single line break
"""
def format_line_html_text(self, html_text):
"""
get the html text without the code, and add the code tag -CODE- where the code is
:param html_text:string
:return:string
>>>htmlutil = HtmlUtil()
>>>htmlutil.format_line_html_text(<html>
>>> <body>
>>> <h1>Title</h1>
>>> <p>This is a paragraph.</p>
>>> <pre>print('Hello, world!')</pre>
>>> <p>Another paragraph.</p>
>>> <pre><code>for i in range(5):
>>> print(i)</code></pre>
>>> </body>
>>> </html>)
Title
This is a paragraph.
-CODE-
Another paragraph.
-CODE-
"""
def extract_code_from_html_text(self, html_text):
"""
extract codes from the html body
:param html_text: string, html text
:return: the list of code
>>>htmlutil = HtmlUtil()
>>>htmlutil.extract_code_from_html_text(<html>
>>> <body>
>>> <h1>Title</h1>
>>> <p>This is a paragraph.</p>
>>> <pre>print('Hello, world!')</pre>
>>> <p>Another paragraph.</p>
>>> <pre><code>for i in range(5):
>>> print(i)</code></pre>
>>> </body>
>>> </html>)
["print('Hello, world!')", 'for i in range(5):\n print(i)']
""" | import unittest
import sys
class HtmlUtilTestFormatLineFeed(unittest.TestCase):
def test_format_line_feed_1(self):
self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\n\n\n'), 'aaa\n')
def test_format_line_feed_2(self):
self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\n\n\n\n'), 'aaa\n')
def test_format_line_feed_3(self):
self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\n\n\nbbb\n\n'), 'aaa\nbbb\n')
def test_format_line_feed_4(self):
self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('ccc\n\n\n'), 'ccc\n')
def test_format_line_feed_5(self):
self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed(''), '')
class HtmlUtilTestFormatLineHtmlText(unittest.TestCase):
def test_format_line_html_text_1(self):
htmlutil = HtmlUtil()
res = htmlutil.format_line_html_text('''
<html>
<body>
<h1>Title</h1>
<p>This is a paragraph.</p>
<pre>print('Hello, world!')</pre>
<p>Another paragraph.</p>
<pre><code>for i in range(5):
print(i)</code></pre>
</body>
</html>
''')
self.assertEqual(res, '''
Title
This is a paragraph.
-CODE-
Another paragraph.
-CODE-
''')
def test_format_line_html_text_2(self):
htmlutil = HtmlUtil()
res = htmlutil.format_line_html_text('''
<html>
<body>
<h1>Title2</h1>
<p>This is a paragraph.</p>
<pre>print('Hello, world!')</pre>
<p>Another paragraph.</p>
<pre><code>for i in range(5):
print(i)</code></pre>
</body>
</html>
''')
self.assertEqual(res, '''
Title2
This is a paragraph.
-CODE-
Another paragraph.
-CODE-
''')
def test_format_line_html_text_3(self):
htmlutil = HtmlUtil()
res = htmlutil.format_line_html_text('''
<html>
<body>
<h1>Title3</h1>
<p>This is a paragraph.</p>
<pre>print('Hello, world!')</pre>
<p>Another paragraph.</p>
<pre><code>for i in range(5):
print(i)</code></pre>
</body>
</html>
''')
self.assertEqual(res, '''
Title3
This is a paragraph.
-CODE-
Another paragraph.
-CODE-
''')
def test_format_line_html_text_4(self):
htmlutil = HtmlUtil()
res = htmlutil.format_line_html_text('''
<html>
<body>
<h1>Title4</h1>
<p>This is a paragraph.</p>
<pre>print('Hello, world!')</pre>
<p>Another paragraph.</p>
<pre><code>for i in range(5):
print(i)</code></pre>
</body>
</html>
''')
self.assertEqual(res, '''
Title4
This is a paragraph.
-CODE-
Another paragraph.
-CODE-
''')
def test_format_line_html_text_5(self):
htmlutil = HtmlUtil()
res = htmlutil.format_line_html_text('''
<html>
<body>
<h1>Title5</h1>
<p>This is a paragraph.</p>
<pre>print('Hello, world!')</pre>
<p>Another paragraph.</p>
<pre><code>for i in range(5):
print(i)</code></pre>
</body>
</html>
''')
self.assertEqual(res, '''
Title5
This is a paragraph.
-CODE-
Another paragraph.
-CODE-
''')
def test_format_line_html_text_6(self):
htmlutil = HtmlUtil()
res = htmlutil.format_line_html_text('')
self.assertEqual(res, '')
def test_format_line_html_text_7(self):
htmlutil = HtmlUtil()
res = htmlutil.format_line_html_text('''<ul><li>Item 1!</li></ul>''')
self.assertEqual(res, '''[-]Item 1!''')
def test_format_line_html_text_8(self):
htmlutil = HtmlUtil()
res = htmlutil.format_line_html_text('''<ul><li></li></ul>''')
self.assertEqual(res, '')
def test_format_line_html_text_9(self):
htmlutil = HtmlUtil()
res = htmlutil.format_line_html_text('''<p>Some sentence here.</p>''')
self.assertEqual(res, 'Some sentence here.')
def test_format_line_html_text_10(self):
htmlutil = HtmlUtil()
res = htmlutil.format_line_html_text('''<p>Some paragraph here</p><code>Code block</code>''')
self.assertEqual(res, '''Some paragraph here.Code block''')
def test_format_line_html_text_11(self):
htmlutil = HtmlUtil()
res = htmlutil.format_line_html_text('''<p>Some paragraph here</p><div>Some text here</div>''')
self.assertEqual(res, '''Some paragraph here.Some text here''')
def test_format_line_html_text_12(self):
htmlutil = HtmlUtil()
res = htmlutil.format_line_html_text('''<ul><li>Item 1</li></ul>''')
self.assertEqual(res, '''[-]Item 1.''')
class HtmlUtilTestExtractCodeFromHtmlText(unittest.TestCase):
def test_extract_code_from_html_text_1(self):
htmlutil = HtmlUtil()
res = htmlutil.extract_code_from_html_text('''
<html>
<body>
<h1>Title</h1>
<p>This is a paragraph.</p>
<pre>print('Hello, world!')</pre>
<p>Another paragraph.</p>
<pre><code>for i in range(5):
print(i)</code></pre>
</body>
</html>
''')
self.assertEqual(res, ["print('Hello, world!')", 'for i in range(5):\n print(i)'])
def test_extract_code_from_html_text_2(self):
htmlutil = HtmlUtil()
res = htmlutil.extract_code_from_html_text('''
<html>
<body>
<h1>Title</h1>
<p>This is a paragraph.</p>
<pre>print('Hello, world!')</pre>
<p>Another paragraph.</p>
<pre><code>for i in range(4):
print(i)</code></pre>
</body>
</html>
''')
self.assertEqual(res, ["print('Hello, world!')", 'for i in range(4):\n print(i)'])
def test_extract_code_from_html_text_3(self):
htmlutil = HtmlUtil()
res = htmlutil.extract_code_from_html_text('''
<html>
<body>
<h1>Title</h1>
<p>This is a paragraph.</p>
<pre>print('Hello, world!')</pre>
<p>Another paragraph.</p>
<pre><code>for i in range(3):
print(i)</code></pre>
</body>
</html>
''')
self.assertEqual(res, ["print('Hello, world!')", 'for i in range(3):\n print(i)'])
def test_extract_code_from_html_text_4(self):
htmlutil = HtmlUtil()
res = htmlutil.extract_code_from_html_text('''
<html>
<body>
<h1>Title</h1>
<p>This is a paragraph.</p>
<pre>print('Hello, world!')</pre>
<p>Another paragraph.</p>
<pre><code>for i in range(2):
print(i)</code></pre>
</body>
</html>
''')
self.assertEqual(res, ["print('Hello, world!')", 'for i in range(2):\n print(i)'])
def test_extract_code_from_html_text_5(self):
htmlutil = HtmlUtil()
htmlutil.CODE_MARK = 'abcdefg'
res = htmlutil.extract_code_from_html_text("")
self.assertEqual(res, [])
class HtmlUtilTest(unittest.TestCase):
def test_htmlutil(self):
htmlutil = HtmlUtil()
res = htmlutil.format_line_html_text('''
<html>
<body>
<h1>Title</h1>
<p>This is a paragraph.</p>
<pre>print('Hello, world!')</pre>
<p>Another paragraph.</p>
<pre><code>for i in range(5):
print(i)</code></pre>
</body>
</html>
''')
self.assertEqual(res, '''
Title
This is a paragraph.
-CODE-
Another paragraph.
-CODE-
''')
res = htmlutil.extract_code_from_html_text('''
<html>
<body>
<h1>Title</h1>
<p>This is a paragraph.</p>
<pre>print('Hello, world!')</pre>
<p>Another paragraph.</p>
<pre><code>for i in range(5):
print(i)</code></pre>
</body>
</html>
''')
self.assertEqual(res, ["print('Hello, world!')", 'for i in range(5):\n print(i)'])
if __name__ == '__main__':
unittest.main() | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
def __init__(self):
self.SPACE_MARK = '-SPACE-'
self.JSON_MARK = '-JSON-'
self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-'
self.URL_MARK = '-URL-'
self.NUMBER_MARK = '-NUMBER-'
self.TRACE_MARK = '-TRACE-'
self.COMMAND_MARK = '-COMMAND-'
self.COMMENT_MARK = '-COMMENT-'
self.CODE_MARK = '-CODE-'
@staticmethod
def __format_line_feed(text):
return re.sub(re.compile(r'\n+'), '\n', text)
def format_line_html_text(self, html_text):
if html_text is None or len(html_text) == 0:
return ''
soup = BeautifulSoup(html_text, 'lxml')
code_tag = soup.find_all(name=['pre', 'blockquote'])
for tag in code_tag:
tag.string = self.CODE_MARK
ul_ol_group = soup.find_all(name=['ul', 'ol'])
for ul_ol_item in ul_ol_group:
li_group = ul_ol_item.find_all('li')
for li_item in li_group:
li_item_text = li_item.get_text().strip()
if len(li_item_text) == 0:
continue
if li_item_text[-1] in string.punctuation:
li_item.string = '[{0}]{1}'.format('-', li_item_text)
continue
li_item.string = '[{0}]{1}.'.format('-', li_item_text)
p_group = soup.find_all(name=['p'])
for p_item in p_group:
p_item_text = p_item.get_text().strip()
if p_item_text:
if p_item_text[-1] in string.punctuation:
p_item.string = p_item_text
continue
next_sibling = p_item.find_next_sibling()
if next_sibling and self.CODE_MARK in next_sibling.get_text():
p_item.string = p_item_text + ':'
continue
p_item.string = p_item_text + '.'
clean_text = gensim.utils.decode_htmlentities(soup.get_text())
return self.__format_line_feed(clean_text)
def extract_code_from_html_text(self, html_text):
text_with_code_tag = self.format_line_html_text(html_text)
if self.CODE_MARK not in text_with_code_tag:
return []
code_index_start = 0
soup = BeautifulSoup(html_text, 'lxml')
code_tag = soup.find_all(name=['pre', 'blockquote'])
code_count = text_with_code_tag.count(self.CODE_MARK)
code_list = []
for code_index in range(code_index_start, code_index_start + code_count):
code = code_tag[code_index].get_text()
if code:
code_list.append(code)
return code_list | [
"import re",
"import string",
"import gensim",
"from bs4 import BeautifulSoup"
] | """
This is a class as util for html, supporting for formatting and extracting code from HTML text, including cleaning up the text and converting certain elements into specific marks.
"""
| [
{
"method_name": "__format_line_feed",
"method_description": "def __format_line_feed(text):\n \"\"\"\n Replace consecutive line breaks with a single line break\n :param text: string with consecutive line breaks\n :return:string, replaced text with single line break\n \"\"\"",
"test_class": "HtmlUtilTestFormatLineFeed",
"test_code": "class HtmlUtilTestFormatLineFeed(unittest.TestCase):\n def test_format_line_feed_1(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\\n\\n\\n'), 'aaa\\n')\n\n def test_format_line_feed_2(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\\n\\n\\n\\n'), 'aaa\\n')\n\n def test_format_line_feed_3(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\\n\\n\\nbbb\\n\\n'), 'aaa\\nbbb\\n')\n\n def test_format_line_feed_4(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('ccc\\n\\n\\n'), 'ccc\\n')\n\n def test_format_line_feed_5(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed(''), '')",
"solution_code": "def __format_line_feed(text):\n return re.sub(re.compile(r'\\n+'), '\\n', text)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"re"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "format_line_html_text",
"method_description": "def format_line_html_text(self, html_text):\n \"\"\"\n get the html text without the code, and add the code tag -CODE- where the code is\n :param html_text:string\n :return:string\n >>>htmlutil = HtmlUtil()\n >>>htmlutil.format_line_html_text(<html>\n >>> <body>\n >>> <h1>Title</h1>\n >>> <p>This is a paragraph.</p>\n >>> <pre>print('Hello, world!')</pre>\n >>> <p>Another paragraph.</p>\n >>> <pre><code>for i in range(5):\n >>> print(i)</code></pre>\n >>> </body>\n >>> </html>)\n Title\n This is a paragraph.\n -CODE-\n Another paragraph.\n -CODE-\n \"\"\"",
"test_class": "HtmlUtilTestFormatLineHtmlText",
"test_code": "class HtmlUtilTestFormatLineHtmlText(unittest.TestCase):\n def test_format_line_html_text_1(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n <html>\n <body>\n <h1>Title</h1>\n <p>This is a paragraph.</p>\n <pre>print('Hello, world!')</pre>\n <p>Another paragraph.</p>\n <pre><code>for i in range(5):\n print(i)</code></pre>\n </body>\n </html>\n ''')\n self.assertEqual(res, '''\nTitle\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n\n def test_format_line_html_text_2(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n <html>\n <body>\n <h1>Title2</h1>\n <p>This is a paragraph.</p>\n <pre>print('Hello, world!')</pre>\n <p>Another paragraph.</p>\n <pre><code>for i in range(5):\n print(i)</code></pre>\n </body>\n </html>\n ''')\n self.assertEqual(res, '''\nTitle2\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n\n def test_format_line_html_text_3(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n <html>\n <body>\n <h1>Title3</h1>\n <p>This is a paragraph.</p>\n <pre>print('Hello, world!')</pre>\n <p>Another paragraph.</p>\n <pre><code>for i in range(5):\n print(i)</code></pre>\n </body>\n </html>\n ''')\n self.assertEqual(res, '''\nTitle3\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n\n def test_format_line_html_text_4(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n <html>\n <body>\n <h1>Title4</h1>\n <p>This is a paragraph.</p>\n <pre>print('Hello, world!')</pre>\n <p>Another paragraph.</p>\n <pre><code>for i in range(5):\n print(i)</code></pre>\n </body>\n </html>\n ''')\n self.assertEqual(res, '''\nTitle4\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n\n def test_format_line_html_text_5(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n <html>\n <body>\n <h1>Title5</h1>\n <p>This is a paragraph.</p>\n <pre>print('Hello, world!')</pre>\n <p>Another paragraph.</p>\n <pre><code>for i in range(5):\n print(i)</code></pre>\n </body>\n </html>\n ''')\n self.assertEqual(res, '''\nTitle5\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n def test_format_line_html_text_6(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('')\n self.assertEqual(res, '')\n\n def test_format_line_html_text_7(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''<ul><li>Item 1!</li></ul>''')\n self.assertEqual(res, '''[-]Item 1!''')\n\n def test_format_line_html_text_8(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''<ul><li></li></ul>''')\n self.assertEqual(res, '')\n\n def test_format_line_html_text_9(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''<p>Some sentence here.</p>''')\n self.assertEqual(res, 'Some sentence here.')\n\n def test_format_line_html_text_10(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''<p>Some paragraph here</p><code>Code block</code>''')\n self.assertEqual(res, '''Some paragraph here.Code block''')\n\n def test_format_line_html_text_11(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''<p>Some paragraph here</p><div>Some text here</div>''')\n self.assertEqual(res, '''Some paragraph here.Some text here''')\n\n def test_format_line_html_text_12(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''<ul><li>Item 1</li></ul>''')\n self.assertEqual(res, '''[-]Item 1.''')",
"solution_code": "def format_line_html_text(self, html_text):\n if html_text is None or len(html_text) == 0:\n return ''\n soup = BeautifulSoup(html_text, 'lxml')\n\n code_tag = soup.find_all(name=['pre', 'blockquote'])\n for tag in code_tag:\n tag.string = self.CODE_MARK\n\n ul_ol_group = soup.find_all(name=['ul', 'ol'])\n for ul_ol_item in ul_ol_group:\n li_group = ul_ol_item.find_all('li')\n for li_item in li_group:\n li_item_text = li_item.get_text().strip()\n if len(li_item_text) == 0:\n continue\n if li_item_text[-1] in string.punctuation:\n li_item.string = '[{0}]{1}'.format('-', li_item_text)\n continue\n li_item.string = '[{0}]{1}.'.format('-', li_item_text)\n\n p_group = soup.find_all(name=['p'])\n for p_item in p_group:\n p_item_text = p_item.get_text().strip()\n if p_item_text:\n if p_item_text[-1] in string.punctuation:\n p_item.string = p_item_text\n continue\n next_sibling = p_item.find_next_sibling()\n if next_sibling and self.CODE_MARK in next_sibling.get_text():\n p_item.string = p_item_text + ':'\n continue\n p_item.string = p_item_text + '.'\n\n clean_text = gensim.utils.decode_htmlentities(soup.get_text())\n return self.__format_line_feed(clean_text)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"string",
"gensim",
"BeautifulSoup"
],
"field_dependencies": [
"self.CODE_MARK"
],
"method_dependencies": [
"__format_line_feed"
]
}
},
{
"method_name": "extract_code_from_html_text",
"method_description": "def extract_code_from_html_text(self, html_text):\n \"\"\"\n extract codes from the html body\n :param html_text: string, html text\n :return: the list of code\n >>>htmlutil = HtmlUtil()\n >>>htmlutil.extract_code_from_html_text(<html>\n >>> <body>\n >>> <h1>Title</h1>\n >>> <p>This is a paragraph.</p>\n >>> <pre>print('Hello, world!')</pre>\n >>> <p>Another paragraph.</p>\n >>> <pre><code>for i in range(5):\n >>> print(i)</code></pre>\n >>> </body>\n >>> </html>)\n [\"print('Hello, world!')\", 'for i in range(5):\\n print(i)']\n \"\"\"",
"test_class": "HtmlUtilTestExtractCodeFromHtmlText",
"test_code": "class HtmlUtilTestExtractCodeFromHtmlText(unittest.TestCase):\n def test_extract_code_from_html_text_1(self):\n htmlutil = HtmlUtil()\n res = htmlutil.extract_code_from_html_text('''\n <html>\n <body>\n <h1>Title</h1>\n <p>This is a paragraph.</p>\n <pre>print('Hello, world!')</pre>\n <p>Another paragraph.</p>\n <pre><code>for i in range(5):\n print(i)</code></pre>\n </body>\n </html>\n ''')\n self.assertEqual(res, [\"print('Hello, world!')\", 'for i in range(5):\\n print(i)'])\n\n def test_extract_code_from_html_text_2(self):\n htmlutil = HtmlUtil()\n res = htmlutil.extract_code_from_html_text('''\n <html>\n <body>\n <h1>Title</h1>\n <p>This is a paragraph.</p>\n <pre>print('Hello, world!')</pre>\n <p>Another paragraph.</p>\n <pre><code>for i in range(4):\n print(i)</code></pre>\n </body>\n </html>\n ''')\n self.assertEqual(res, [\"print('Hello, world!')\", 'for i in range(4):\\n print(i)'])\n\n def test_extract_code_from_html_text_3(self):\n htmlutil = HtmlUtil()\n res = htmlutil.extract_code_from_html_text('''\n <html>\n <body>\n <h1>Title</h1>\n <p>This is a paragraph.</p>\n <pre>print('Hello, world!')</pre>\n <p>Another paragraph.</p>\n <pre><code>for i in range(3):\n print(i)</code></pre>\n </body>\n </html>\n ''')\n self.assertEqual(res, [\"print('Hello, world!')\", 'for i in range(3):\\n print(i)'])\n\n def test_extract_code_from_html_text_4(self):\n htmlutil = HtmlUtil()\n res = htmlutil.extract_code_from_html_text('''\n <html>\n <body>\n <h1>Title</h1>\n <p>This is a paragraph.</p>\n <pre>print('Hello, world!')</pre>\n <p>Another paragraph.</p>\n <pre><code>for i in range(2):\n print(i)</code></pre>\n </body>\n </html>\n ''')\n self.assertEqual(res, [\"print('Hello, world!')\", 'for i in range(2):\\n print(i)'])\n\n def test_extract_code_from_html_text_5(self):\n htmlutil = HtmlUtil()\n htmlutil.CODE_MARK = 'abcdefg'\n res = htmlutil.extract_code_from_html_text(\"\")\n self.assertEqual(res, [])",
"solution_code": "def extract_code_from_html_text(self, html_text):\n text_with_code_tag = self.format_line_html_text(html_text)\n\n if self.CODE_MARK not in text_with_code_tag:\n return []\n\n code_index_start = 0\n soup = BeautifulSoup(html_text, 'lxml')\n code_tag = soup.find_all(name=['pre', 'blockquote'])\n code_count = text_with_code_tag.count(self.CODE_MARK)\n code_list = []\n for code_index in range(code_index_start, code_index_start + code_count):\n code = code_tag[code_index].get_text()\n if code:\n code_list.append(code)\n return code_list",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"BeautifulSoup"
],
"field_dependencies": [
"self.CODE_MARK"
],
"method_dependencies": [
"format_line_html_text"
]
}
}
] | HtmlUtil | [
"HtmlUtilTestFormatLineFeed",
"HtmlUtilTestFormatLineHtmlText",
"HtmlUtilTestExtractCodeFromHtmlText",
"HtmlUtilTest"
] | class HtmlUtil:
def __init__(self):
"""
Initialize a series of labels
"""
self.SPACE_MARK = '-SPACE-'
self.JSON_MARK = '-JSON-'
self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-'
self.URL_MARK = '-URL-'
self.NUMBER_MARK = '-NUMBER-'
self.TRACE_MARK = '-TRACE-'
self.COMMAND_MARK = '-COMMAND-'
self.COMMENT_MARK = '-COMMENT-'
self.CODE_MARK = '-CODE-'
| [
"self.CODE_MARK",
"self.COMMAND_MARK",
"self.COMMENT_MARK",
"self.JSON_MARK",
"self.MARKUP_LANGUAGE_MARK",
"self.NUMBER_MARK",
"self.SPACE_MARK",
"self.TRACE_MARK",
"self.URL_MARK"
] |
ClassEval_45 | from PIL import Image, ImageEnhance
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
"""
Initialize self.image
"""
self.image = None
def load_image(self, image_path):
"""
Use Image util in PIL to open a image
:param image_path: str, path of image that is to be
>>> processor.load_image('test.jpg')
>>> processor.image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=3072x4096 at 0x194F2412A48>
"""
def save_image(self, save_path):
"""
Save image to a path if image has opened
:param save_path: str, the path that the image will be saved
>>> processor.load_image('test.jpg')
>>> processor.save_image('test2.jpg')
"""
def resize_image(self, width, height):
"""
Risize the image if image has opened.
:param width: int, the target width of image
:param height: int, the target height of image
>>> processor.load_image('test.jpg')
>>> processor.resize_image(300, 300)
>>> processor.image.width
300
>>> processor.image.height
300
"""
def rotate_image(self, degrees):
"""
rotate image if image has opened
:param degrees: float, the degrees that the image will be rotated
>>> processor.load_image('test.jpg')
>>> processor.resize_image(90)
"""
def adjust_brightness(self, factor):
"""
Adjust the brightness of image if image has opened.
:param factor: float, brightness of an image. A factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
>>> processor.load_image('test.jpg')
>>> processor.adjust_brightness(0.5)
""" | import unittest
import os
class ImageProcessorTestLoadImage(unittest.TestCase):
def setUp(self):
self.processor = ImageProcessor()
self.image_path = os.path.join(os.path.dirname(__file__), "test.png")
image = Image.new("RGB", (100, 100), (255, 255, 255))
image.save(self.image_path)
def tearDown(self):
self.processor.image.close()
# if os.path.exists(self.image_path):
# os.remove(self.image_path)
def test_load_image(self):
self.processor.load_image(self.image_path)
self.assertIsNotNone(self.processor.image)
def test_load_image_2(self):
self.processor.load_image(self.image_path)
self.assertEqual(self.processor.image.size, (100, 100))
def test_load_image_3(self):
self.processor.load_image(self.image_path)
self.assertEqual(self.processor.image.mode, "RGB")
def test_load_image_4(self):
self.processor.load_image(self.image_path)
self.assertEqual(self.processor.image.format, "PNG")
def test_load_image_5(self):
self.processor.load_image(self.image_path)
self.assertEqual(self.processor.image.filename, self.image_path)
class ImageProcessorTestSaveImage(unittest.TestCase):
def setUp(self):
self.processor = ImageProcessor()
self.image_path = os.path.join(os.path.dirname(__file__), "test.png")
image = Image.new("RGB", (100, 100), (255, 255, 255))
image.save(self.image_path)
def tearDown(self):
self.processor.image.close()
def test_save_image(self):
save_path = os.path.join(os.path.dirname(__file__), "test_save.png")
self.processor.load_image(self.image_path)
self.processor.save_image(save_path)
saved_image = Image.open(save_path)
self.assertIsNotNone(saved_image)
def test_save_image_2(self):
save_path = os.path.join(os.path.dirname(__file__), "test_save.png")
self.processor.load_image(self.image_path)
self.processor.save_image(save_path)
saved_image = Image.open(save_path)
self.assertEqual(saved_image.size, (100, 100))
def test_save_image_3(self):
save_path = os.path.join(os.path.dirname(__file__), "test_save.png")
self.processor.load_image(self.image_path)
self.processor.save_image(save_path)
saved_image = Image.open(save_path)
self.assertEqual(saved_image.mode, "RGB")
def test_save_image_4(self):
save_path = os.path.join(os.path.dirname(__file__), "test_save.png")
self.processor.load_image(self.image_path)
self.processor.save_image(save_path)
saved_image = Image.open(save_path)
self.assertEqual(saved_image.format, "PNG")
def test_save_image_5(self):
save_path = os.path.join(os.path.dirname(__file__), "test_save.png")
self.processor.load_image(self.image_path)
self.processor.save_image(save_path)
saved_image = Image.open(save_path)
self.assertEqual(saved_image.filename, save_path)
class ImageProcessorTestResizeImage(unittest.TestCase):
def setUp(self):
self.processor = ImageProcessor()
self.image_path = os.path.join(os.path.dirname(__file__), "test.png")
image = Image.new("RGB", (100, 100), (255, 255, 255))
image.save(self.image_path)
def tearDown(self):
self.processor.image.close()
def test_resize_image(self):
self.processor.load_image(self.image_path)
self.processor.resize_image(30, 15)
self.assertEqual(self.processor.image.size, (30, 15))
def test_resize_image_2(self):
self.processor.load_image(self.image_path)
self.processor.resize_image(30, 15)
self.assertEqual(self.processor.image.mode, "RGB")
def test_resize_image_3(self):
self.processor.load_image(self.image_path)
self.processor.resize_image(30, 15)
self.assertEqual(self.processor.image.format, None)
def test_resize_image_4(self):
self.processor.load_image(self.image_path)
self.processor.resize_image(40, 20)
self.assertEqual(self.processor.image.mode, "RGB")
def test_resize_image_5(self):
self.processor.load_image(self.image_path)
self.processor.resize_image(50, 25)
self.assertEqual(self.processor.image.format, None)
class ImageProcessorTestRotateImage(unittest.TestCase):
def setUp(self):
self.processor = ImageProcessor()
self.image_path = os.path.join(os.path.dirname(__file__), "test.png")
image = Image.new("RGB", (100, 100), (255, 255, 255))
image.save(self.image_path)
def tearDown(self):
self.processor.image.close()
def test_rotate_image(self):
self.processor.load_image(self.image_path)
original_image = self.processor.image
self.processor.rotate_image(90)
self.assertTrue(ImageChops.difference(original_image.rotate(90), self.processor.image).getbbox() is None)
def test_rotate_image_2(self):
self.processor.load_image(self.image_path)
original_image = self.processor.image
self.processor.rotate_image(180)
self.assertTrue(ImageChops.difference(original_image.rotate(180), self.processor.image).getbbox() is None)
def test_rotate_image_3(self):
self.processor.load_image(self.image_path)
original_image = self.processor.image
self.processor.rotate_image(270)
self.assertTrue(ImageChops.difference(original_image.rotate(270), self.processor.image).getbbox() is None)
def test_rotate_image_4(self):
self.processor.load_image(self.image_path)
original_image = self.processor.image
self.processor.rotate_image(360)
self.assertTrue(ImageChops.difference(original_image.rotate(360), self.processor.image).getbbox() is None)
def test_rotate_image_5(self):
self.processor.load_image(self.image_path)
original_image = self.processor.image
self.processor.rotate_image(45)
self.assertTrue(ImageChops.difference(original_image.rotate(45), self.processor.image).getbbox() is None)
class ImageProcessorTestAdjustBrightness(unittest.TestCase):
def setUp(self):
self.processor = ImageProcessor()
self.image_path = os.path.join(os.path.dirname(__file__), "test.png")
image = Image.new("RGB", (100, 100), (255, 255, 255))
image.save(self.image_path)
def tearDown(self):
self.processor.image.close()
def test_adjust_brightness(self):
self.processor.load_image(self.image_path)
enhancer = ImageEnhance.Brightness(Image.open(self.image_path))
expected_image = enhancer.enhance(0.3)
self.processor.adjust_brightness(0.3)
self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)
def test_adjust_brightness_2(self):
self.processor.load_image(self.image_path)
enhancer = ImageEnhance.Brightness(Image.open(self.image_path))
expected_image = enhancer.enhance(0.5)
self.processor.adjust_brightness(0.5)
self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)
def test_adjust_brightness_3(self):
self.processor.load_image(self.image_path)
enhancer = ImageEnhance.Brightness(Image.open(self.image_path))
expected_image = enhancer.enhance(0.7)
self.processor.adjust_brightness(0.7)
self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)
def test_adjust_brightness_4(self):
self.processor.load_image(self.image_path)
enhancer = ImageEnhance.Brightness(Image.open(self.image_path))
expected_image = enhancer.enhance(1.0)
self.processor.adjust_brightness(1.0)
self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)
def test_adjust_brightness_5(self):
self.processor.load_image(self.image_path)
enhancer = ImageEnhance.Brightness(Image.open(self.image_path))
expected_image = enhancer.enhance(1.5)
self.processor.adjust_brightness(1.5)
self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)
class ImageProcessorTestMain(unittest.TestCase):
def setUp(self):
self.processor = ImageProcessor()
self.image_path = os.path.join(os.path.dirname(__file__), "test.png")
image = Image.new("RGB", (100, 100), (255, 255, 255))
image.save(self.image_path)
def tearDown(self):
self.processor.image.close()
def test_main(self):
self.processor.load_image(self.image_path)
self.assertIsNotNone(self.processor.image)
enhancer = ImageEnhance.Brightness(Image.open(self.image_path))
expected_image = enhancer.enhance(0.4)
self.processor.adjust_brightness(0.4)
self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)
self.processor.resize_image(30, 15)
self.assertEqual(self.processor.image.size, (30, 15))
original_image = self.processor.image
self.processor.rotate_image(90)
self.assertTrue(ImageChops.difference(original_image.rotate(90), self.processor.image).getbbox() is None)
save_path = os.path.join(os.path.dirname(__file__), "test_save.png")
self.processor.save_image(save_path)
saved_image = Image.open(save_path)
self.assertIsNotNone(saved_image)
saved_image.close() | from PIL import Image, ImageEnhance, ImageChops
class ImageProcessor:
def __init__(self):
self.image = None
def load_image(self, image_path):
self.image = Image.open(image_path)
def save_image(self, save_path):
if self.image:
self.image.save(save_path)
def resize_image(self, width, height):
if self.image:
self.image = self.image.resize((width, height))
def rotate_image(self, degrees):
if self.image:
self.image = self.image.rotate(degrees)
def adjust_brightness(self, factor):
if self.image:
enhancer = ImageEnhance.Brightness(self.image)
self.image = enhancer.enhance(factor) | [
"from PIL import Image, ImageEnhance, ImageChops"
] | """
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
| [
{
"method_name": "load_image",
"method_description": "def load_image(self, image_path):\n \"\"\"\n Use Image util in PIL to open a image\n :param image_path: str, path of image that is to be\n >>> processor.load_image('test.jpg')\n >>> processor.image\n <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=3072x4096 at 0x194F2412A48>\n \"\"\"",
"test_class": "ImageProcessorTestLoadImage",
"test_code": "class ImageProcessorTestLoadImage(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n # if os.path.exists(self.image_path):\n # os.remove(self.image_path)\n\n def test_load_image(self):\n self.processor.load_image(self.image_path)\n self.assertIsNotNone(self.processor.image)\n\n def test_load_image_2(self):\n self.processor.load_image(self.image_path)\n self.assertEqual(self.processor.image.size, (100, 100))\n\n def test_load_image_3(self):\n self.processor.load_image(self.image_path)\n self.assertEqual(self.processor.image.mode, \"RGB\")\n\n def test_load_image_4(self):\n self.processor.load_image(self.image_path)\n self.assertEqual(self.processor.image.format, \"PNG\")\n\n def test_load_image_5(self):\n self.processor.load_image(self.image_path)\n self.assertEqual(self.processor.image.filename, self.image_path)",
"solution_code": "def load_image(self, image_path):\n self.image = Image.open(image_path)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.image"
],
"method_dependencies": []
}
},
{
"method_name": "save_image",
"method_description": "def save_image(self, save_path):\n \"\"\"\n Save image to a path if image has opened\n :param save_path: str, the path that the image will be saved\n >>> processor.load_image('test.jpg')\n >>> processor.save_image('test2.jpg')\n \"\"\"",
"test_class": "ImageProcessorTestSaveImage",
"test_code": "class ImageProcessorTestSaveImage(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n\n def test_save_image(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertIsNotNone(saved_image)\n\n def test_save_image_2(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertEqual(saved_image.size, (100, 100))\n\n def test_save_image_3(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertEqual(saved_image.mode, \"RGB\")\n\n def test_save_image_4(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertEqual(saved_image.format, \"PNG\")\n\n def test_save_image_5(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertEqual(saved_image.filename, save_path)",
"solution_code": "def save_image(self, save_path):\n if self.image:\n self.image.save(save_path)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.image"
],
"method_dependencies": []
}
},
{
"method_name": "resize_image",
"method_description": "def resize_image(self, width, height):\n \"\"\"\n Risize the image if image has opened.\n :param width: int, the target width of image\n :param height: int, the target height of image\n >>> processor.load_image('test.jpg')\n >>> processor.resize_image(300, 300)\n >>> processor.image.width\n 300\n >>> processor.image.height\n 300\n \"\"\"",
"test_class": "ImageProcessorTestResizeImage",
"test_code": "class ImageProcessorTestResizeImage(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n\n def test_resize_image(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(30, 15)\n self.assertEqual(self.processor.image.size, (30, 15))\n\n def test_resize_image_2(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(30, 15)\n self.assertEqual(self.processor.image.mode, \"RGB\")\n\n def test_resize_image_3(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(30, 15)\n self.assertEqual(self.processor.image.format, None)\n\n def test_resize_image_4(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(40, 20)\n self.assertEqual(self.processor.image.mode, \"RGB\")\n\n def test_resize_image_5(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(50, 25)\n self.assertEqual(self.processor.image.format, None)",
"solution_code": "def resize_image(self, width, height):\n if self.image:\n self.image = self.image.resize((width, height))",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.image"
],
"method_dependencies": []
}
},
{
"method_name": "rotate_image",
"method_description": "def rotate_image(self, degrees):\n \"\"\"\n rotate image if image has opened\n :param degrees: float, the degrees that the image will be rotated\n >>> processor.load_image('test.jpg')\n >>> processor.resize_image(90)\n \"\"\"",
"test_class": "ImageProcessorTestRotateImage",
"test_code": "class ImageProcessorTestRotateImage(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n\n def test_rotate_image(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(90)\n self.assertTrue(ImageChops.difference(original_image.rotate(90), self.processor.image).getbbox() is None)\n\n def test_rotate_image_2(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(180)\n self.assertTrue(ImageChops.difference(original_image.rotate(180), self.processor.image).getbbox() is None)\n\n def test_rotate_image_3(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(270)\n self.assertTrue(ImageChops.difference(original_image.rotate(270), self.processor.image).getbbox() is None)\n\n def test_rotate_image_4(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(360)\n self.assertTrue(ImageChops.difference(original_image.rotate(360), self.processor.image).getbbox() is None)\n\n def test_rotate_image_5(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(45)\n self.assertTrue(ImageChops.difference(original_image.rotate(45), self.processor.image).getbbox() is None)",
"solution_code": "def rotate_image(self, degrees):\n if self.image:\n self.image = self.image.rotate(degrees)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.image"
],
"method_dependencies": []
}
},
{
"method_name": "adjust_brightness",
"method_description": "def adjust_brightness(self, factor):\n \"\"\"\n Adjust the brightness of image if image has opened.\n :param factor: float, brightness of an image. A factor of 0.0 gives a black image. A factor of 1.0 gives the original image.\n >>> processor.load_image('test.jpg')\n >>> processor.adjust_brightness(0.5)\n \"\"\"",
"test_class": "ImageProcessorTestAdjustBrightness",
"test_code": "class ImageProcessorTestAdjustBrightness(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n\n def test_adjust_brightness(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(0.3)\n self.processor.adjust_brightness(0.3)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n def test_adjust_brightness_2(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(0.5)\n self.processor.adjust_brightness(0.5)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n def test_adjust_brightness_3(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(0.7)\n self.processor.adjust_brightness(0.7)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n def test_adjust_brightness_4(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(1.0)\n self.processor.adjust_brightness(1.0)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n def test_adjust_brightness_5(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(1.5)\n self.processor.adjust_brightness(1.5)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)",
"solution_code": "def adjust_brightness(self, factor):\n if self.image:\n enhancer = ImageEnhance.Brightness(self.image)\n self.image = enhancer.enhance(factor)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.image"
],
"method_dependencies": []
}
}
] | ImageProcessor | [
"ImageProcessorTestLoadImage",
"ImageProcessorTestSaveImage",
"ImageProcessorTestResizeImage",
"ImageProcessorTestRotateImage",
"ImageProcessorTestAdjustBrightness",
"ImageProcessorTestMain"
] | class ImageProcessor:
def __init__(self):
"""
Initialize self.image
"""
self.image = None
| [
"self.image"
] |
ClassEval_46 | class Interpolation:
"""
This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data
"""
def __init__(self):
pass
@staticmethod
def interpolate_1d(x, y, x_interp):
"""
Linear interpolation of one-dimensional data
:param x: The x-coordinate of the data point, list.
:param y: The y-coordinate of the data point, list.
:param x_interp: The x-coordinate of the interpolation point, list.
:return: The y-coordinate of the interpolation point, list.
>>> interpolation = Interpolation()
>>> interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5])
[1.5, 2.5]
"""
@staticmethod
def interpolate_2d(x, y, z, x_interp, y_interp):
”“”
Linear interpolation of two-dimensional data
:param x: The x-coordinate of the data point, list.
:param y: The y-coordinate of the data point, list.
:param z: The z-coordinate of the data point, list.
:param x_interp: The x-coordinate of the interpolation point, list.
:param y_interp: The y-coordinate of the interpolation point, list.
:return: The z-coordinate of the interpolation point, list.
>>> interpolation = Interpolation()
>>> interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5], [1.5, 2.5])
[3.0, 7.0]
”“” | import unittest
class InterpolationTestInterpolate1d(unittest.TestCase):
def test_interpolate_1d(self):
interpolation = Interpolation()
self.assertEqual(interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5]), [1.5, 2.5])
def test_interpolate_1d_2(self):
interpolation = Interpolation()
self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 2, 5], [1.5, 2.5]), [1.1, 1.3])
def test_interpolate_1d_3(self):
interpolation = Interpolation()
self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 7, 5], [1.5, 2.5]), [1.6, 2.8])
def test_interpolate_1d_4(self):
interpolation = Interpolation()
self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 2, 5], [2, 3]), [1.2, 1.4])
def test_interpolate_1d_5(self):
interpolation = Interpolation()
self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 7, 5], [2, 3]), [2.2, 3.4])
def test_interpolate_1d_6(self):
interpolation = Interpolation()
self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 7, 5], []), [])
def test_interpolate_1d_7(self):
interpolation = Interpolation()
self.assertEqual(interpolation.interpolate_1d([], [], [[], []]), [])
class InterpolationTestInterpolate2d(unittest.TestCase):
def test_interpolate_2d(self):
interpolation = Interpolation()
self.assertEqual(
interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5],
[1.5, 2.5]), [3.0, 7.0])
def test_interpolate_2d_2(self):
interpolation = Interpolation()
self.assertEqual(
interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5], [3, 4]),
[4.5])
def test_interpolate_2d_3(self):
interpolation = Interpolation()
self.assertEqual(
interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [3, 4], [1.5, 2.5]),
[7.5])
def test_interpolate_2d_4(self):
interpolation = Interpolation()
self.assertEqual(
interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [3, 4], [3, 4]),
[9.0])
def test_interpolate_2d_5(self):
interpolation = Interpolation()
self.assertEqual(
interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5],
[1.5, 2.5]), [3.0, 7.0])
class InterpolationTestMain(unittest.TestCase):
def test_main(self):
interpolation = Interpolation()
self.assertEqual(interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5]), [1.5, 2.5])
self.assertEqual(
interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5],
[1.5, 2.5]), [3.0, 7.0]) | class Interpolation:
def __init__(self):
pass
@staticmethod
def interpolate_1d(x, y, x_interp):
y_interp = []
for xi in x_interp:
for i in range(len(x) - 1):
if x[i] <= xi <= x[i+1]:
yi = y[i] + (y[i+1] - y[i]) * (xi - x[i]) / (x[i+1] - x[i])
y_interp.append(yi)
break
return y_interp
@staticmethod
def interpolate_2d(x, y, z, x_interp, y_interp):
z_interp = []
for xi, yi in zip(x_interp, y_interp):
for i in range(len(x) - 1):
if x[i] <= xi <= x[i+1]:
for j in range(len(y) - 1):
if y[j] <= yi <= y[j+1]:
z00 = z[i][j]
z01 = z[i][j+1]
z10 = z[i+1][j]
z11 = z[i+1][j+1]
zi = (z00 * (x[i+1] - xi) * (y[j+1] - yi) +
z10 * (xi - x[i]) * (y[j+1] - yi) +
z01 * (x[i+1] - xi) * (yi - y[j]) +
z11 * (xi - x[i]) * (yi - y[j])) / ((x[i+1] - x[i]) * (y[j+1] - y[j]))
z_interp.append(zi)
break
break
return z_interp | [] | """
This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data
"""
| [
{
"method_name": "interpolate_1d",
"method_description": "def interpolate_1d(x, y, x_interp):\n \"\"\"\n Linear interpolation of one-dimensional data\n :param x: The x-coordinate of the data point, list.\n :param y: The y-coordinate of the data point, list.\n :param x_interp: The x-coordinate of the interpolation point, list.\n :return: The y-coordinate of the interpolation point, list.\n >>> interpolation = Interpolation()\n >>> interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5])\n [1.5, 2.5]\n\n \"\"\"",
"test_class": "InterpolationTestInterpolate1d",
"test_code": "class InterpolationTestInterpolate1d(unittest.TestCase):\n def test_interpolate_1d(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5]), [1.5, 2.5])\n\n def test_interpolate_1d_2(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 2, 5], [1.5, 2.5]), [1.1, 1.3])\n\n def test_interpolate_1d_3(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 7, 5], [1.5, 2.5]), [1.6, 2.8])\n\n def test_interpolate_1d_4(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 2, 5], [2, 3]), [1.2, 1.4])\n\n def test_interpolate_1d_5(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 7, 5], [2, 3]), [2.2, 3.4])\n\n def test_interpolate_1d_6(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 7, 5], []), [])\n\n def test_interpolate_1d_7(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([], [], [[], []]), [])",
"solution_code": "def interpolate_1d(x, y, x_interp):\n y_interp = []\n for xi in x_interp:\n for i in range(len(x) - 1):\n if x[i] <= xi <= x[i+1]:\n yi = y[i] + (y[i+1] - y[i]) * (xi - x[i]) / (x[i+1] - x[i])\n y_interp.append(yi)\n break\n return y_interp",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "interpolate_2d",
"method_description": "@staticmethod\n def interpolate_2d(x, y, z, x_interp, y_interp):\n ”“”\n Linear interpolation of two-dimensional data\n :param x: The x-coordinate of the data point, list.\n :param y: The y-coordinate of the data point, list.\n :param z: The z-coordinate of the data point, list.\n :param x_interp: The x-coordinate of the interpolation point, list.\n :param y_interp: The y-coordinate of the interpolation point, list.\n :return: The z-coordinate of the interpolation point, list.\n >>> interpolation = Interpolation()\n >>> interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5], [1.5, 2.5])\n [3.0, 7.0]\n\n ”“”",
"test_class": "InterpolationTestInterpolate2d",
"test_code": "class InterpolationTestInterpolate2d(unittest.TestCase):\n def test_interpolate_2d(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5],\n [1.5, 2.5]), [3.0, 7.0])\n\n def test_interpolate_2d_2(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5], [3, 4]),\n [4.5])\n\n def test_interpolate_2d_3(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [3, 4], [1.5, 2.5]),\n [7.5])\n\n def test_interpolate_2d_4(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [3, 4], [3, 4]),\n [9.0])\n\n def test_interpolate_2d_5(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5],\n [1.5, 2.5]), [3.0, 7.0])",
"solution_code": "@staticmethod\n def interpolate_2d(x, y, z, x_interp, y_interp):\n z_interp = []\n for xi, yi in zip(x_interp, y_interp):\n for i in range(len(x) - 1):\n if x[i] <= xi <= x[i+1]:\n for j in range(len(y) - 1):\n if y[j] <= yi <= y[j+1]:\n z00 = z[i][j]\n z01 = z[i][j+1]\n z10 = z[i+1][j]\n z11 = z[i+1][j+1]\n zi = (z00 * (x[i+1] - xi) * (y[j+1] - yi) +\n z10 * (xi - x[i]) * (y[j+1] - yi) +\n z01 * (x[i+1] - xi) * (yi - y[j]) +\n z11 * (xi - x[i]) * (yi - y[j])) / ((x[i+1] - x[i]) * (y[j+1] - y[j]))\n z_interp.append(zi)\n break\n break\n return z_interp",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | Interpolation | [
"InterpolationTestInterpolate1d",
"InterpolationTestInterpolate2d",
"InterpolationTestMain"
] | class Interpolation:
def __init__(self):
pass
| [] |
ClassEval_47 | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
"""
Initialize the IP address to the specified address
:param ip_address:string
"""
self.ip_address = ip_address
def is_valid(self):
"""
Judge whether the IP address is valid, that is, whether the IP address is composed of four Decimal digits separated by '.'. Each digit is greater than or equal to 0 and less than or equal to 255
:return: bool
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.is_valid()
True
"""
def get_octets(self):
"""
If the IP address is valid, the list of four decimal numbers separated by "." constituting the IP address is returned; otherwise, an empty list is returned
:return: list
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.get_octets()
["10", "10", "10", "10"]
"""
def get_binary(self):
"""
If the IP address is valid, return the binary form of the IP address; otherwise, return ''
:return: string
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.get_binary()
"00001010.00001010.00001010.00001010"
""" | import unittest
class IPAddressTestIsValid(unittest.TestCase):
def test_is_valid_1(self):
ipaddress = IPAddress("10.10.10.10")
self.assertEqual(ipaddress.is_valid(), True)
def test_is_valid_2(self):
ipaddress = IPAddress("-1.10.10.10")
self.assertEqual(ipaddress.is_valid(), False)
def test_is_valid_3(self):
ipaddress = IPAddress("10.10.10")
self.assertEqual(ipaddress.is_valid(), False)
def test_is_valid_4(self):
ipaddress = IPAddress("a.10.10.10")
self.assertEqual(ipaddress.is_valid(), False)
def test_is_valid_5(self):
ipaddress = IPAddress("300.10.10.10")
self.assertEqual(ipaddress.is_valid(), False)
class IPAddressTestGetOctets(unittest.TestCase):
def test_get_octets_1(self):
ipaddress = IPAddress("10.10.10.10")
self.assertEqual(ipaddress.get_octets(), ["10", "10", "10", "10"])
def test_get_octets_2(self):
ipaddress = IPAddress("a.10.10.10")
self.assertEqual(ipaddress.get_octets(), [])
def test_get_octets_3(self):
ipaddress = IPAddress("-1.10.10.10")
self.assertEqual(ipaddress.get_octets(), [])
def test_get_octets_4(self):
ipaddress = IPAddress("300.10.10.10")
self.assertEqual(ipaddress.get_octets(), [])
def test_get_octets_5(self):
ipaddress = IPAddress(".10.10.10")
self.assertEqual(ipaddress.get_octets(), [])
class IPAddressTestGetBinary(unittest.TestCase):
def test_get_binary_1(self):
ipaddress = IPAddress("10.10.10.10")
self.assertEqual(ipaddress.get_binary(), "00001010.00001010.00001010.00001010")
def test_get_binary_2(self):
ipaddress = IPAddress("a.10.10.10")
self.assertEqual(ipaddress.get_binary(), '')
def test_get_binary_3(self):
ipaddress = IPAddress("-1.10.10.10")
self.assertEqual(ipaddress.get_binary(), '')
def test_get_binary_4(self):
ipaddress = IPAddress("300.10.10.10")
self.assertEqual(ipaddress.get_binary(), '')
def test_get_binary_5(self):
ipaddress = IPAddress(".10.10.10")
self.assertEqual(ipaddress.get_binary(), '')
class IPAddressTest(unittest.TestCase):
def test_IPAddress(self):
ipaddress = IPAddress("10.10.10.10")
self.assertEqual(ipaddress.is_valid(), True)
self.assertEqual(ipaddress.get_octets(), ["10", "10", "10", "10"])
self.assertEqual(ipaddress.get_binary(), "00001010.00001010.00001010.00001010") | class IPAddress:
def __init__(self, ip_address):
self.ip_address = ip_address
def is_valid(self):
octets = self.ip_address.split('.')
if len(octets) != 4:
return False
for octet in octets:
if not octet.isdigit() or int(octet) < 0 or int(octet) > 255:
return False
return True
def get_octets(self):
if self.is_valid():
return self.ip_address.split('.')
else:
return []
def get_binary(self):
if self.is_valid():
binary_octets = []
for octet in self.get_octets():
binary_octets.append(format(int(octet), '08b'))
return '.'.join(binary_octets)
else:
return '' | [] | """
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
| [
{
"method_name": "is_valid",
"method_description": "def is_valid(self):\n \"\"\"\n Judge whether the IP address is valid, that is, whether the IP address is composed of four Decimal digits separated by '.'. Each digit is greater than or equal to 0 and less than or equal to 255\n :return: bool\n >>> ipaddress = IPAddress(\"10.10.10.10\")\n >>> ipaddress.is_valid()\n True\n \"\"\"",
"test_class": "IPAddressTestIsValid",
"test_code": "class IPAddressTestIsValid(unittest.TestCase):\n def test_is_valid_1(self):\n ipaddress = IPAddress(\"10.10.10.10\")\n self.assertEqual(ipaddress.is_valid(), True)\n\n def test_is_valid_2(self):\n ipaddress = IPAddress(\"-1.10.10.10\")\n self.assertEqual(ipaddress.is_valid(), False)\n\n def test_is_valid_3(self):\n ipaddress = IPAddress(\"10.10.10\")\n self.assertEqual(ipaddress.is_valid(), False)\n\n def test_is_valid_4(self):\n ipaddress = IPAddress(\"a.10.10.10\")\n self.assertEqual(ipaddress.is_valid(), False)\n\n def test_is_valid_5(self):\n ipaddress = IPAddress(\"300.10.10.10\")\n self.assertEqual(ipaddress.is_valid(), False)",
"solution_code": "def is_valid(self):\n octets = self.ip_address.split('.')\n if len(octets) != 4:\n return False\n for octet in octets:\n if not octet.isdigit() or int(octet) < 0 or int(octet) > 255:\n return False\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.ip_address"
],
"method_dependencies": []
}
},
{
"method_name": "get_octets",
"method_description": "def get_octets(self):\n \"\"\"\n If the IP address is valid, the list of four decimal numbers separated by \".\" constituting the IP address is returned; otherwise, an empty list is returned\n :return: list\n >>> ipaddress = IPAddress(\"10.10.10.10\")\n >>> ipaddress.get_octets()\n [\"10\", \"10\", \"10\", \"10\"]\n \"\"\"",
"test_class": "IPAddressTestGetOctets",
"test_code": "class IPAddressTestGetOctets(unittest.TestCase):\n def test_get_octets_1(self):\n ipaddress = IPAddress(\"10.10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [\"10\", \"10\", \"10\", \"10\"])\n\n def test_get_octets_2(self):\n ipaddress = IPAddress(\"a.10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [])\n\n def test_get_octets_3(self):\n ipaddress = IPAddress(\"-1.10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [])\n\n def test_get_octets_4(self):\n ipaddress = IPAddress(\"300.10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [])\n\n def test_get_octets_5(self):\n ipaddress = IPAddress(\".10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [])",
"solution_code": "def get_octets(self):\n if self.is_valid():\n return self.ip_address.split('.')\n else:\n return []",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.ip_address"
],
"method_dependencies": [
"is_valid"
]
}
},
{
"method_name": "get_binary",
"method_description": "def get_binary(self):\n \"\"\"\n If the IP address is valid, return the binary form of the IP address; otherwise, return ''\n :return: string\n >>> ipaddress = IPAddress(\"10.10.10.10\")\n >>> ipaddress.get_binary()\n \"00001010.00001010.00001010.00001010\"\n \"\"\"",
"test_class": "IPAddressTestGetBinary",
"test_code": "class IPAddressTestGetBinary(unittest.TestCase):\n def test_get_binary_1(self):\n ipaddress = IPAddress(\"10.10.10.10\")\n self.assertEqual(ipaddress.get_binary(), \"00001010.00001010.00001010.00001010\")\n\n def test_get_binary_2(self):\n ipaddress = IPAddress(\"a.10.10.10\")\n self.assertEqual(ipaddress.get_binary(), '')\n\n def test_get_binary_3(self):\n ipaddress = IPAddress(\"-1.10.10.10\")\n self.assertEqual(ipaddress.get_binary(), '')\n\n def test_get_binary_4(self):\n ipaddress = IPAddress(\"300.10.10.10\")\n self.assertEqual(ipaddress.get_binary(), '')\n\n def test_get_binary_5(self):\n ipaddress = IPAddress(\".10.10.10\")\n self.assertEqual(ipaddress.get_binary(), '')",
"solution_code": "def get_binary(self):\n if self.is_valid():\n binary_octets = []\n for octet in self.get_octets():\n binary_octets.append(format(int(octet), '08b'))\n return '.'.join(binary_octets)\n else:\n return ''",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"is_valid",
"get_octets"
]
}
}
] | IPAddress | [
"IPAddressTestIsValid",
"IPAddressTestGetOctets",
"IPAddressTestGetBinary",
"IPAddressTest"
] | class IPAddress:
def __init__(self, ip_address):
"""
Initialize the IP address to the specified address
:param ip_address:string
"""
self.ip_address = ip_address
| [
"self.ip_address"
] |
ClassEval_48 | import socket
import netifaces
class IpUtil:
"""
This is a class as tool for ip that can be used to obtain the local IP address, validate its validity, and also provides the functionality to retrieve the corresponding hostname.
"""
@staticmethod
def is_valid_ipv4(ip_address):
"""
Check if the given IP address is a valid IPv4 address.
:param ip_address: string, the IP address to check
:return: bool, True if the IP address is valid, False otherwise
>>> IpUtil.is_valid_ipv4('192.168.0.123')
True
>>> IpUtil.is_valid_ipv4('256.0.0.0')
False
"""
@staticmethod
def is_valid_ipv6(ip_address):
"""
Check if the given IP address is a valid IPv6 address.
:param ip_address:string, the IP address to check
:return:bool, True if the IP address is valid, False otherwise
>>> IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')
True
>>> IpUtil.is_valid_ipv6('2001:0db8:85a3:::8a2e:0370:7334')
False
"""
@staticmethod
def get_hostname(ip_address):
"""
Get the hostname associated with the given IP address.
:param ip_address:string, the IP address to get the hostname for
:return: string, the hostname associated with the IP address
>>> IpUtil.get_hostname('110.242.68.3')
'www.baidu.com'
>>> IpUtil.get_hostname('10.0.0.1')
""" | import unittest
class IpUtilTestIsValidIpv4(unittest.TestCase):
def test_is_valid_ipv4_1(self):
result = IpUtil.is_valid_ipv4('192.168.0.123')
self.assertEqual(result, True)
def test_is_valid_ipv4_2(self):
result = IpUtil.is_valid_ipv4('10.10.10.10')
self.assertEqual(result, True)
def test_is_valid_ipv4_3(self):
result = IpUtil.is_valid_ipv4('0.0.0.0')
self.assertEqual(result, True)
def test_is_valid_ipv4_4(self):
result = IpUtil.is_valid_ipv4('abc.168.0.123')
self.assertEqual(result, False)
def test_is_valid_ipv4_5(self):
result = IpUtil.is_valid_ipv4('256.0.0.0')
self.assertEqual(result, False)
class IpUtilTestIsValidIpv6(unittest.TestCase):
def test_is_valid_ipv6_1(self):
result = IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')
self.assertEqual(result, True)
def test_is_valid_ipv6_2(self):
result = IpUtil.is_valid_ipv6('2001:0db8:85a3:::8a2e:0370:7334')
self.assertEqual(result, False)
def test_is_valid_ipv6_3(self):
result = IpUtil.is_valid_ipv6('2001:0db8:85a3:2001:llll:8a2e:0370:7334')
self.assertEqual(result, False)
def test_is_valid_ipv6_4(self):
result = IpUtil.is_valid_ipv6('2001:0db8:85a3:llll:llll:8a2e:0370:7334')
self.assertEqual(result, False)
def test_is_valid_ipv6_5(self):
result = IpUtil.is_valid_ipv6('2001:0db8:85a3::llll:8a2e:0370:7334')
self.assertEqual(result, False)
class IpUtilTestGetHostname(unittest.TestCase):
def test_get_hostname_1(self):
result = IpUtil.get_hostname('110.242.68.3')
self.assertEqual(result, None)
def test_get_hostname_2(self):
result = IpUtil.get_hostname('10.0.0.1')
self.assertEqual(result, None)
def test_get_hostname_3(self):
result = IpUtil.get_hostname('0.0.0.0')
self.assertEqual(result, 'LAPTOP-2CS86KUM')
def test_get_hostname_4(self):
result = IpUtil.get_hostname('0.0.0.1')
self.assertEqual(result, None)
def test_get_hostname_5(self):
result = IpUtil.get_hostname('0.0.0.2')
self.assertEqual(result, None)
class IpUtilTest(unittest.TestCase):
def test_IpUtil(self):
result = IpUtil.is_valid_ipv4('192.168.0.123')
self.assertEqual(result, True)
result = IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')
self.assertEqual(result, True)
result = IpUtil.get_hostname('110.242.68.3')
self.assertEqual(result, None) | import socket
class IpUtil:
@staticmethod
def is_valid_ipv4(ip_address):
try:
socket.inet_pton(socket.AF_INET, ip_address)
return True
except socket.error:
return False
@staticmethod
def is_valid_ipv6(ip_address):
try:
socket.inet_pton(socket.AF_INET6, ip_address)
return True
except socket.error:
return False
@staticmethod
def get_hostname(ip_address):
try:
hostname = socket.gethostbyaddr(ip_address)[0]
return hostname
except socket.herror:
return None | [
"import socket"
] | """
This is a class as tool for ip that can be used to obtain the local IP address, validate its validity, and also provides the functionality to retrieve the corresponding hostname.
"""
| [
{
"method_name": "is_valid_ipv4",
"method_description": "def is_valid_ipv4(ip_address):\n \"\"\"\n Check if the given IP address is a valid IPv4 address.\n :param ip_address: string, the IP address to check\n :return: bool, True if the IP address is valid, False otherwise\n >>> IpUtil.is_valid_ipv4('192.168.0.123')\n True\n >>> IpUtil.is_valid_ipv4('256.0.0.0')\n False\n\n \"\"\"",
"test_class": "IpUtilTestIsValidIpv4",
"test_code": "class IpUtilTestIsValidIpv4(unittest.TestCase):\n def test_is_valid_ipv4_1(self):\n result = IpUtil.is_valid_ipv4('192.168.0.123')\n self.assertEqual(result, True)\n\n def test_is_valid_ipv4_2(self):\n result = IpUtil.is_valid_ipv4('10.10.10.10')\n self.assertEqual(result, True)\n\n def test_is_valid_ipv4_3(self):\n result = IpUtil.is_valid_ipv4('0.0.0.0')\n self.assertEqual(result, True)\n\n def test_is_valid_ipv4_4(self):\n result = IpUtil.is_valid_ipv4('abc.168.0.123')\n self.assertEqual(result, False)\n\n def test_is_valid_ipv4_5(self):\n result = IpUtil.is_valid_ipv4('256.0.0.0')\n self.assertEqual(result, False)",
"solution_code": "def is_valid_ipv4(ip_address):\n try:\n socket.inet_pton(socket.AF_INET, ip_address)\n return True\n except socket.error:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"socket"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "is_valid_ipv6",
"method_description": "@staticmethod\n def is_valid_ipv6(ip_address):\n \"\"\"\n Check if the given IP address is a valid IPv6 address.\n :param ip_address:string, the IP address to check\n :return:bool, True if the IP address is valid, False otherwise\n >>> IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')\n True\n >>> IpUtil.is_valid_ipv6('2001:0db8:85a3:::8a2e:0370:7334')\n False\n\n \"\"\"",
"test_class": "IpUtilTestIsValidIpv6",
"test_code": "class IpUtilTestIsValidIpv6(unittest.TestCase):\n def test_is_valid_ipv6_1(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')\n self.assertEqual(result, True)\n\n def test_is_valid_ipv6_2(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3:::8a2e:0370:7334')\n self.assertEqual(result, False)\n\n def test_is_valid_ipv6_3(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3:2001:llll:8a2e:0370:7334')\n self.assertEqual(result, False)\n\n def test_is_valid_ipv6_4(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3:llll:llll:8a2e:0370:7334')\n self.assertEqual(result, False)\n\n def test_is_valid_ipv6_5(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3::llll:8a2e:0370:7334')\n self.assertEqual(result, False)",
"solution_code": "@staticmethod\n def is_valid_ipv6(ip_address):\n try:\n socket.inet_pton(socket.AF_INET6, ip_address)\n return True\n except socket.error:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"socket"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "get_hostname",
"method_description": "@staticmethod\n def get_hostname(ip_address):\n \"\"\"\n Get the hostname associated with the given IP address.\n :param ip_address:string, the IP address to get the hostname for\n :return: string, the hostname associated with the IP address\n >>> IpUtil.get_hostname('110.242.68.3')\n 'www.baidu.com'\n >>> IpUtil.get_hostname('10.0.0.1')\n\n \"\"\"",
"test_class": "IpUtilTestGetHostname",
"test_code": "class IpUtilTestGetHostname(unittest.TestCase):\n def test_get_hostname_1(self):\n result = IpUtil.get_hostname('110.242.68.3')\n self.assertEqual(result, None)\n\n def test_get_hostname_2(self):\n result = IpUtil.get_hostname('10.0.0.1')\n self.assertEqual(result, None)\n\n def test_get_hostname_3(self):\n result = IpUtil.get_hostname('0.0.0.0')\n self.assertEqual(result, 'LAPTOP-2CS86KUM')\n\n def test_get_hostname_4(self):\n result = IpUtil.get_hostname('0.0.0.1')\n self.assertEqual(result, None)\n\n def test_get_hostname_5(self):\n result = IpUtil.get_hostname('0.0.0.2')\n self.assertEqual(result, None)",
"solution_code": "@staticmethod\n def get_hostname(ip_address):\n try:\n hostname = socket.gethostbyaddr(ip_address)[0]\n return hostname\n except socket.herror:\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"socket"
],
"field_dependencies": [],
"method_dependencies": []
}
}
] | IpUtil | [
"IpUtilTestIsValidIpv4",
"IpUtilTestIsValidIpv6",
"IpUtilTestGetHostname",
"IpUtilTest"
] | class IpUtil:
| [] |
ClassEval_49 | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(self, job_title, company, requirements):
"""
This function is used to publish positions,and add the position information to the job_listings list.
:param job_title: The title of the position,str.
:param company: The company of the position,str.
:param requirements: The requirements of the position,list.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
>>> jobMarketplace.job_listings
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]
"""
def remove_job(self, job):
"""
This function is used to remove positions,and remove the position information from the job_listings list.
:param job: The position information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}]
>>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])
>>> jobMarketplace.job_listings
[]
"""
def submit_resume(self, name, skills, experience):
"""
This function is used to submit resumes,and add the resume information to the resumes list.
:param name: The name of the resume,str.
:param skills: The skills of the resume,list.
:param experience: The experience of the resume,str.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
>>> jobMarketplace.resumes
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
def withdraw_resume(self, resume):
"""
This function is used to withdraw resumes,and remove the resume information from the resumes list.
:param resume: The resume information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
>>> jobMarketplace.resumes
[]
"""
def search_jobs(self, criteria):
"""
This function is used to search for positions,and return the position information that meets the requirements.
:param criteria: The requirements of the position,str.
:return: The position information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.search_jobs("skill1")
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]
"""
def get_job_applicants(self, job):
"""
This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.
:param job: The position information,dict.
:return: The candidate information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
""" | import unittest
class JobMarketplaceTestPostJob(unittest.TestCase):
def test_post_job(self):
jobMarketplace = JobMarketplace()
jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])
def test_post_job_2(self):
jobMarketplace = JobMarketplace()
jobMarketplace.post_job("Mechanical Engineer", "XYZ Company", ['requirement3', 'requirement4'])
self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])
def test_post_job_3(self):
jobMarketplace = JobMarketplace()
jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
jobMarketplace.post_job("Mechanical Engineer", "XYZ Company", ['requirement3', 'requirement4'])
self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])
def test_post_job_4(self):
jobMarketplace = JobMarketplace()
jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
jobMarketplace.post_job("Mechanical Engineer", "XYZ Company", ['requirement3', 'requirement4'])
jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}, {'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])
def test_post_job_5(self):
jobMarketplace = JobMarketplace()
jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
jobMarketplace.post_job("Mechanical Engineer", "XYZ Company", ['requirement3', 'requirement4'])
jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
jobMarketplace.post_job("Mechanical Engineer", "XYZ Company", ['requirement3', 'requirement4'])
self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}, {'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])
class JobMarketplaceTestRemoveJob(unittest.TestCase):
def test_remove_job(self):
jobMarketplace = JobMarketplace()
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}]
jobMarketplace.remove_job(jobMarketplace.job_listings[0])
self.assertEqual(jobMarketplace.job_listings, [])
def test_remove_job_2(self):
jobMarketplace = JobMarketplace()
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}, {"job_title": "Mechanical Engineer", "company": "XYZ Company", "requirements": ['requirement3', 'requirement4']}]
jobMarketplace.remove_job(jobMarketplace.job_listings[0])
self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])
def test_remove_job_3(self):
jobMarketplace = JobMarketplace()
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}, {"job_title": "Mechanical Engineer", "company": "XYZ Company", "requirements": ['requirement3', 'requirement4']}]
jobMarketplace.remove_job(jobMarketplace.job_listings[0])
jobMarketplace.remove_job(jobMarketplace.job_listings[0])
self.assertEqual(jobMarketplace.job_listings, [])
def test_remove_job_4(self):
jobMarketplace = JobMarketplace()
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}, {"job_title": "Mechanical Engineer", "company": "XYZ Company", "requirements": ['requirement3', 'requirement4']}, {"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}]
jobMarketplace.remove_job(jobMarketplace.job_listings[0])
jobMarketplace.remove_job(jobMarketplace.job_listings[0])
self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])
def test_remove_job_5(self):
jobMarketplace = JobMarketplace()
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company",
"requirements": ['requirement1', 'requirement2']},
{"job_title": "Mechanical Engineer", "company": "XYZ Company",
"requirements": ['requirement3', 'requirement4']},
{"job_title": "Software Engineer", "company": "ABC Company",
"requirements": ['requirement1', 'requirement2']}]
jobMarketplace.remove_job(jobMarketplace.job_listings[0])
self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}, {'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])
class JobMarketplaceTestSubmitResume(unittest.TestCase):
def test_submit_resume(self):
jobMarketplace = JobMarketplace()
jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])
def test_submit_resume_2(self):
jobMarketplace = JobMarketplace()
jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
jobMarketplace.submit_resume("John", ['skill3', 'skill4'], "experience")
self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])
def test_submit_resume_3(self):
jobMarketplace = JobMarketplace()
jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
jobMarketplace.submit_resume("John", ['skill3', 'skill4'], "experience")
jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])
def test_submit_resume_4(self):
jobMarketplace = JobMarketplace()
jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
jobMarketplace.submit_resume("John", ['skill3', 'skill4'], "experience")
jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
jobMarketplace.submit_resume("John", ['skill3', 'skill4'], "experience")
self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])
def test_submit_resume_5(self):
jobMarketplace = JobMarketplace()
jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
jobMarketplace.submit_resume("John", ['skill3', 'skill4'], "experience")
jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
jobMarketplace.submit_resume("John", ['skill3', 'skill4'], "experience")
jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])
class JobMarketplaceTestWithdrawResume(unittest.TestCase):
def test_withdraw_resume(self):
jobMarketplace = JobMarketplace()
jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
self.assertEqual(jobMarketplace.resumes, [])
def test_withdraw_resume_2(self):
jobMarketplace = JobMarketplace()
jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}, {"name": "John", "skills": ['skill3', 'skill4'], "experience": "experience"}]
jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
self.assertEqual(jobMarketplace.resumes, [{'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])
def test_withdraw_resume_3(self):
jobMarketplace = JobMarketplace()
jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}, {"name": "John", "skills": ['skill3', 'skill4'], "experience": "experience"}]
jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
self.assertEqual(jobMarketplace.resumes, [])
def test_withdraw_resume_4(self):
jobMarketplace = JobMarketplace()
jobMarketplace.resumes = [{"name": "Amy", "skills": ['skill3', 'skill2'], "experience": "experience"}, {"name": "John", "skills": ['skill3', 'skill4'], "experience": "experience"}]
jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
self.assertEqual(jobMarketplace.resumes, [])
def test_withdraw_resume_5(self):
jobMarketplace = JobMarketplace()
jobMarketplace.resumes = [{"name": "Amy", "skills": ['skill1', 'skill2'], "experience": "experience"}, {"name": "John", "skills": ['skill3', 'skill4'], "experience": "experience"}]
jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
self.assertEqual(jobMarketplace.resumes, [{'experience': 'experience', 'name': 'John', 'skills': ['skill3', 'skill4']}])
class JobMarketplaceTestSearchJobs(unittest.TestCase):
def test_search_jobs(self):
jobMarketplace = JobMarketplace()
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
self.assertEqual(jobMarketplace.search_jobs("skill1"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}])
def test_search_jobs_2(self):
jobMarketplace = JobMarketplace()
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}, {"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill3', 'skill4']}]
self.assertEqual(jobMarketplace.search_jobs("skill1"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}])
def test_search_jobs_3(self):
jobMarketplace = JobMarketplace()
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}, {"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill3', 'skill4']}]
self.assertEqual(jobMarketplace.search_jobs("skill3"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill3', 'skill4']}])
def test_search_jobs_4(self):
jobMarketplace = JobMarketplace()
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}, {"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill3', 'skill4']}]
self.assertEqual(jobMarketplace.search_jobs("skill5"), [])
def test_search_jobs_5(self):
jobMarketplace = JobMarketplace()
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}, {"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill3', 'skill4']}]
self.assertEqual(jobMarketplace.search_jobs("skill6"), [])
class JobMarketplaceTestGetJobApplicants(unittest.TestCase):
def test_get_job_applicants(self):
jobMarketplace = JobMarketplace()
jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])
def test_get_job_applicants_2(self):
jobMarketplace = JobMarketplace()
jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}, {"name": "John", "skills": ['skill3', 'skill4'], "experience": "experience"}]
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])
def test_get_job_applicants_3(self):
jobMarketplace = JobMarketplace()
jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}, {"name": "John", "skills": ['skill3', 'skill4'], "experience": "experience"}]
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill3', 'skill4']}]
self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])
def test_get_job_applicants_4(self):
jobMarketplace = JobMarketplace()
jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}, {"name": "John", "skills": ['skill3', 'skill4'], "experience": "experience"}]
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill5', 'skill6']}]
self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [])
def test_get_job_applicants_5(self):
jobMarketplace = JobMarketplace()
jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}, {"name": "John", "skills": ['skill3', 'skill4'], "experience": "experience"}]
jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill6', 'skill7']}]
self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [])
class JobMarketplaceTestMatchesRequirements(unittest.TestCase):
def test_matches_requirements(self):
jobMarketplace = JobMarketplace()
self.assertEqual(jobMarketplace.matches_requirements({"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}, ['skill1', 'skill2']), True)
def test_matches_requirements_2(self):
jobMarketplace = JobMarketplace()
self.assertEqual(jobMarketplace.matches_requirements({"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}, ['skill3', 'skill4']), False)
def test_matches_requirements_3(self):
jobMarketplace = JobMarketplace()
self.assertEqual(jobMarketplace.matches_requirements({"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}, ['skill5', 'skill6']), False)
def test_matches_requirements_4(self):
jobMarketplace = JobMarketplace()
self.assertEqual(jobMarketplace.matches_requirements({"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}, ['skill1', 'skill3']), False)
def test_matches_requirements_5(self):
jobMarketplace = JobMarketplace()
self.assertEqual(jobMarketplace.matches_requirements({"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}, ['skill1']), False)
class JobMarketplaceTestMain(unittest.TestCase):
def test_main(self):
jobMarketplace = JobMarketplace()
jobMarketplace.post_job("Software Engineer", "ABC Company", ['skill1', 'skill2'])
jobMarketplace.post_job("Mechanical Engineer", "XYZ Company", ['skill3', 'skill4'])
self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['skill3', 'skill4']}])
jobMarketplace.remove_job(jobMarketplace.job_listings[1])
self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}])
jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])
jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
self.assertEqual(jobMarketplace.resumes, [])
self.assertEqual(jobMarketplace.search_jobs("skill1"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}])
jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])
self.assertEqual(jobMarketplace.matches_requirements({"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}, ['skill1', 'skill2']), True) | class JobMarketplace:
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(self, job_title, company, requirements):
# requirements = ['requirement1', 'requirement2']
job = {"job_title": job_title, "company": company, "requirements": requirements}
self.job_listings.append(job)
def remove_job(self, job):
self.job_listings.remove(job)
def submit_resume(self, name, skills, experience):
resume = {"name": name, "skills": skills, "experience": experience}
self.resumes.append(resume)
def withdraw_resume(self, resume):
self.resumes.remove(resume)
def search_jobs(self, criteria):
matching_jobs = []
for job_listing in self.job_listings:
if criteria.lower() in job_listing["job_title"].lower() or criteria.lower() in [r.lower() for r in job_listing["requirements"]]:
matching_jobs.append(job_listing)
return matching_jobs
def get_job_applicants(self, job):
applicants = []
for resume in self.resumes:
if self.matches_requirements(resume, job["requirements"]):
applicants.append(resume)
return applicants
@staticmethod
def matches_requirements(resume, requirements):
for skill in resume["skills"]:
if skill not in requirements:
return False
return True | [] | """
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
| [
{
"method_name": "post_job",
"method_description": "def post_job(self, job_title, company, requirements):\n \"\"\"\n This function is used to publish positions,and add the position information to the job_listings list.\n :param job_title: The title of the position,str.\n :param company: The company of the position,str.\n :param requirements: The requirements of the position,list.\n :return: None\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n >>> jobMarketplace.job_listings\n [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]\n\n \"\"\"",
"test_class": "JobMarketplaceTestPostJob",
"test_code": "class JobMarketplaceTestPostJob(unittest.TestCase):\n def test_post_job(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])\n\n def test_post_job_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])\n\n def test_post_job_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])\n\n def test_post_job_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}, {'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])\n\n def test_post_job_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}, {'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])",
"solution_code": "def post_job(self, job_title, company, requirements):\n # requirements = ['requirement1', 'requirement2']\n job = {\"job_title\": job_title, \"company\": company, \"requirements\": requirements}\n self.job_listings.append(job)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.job_listings"
],
"method_dependencies": []
}
},
{
"method_name": "remove_job",
"method_description": "def remove_job(self, job):\n \"\"\"\n This function is used to remove positions,and remove the position information from the job_listings list.\n :param job: The position information to be removed,dict.\n :return: None\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}]\n >>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n >>> jobMarketplace.job_listings\n []\n\n \"\"\"",
"test_class": "JobMarketplaceTestRemoveJob",
"test_code": "class JobMarketplaceTestRemoveJob(unittest.TestCase):\n def test_remove_job(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [])\n\n def test_remove_job_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}, {\"job_title\": \"Mechanical Engineer\", \"company\": \"XYZ Company\", \"requirements\": ['requirement3', 'requirement4']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])\n\n def test_remove_job_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}, {\"job_title\": \"Mechanical Engineer\", \"company\": \"XYZ Company\", \"requirements\": ['requirement3', 'requirement4']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [])\n\n def test_remove_job_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}, {\"job_title\": \"Mechanical Engineer\", \"company\": \"XYZ Company\", \"requirements\": ['requirement3', 'requirement4']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])\n\n def test_remove_job_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\",\n \"requirements\": ['requirement1', 'requirement2']},\n {\"job_title\": \"Mechanical Engineer\", \"company\": \"XYZ Company\",\n \"requirements\": ['requirement3', 'requirement4']},\n {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\",\n \"requirements\": ['requirement1', 'requirement2']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}, {'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])",
"solution_code": "def remove_job(self, job):\n self.job_listings.remove(job)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.job_listings"
],
"method_dependencies": []
}
},
{
"method_name": "submit_resume",
"method_description": "def submit_resume(self, name, skills, experience):\n \"\"\"\n This function is used to submit resumes,and add the resume information to the resumes list.\n :param name: The name of the resume,str.\n :param skills: The skills of the resume,list.\n :param experience: The experience of the resume,str.\n :return: None\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n >>> jobMarketplace.resumes\n [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]\n\n \"\"\"",
"test_class": "JobMarketplaceTestSubmitResume",
"test_code": "class JobMarketplaceTestSubmitResume(unittest.TestCase):\n def test_submit_resume(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n\n def test_submit_resume_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])\n\n def test_submit_resume_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n\n def test_submit_resume_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])\n\n def test_submit_resume_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])",
"solution_code": "def submit_resume(self, name, skills, experience):\n resume = {\"name\": name, \"skills\": skills, \"experience\": experience}\n self.resumes.append(resume)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.resumes"
],
"method_dependencies": []
}
},
{
"method_name": "withdraw_resume",
"method_description": "def withdraw_resume(self, resume):\n \"\"\"\n This function is used to withdraw resumes,and remove the resume information from the resumes list.\n :param resume: The resume information to be removed,dict.\n :return: None\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}]\n >>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n >>> jobMarketplace.resumes\n []\n\n \"\"\"",
"test_class": "JobMarketplaceTestWithdrawResume",
"test_code": "class JobMarketplaceTestWithdrawResume(unittest.TestCase):\n def test_withdraw_resume(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [])\n\n def test_withdraw_resume_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [{'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])\n\n def test_withdraw_resume_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [])\n \n def test_withdraw_resume_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Amy\", \"skills\": ['skill3', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [])\n\n def test_withdraw_resume_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Amy\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [{'experience': 'experience', 'name': 'John', 'skills': ['skill3', 'skill4']}])",
"solution_code": "def withdraw_resume(self, resume):\n self.resumes.remove(resume)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.resumes"
],
"method_dependencies": []
}
},
{
"method_name": "search_jobs",
"method_description": "def search_jobs(self, criteria):\n \"\"\"\n This function is used to search for positions,and return the position information that meets the requirements.\n :param criteria: The requirements of the position,str.\n :return: The position information that meets the requirements,list.\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n >>> jobMarketplace.search_jobs(\"skill1\")\n [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]\n\n \"\"\"",
"test_class": "JobMarketplaceTestSearchJobs",
"test_code": "class JobMarketplaceTestSearchJobs(unittest.TestCase):\n def test_search_jobs(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill1\"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}])\n\n def test_search_jobs_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill1\"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}])\n\n def test_search_jobs_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill3\"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill3', 'skill4']}])\n\n def test_search_jobs_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill5\"), [])\n\n def test_search_jobs_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill6\"), [])",
"solution_code": "def search_jobs(self, criteria):\n matching_jobs = []\n for job_listing in self.job_listings:\n if criteria.lower() in job_listing[\"job_title\"].lower() or criteria.lower() in [r.lower() for r in job_listing[\"requirements\"]]:\n matching_jobs.append(job_listing)\n return matching_jobs",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.job_listings"
],
"method_dependencies": []
}
},
{
"method_name": "get_job_applicants",
"method_description": "def get_job_applicants(self, job):\n \"\"\"\n This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.\n :param job: The position information,dict.\n :return: The candidate information that meets the requirements,list.\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}]\n >>> jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n >>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])\n [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]\n\n \"\"\"",
"test_class": "JobMarketplaceTestGetJobApplicants",
"test_code": "class JobMarketplaceTestGetJobApplicants(unittest.TestCase):\n def test_get_job_applicants(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n\n def test_get_job_applicants_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n\n def test_get_job_applicants_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])\n\n def test_get_job_applicants_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill5', 'skill6']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [])\n\n def test_get_job_applicants_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill6', 'skill7']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [])",
"solution_code": "def get_job_applicants(self, job):\n applicants = []\n for resume in self.resumes:\n if self.matches_requirements(resume, job[\"requirements\"]):\n applicants.append(resume)\n return applicants",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.resumes"
],
"method_dependencies": []
}
}
] | JobMarketplace | [
"JobMarketplaceTestPostJob",
"JobMarketplaceTestRemoveJob",
"JobMarketplaceTestSubmitResume",
"JobMarketplaceTestWithdrawResume",
"JobMarketplaceTestSearchJobs",
"JobMarketplaceTestGetJobApplicants",
"JobMarketplaceTestMatchesRequirements",
"JobMarketplaceTestMain"
] | class JobMarketplace:
def __init__(self):
self.job_listings = []
self.resumes = []
| [
"self.job_listings",
"self.resumes"
] |
ClassEval_50 | import json
import os
class JSONProcessor:
"""
This is a class to process JSON file, including reading and writing JSON files, as well as processing JSON data by removing a specified key from the JSON object.
"""
def read_json(self, file_path):
"""
Read a JSON file and return the data.
:param file_path: str, the path of the JSON file.
:return: dict, the data from the JSON file if read successfully, or return -1 if an error occurs during the reading process.
return 0 if the file does not exist.
>>> json.read_json('test.json')
{'name': 'test', 'age': 14}
"""
def write_json(self, data, file_path):
"""
Write data to a JSON file and save it to the given path.
:param data: dict, the data to be written to the JSON file.
:param file_path: str, the path of the JSON file.
:return: 1 if the writing process is successful, or -1, if an error occurs during the writing process.
>>> json.write_json({'key1': 'value1', 'key2': 'value2'}, 'test.json')
1
>>> json.read_json('test.json')
{'key1': 'value1', 'key2': 'value2'}
"""
def process_json(self, file_path, remove_key):
"""
read a JSON file and process the data by removing a specified key and rewrite the modified data back to the file.
:param file_path: str, the path of the JSON file.
:param remove_key: str, the key to be removed.
:return: 1, if the specified key is successfully removed and the data is written back.
0, if the file does not exist or the specified key does not exist in the data.
>>> json.read_json('test.json')
{'key1': 'value1', 'key2': 'value2'}
>>> json.process_json('test.json', 'key1')
1
>>> json.read_json('test.json')
{'key2': 'value2'}
""" | import os
import stat
import json
import unittest
class JSONProcessorTestReadJson(unittest.TestCase):
def setUp(self):
self.processor = JSONProcessor()
self.test_data = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
self.file_path = "test.json"
def tearDown(self):
if os.path.exists(self.file_path):
os.remove(self.file_path)
# file exists
def test_read_json_1(self):
with open(self.file_path, 'w') as file:
json.dump(self.test_data, file)
result = self.processor.read_json(self.file_path)
self.assertEqual(result, self.test_data)
# file not exists
def test_read_json_2(self):
result = self.processor.read_json(self.file_path)
self.assertEqual(result, 0)
# invalid json file
def test_read_json_3(self):
with open(self.file_path, 'w') as file:
file.write("Invalid JSON")
result = self.processor.read_json(self.file_path)
self.assertEqual(result, -1)
def test_read_json_4(self):
result = self.processor.read_json('wrong')
self.assertEqual(result, 0)
def test_read_json_5(self):
result = self.processor.read_json('abcd')
self.assertEqual(result, 0)
class JSONProcessorTestWriteJson(unittest.TestCase):
def setUp(self):
self.processor = JSONProcessor()
self.test_data = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
self.file_path = "test.json"
# create a read only file
self.file_path_only_read = 'test_only_read.json'
with open(self.file_path_only_read, 'w') as f:
f.write('{"key1": "value1"}')
# set file only read mode
os.chmod(self.file_path_only_read, stat.S_IRUSR + stat.S_IRGRP + stat.S_IROTH)
def tearDown(self):
if os.path.exists(self.file_path):
os.remove(self.file_path)
if os.path.exists(self.file_path_only_read):
# unset file only read mode and remove the file
os.chmod(self.file_path_only_read,
stat.S_IWUSR + stat.S_IRUSR + stat.S_IWGRP + stat.S_IRGRP + stat.S_IWOTH + stat.S_IROTH)
os.remove(self.file_path_only_read)
def test_write_json_1(self):
result = self.processor.write_json(self.test_data, self.file_path)
self.assertEqual(result, 1)
with open(self.file_path, 'r') as file:
written_data = json.load(file)
self.assertEqual(written_data, self.test_data)
def test_write_json_2(self):
# Provide a read-only file path to simulate an exception
result = self.processor.write_json(self.test_data, self.file_path_only_read)
self.assertEqual(result, -1)
def test_write_json_3(self):
result = self.processor.write_json([], self.file_path_only_read)
self.assertEqual(result, -1)
def test_write_json_4(self):
result = self.processor.write_json(self.test_data, '')
self.assertEqual(result, -1)
def test_write_json_5(self):
result = self.processor.write_json([], '')
self.assertEqual(result, -1)
class JSONProcessorTestProcessJsonExistingKey(unittest.TestCase):
def setUp(self):
self.processor = JSONProcessor()
self.test_data = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
self.file_path = "test.json"
def tearDown(self):
if os.path.exists(self.file_path):
os.remove(self.file_path)
# key exists
def test_process_json_1(self):
with open(self.file_path, 'w') as file:
json.dump(self.test_data, file)
remove_key = "key2"
self.processor.process_json(self.file_path, remove_key)
with open(self.file_path, 'r') as file:
processed_data = json.load(file)
expected_data = {
"key1": "value1",
"key3": "value3"
}
self.assertEqual(processed_data, expected_data)
# key not exists
def test_process_json_2(self):
with open(self.file_path, 'w') as file:
json.dump(self.test_data, file)
remove_key = "nonexistent_key"
self.processor.process_json(self.file_path, remove_key)
with open(self.file_path, 'r') as file:
processed_data = json.load(file)
self.assertEqual(processed_data, self.test_data)
# file is empty
def test_process_json_3(self):
# Create an empty JSON file
with open(self.file_path, 'w') as file:
pass
remove_key = "key1"
self.assertEqual(self.processor.process_json(self.file_path, remove_key), 0)
def test_process_json_4(self):
with open(self.file_path, 'w') as file:
json.dump(self.test_data, file)
remove_key = "aaa"
self.processor.process_json(self.file_path, remove_key)
with open(self.file_path, 'r') as file:
processed_data = json.load(file)
self.assertEqual(processed_data, self.test_data)
def test_process_json_5(self):
with open(self.file_path, 'w') as file:
json.dump(self.test_data, file)
remove_key = "bbb"
self.processor.process_json(self.file_path, remove_key)
with open(self.file_path, 'r') as file:
processed_data = json.load(file)
self.assertEqual(processed_data, self.test_data)
class JSONProcessorTestMain(unittest.TestCase):
def setUp(self):
self.processor = JSONProcessor()
self.test_data = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
self.file_path = "test.json"
def tearDown(self):
if os.path.exists(self.file_path):
os.remove(self.file_path)
def test_main(self):
# write first
result = self.processor.write_json(self.test_data, self.file_path)
self.assertEqual(result, 1)
with open(self.file_path, 'r') as file:
written_data = json.load(file)
self.assertEqual(written_data, self.test_data)
# read
result = self.processor.read_json(self.file_path)
self.assertEqual(result, self.test_data)
# process
remove_key = "key2"
self.processor.process_json(self.file_path, remove_key)
with open(self.file_path, 'r') as file:
processed_data = json.load(file)
expected_data = {
"key1": "value1",
"key3": "value3"
}
self.assertEqual(processed_data, expected_data) | import json
import os
class JSONProcessor:
def read_json(self, file_path):
if not os.path.exists(file_path):
return 0
try:
with open(file_path, 'r') as file:
data = json.load(file)
return data
except:
return -1
def write_json(self, data, file_path):
try:
with open(file_path, 'w') as file:
json.dump(data, file)
return 1
except:
return -1
def process_json(self, file_path, remove_key):
data = self.read_json(file_path)
if data == 0 or data == -1:
return 0
if remove_key in data:
del data[remove_key]
self.write_json(data, file_path)
return 1
else:
return 0 | [
"import json",
"import os"
] | """
This is a class to process JSON file, including reading and writing JSON files, as well as processing JSON data by removing a specified key from the JSON object.
"""
| [
{
"method_name": "read_json",
"method_description": "def read_json(self, file_path):\n \"\"\"\n Read a JSON file and return the data.\n :param file_path: str, the path of the JSON file.\n :return: dict, the data from the JSON file if read successfully, or return -1 if an error occurs during the reading process.\n return 0 if the file does not exist.\n >>> json.read_json('test.json')\n {'name': 'test', 'age': 14}\n \"\"\"",
"test_class": "JSONProcessorTestReadJson",
"test_code": "class JSONProcessorTestReadJson(unittest.TestCase):\n def setUp(self):\n self.processor = JSONProcessor()\n self.test_data = {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\"\n }\n self.file_path = \"test.json\"\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n # file exists\n def test_read_json_1(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n result = self.processor.read_json(self.file_path)\n self.assertEqual(result, self.test_data)\n\n # file not exists\n def test_read_json_2(self):\n result = self.processor.read_json(self.file_path)\n self.assertEqual(result, 0)\n\n # invalid json file\n def test_read_json_3(self):\n with open(self.file_path, 'w') as file:\n file.write(\"Invalid JSON\")\n result = self.processor.read_json(self.file_path)\n self.assertEqual(result, -1)\n\n def test_read_json_4(self):\n result = self.processor.read_json('wrong')\n self.assertEqual(result, 0)\n\n def test_read_json_5(self):\n result = self.processor.read_json('abcd')\n self.assertEqual(result, 0)",
"solution_code": "def read_json(self, file_path):\n if not os.path.exists(file_path):\n return 0\n try:\n with open(file_path, 'r') as file:\n data = json.load(file)\n return data\n except:\n return -1",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"json",
"os"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "write_json",
"method_description": "def write_json(self, data, file_path):\n \"\"\"\n Write data to a JSON file and save it to the given path.\n\n :param data: dict, the data to be written to the JSON file.\n :param file_path: str, the path of the JSON file.\n :return: 1 if the writing process is successful, or -1, if an error occurs during the writing process.\n >>> json.write_json({'key1': 'value1', 'key2': 'value2'}, 'test.json')\n 1\n >>> json.read_json('test.json')\n {'key1': 'value1', 'key2': 'value2'}\n \"\"\"",
"test_class": "JSONProcessorTestWriteJson",
"test_code": "class JSONProcessorTestWriteJson(unittest.TestCase):\n def setUp(self):\n self.processor = JSONProcessor()\n self.test_data = {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\"\n }\n self.file_path = \"test.json\"\n\n # create a read only file\n self.file_path_only_read = 'test_only_read.json'\n with open(self.file_path_only_read, 'w') as f:\n f.write('{\"key1\": \"value1\"}')\n\n # set file only read mode\n os.chmod(self.file_path_only_read, stat.S_IRUSR + stat.S_IRGRP + stat.S_IROTH)\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n if os.path.exists(self.file_path_only_read):\n # unset file only read mode and remove the file\n os.chmod(self.file_path_only_read,\n stat.S_IWUSR + stat.S_IRUSR + stat.S_IWGRP + stat.S_IRGRP + stat.S_IWOTH + stat.S_IROTH)\n os.remove(self.file_path_only_read)\n\n def test_write_json_1(self):\n result = self.processor.write_json(self.test_data, self.file_path)\n self.assertEqual(result, 1)\n with open(self.file_path, 'r') as file:\n written_data = json.load(file)\n self.assertEqual(written_data, self.test_data)\n\n def test_write_json_2(self):\n # Provide a read-only file path to simulate an exception\n result = self.processor.write_json(self.test_data, self.file_path_only_read)\n self.assertEqual(result, -1)\n\n def test_write_json_3(self):\n result = self.processor.write_json([], self.file_path_only_read)\n self.assertEqual(result, -1)\n\n def test_write_json_4(self):\n result = self.processor.write_json(self.test_data, '')\n self.assertEqual(result, -1)\n\n def test_write_json_5(self):\n result = self.processor.write_json([], '')\n self.assertEqual(result, -1)",
"solution_code": "def write_json(self, data, file_path):\n try:\n with open(file_path, 'w') as file:\n json.dump(data, file)\n return 1\n except:\n return -1",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"json"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "process_json",
"method_description": "def process_json(self, file_path, remove_key):\n \"\"\"\n read a JSON file and process the data by removing a specified key and rewrite the modified data back to the file.\n\n :param file_path: str, the path of the JSON file.\n :param remove_key: str, the key to be removed.\n :return: 1, if the specified key is successfully removed and the data is written back.\n 0, if the file does not exist or the specified key does not exist in the data.\n >>> json.read_json('test.json')\n {'key1': 'value1', 'key2': 'value2'}\n >>> json.process_json('test.json', 'key1')\n 1\n >>> json.read_json('test.json')\n {'key2': 'value2'}\n \"\"\"",
"test_class": "JSONProcessorTestProcessJsonExistingKey",
"test_code": "class JSONProcessorTestProcessJsonExistingKey(unittest.TestCase):\n def setUp(self):\n self.processor = JSONProcessor()\n self.test_data = {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\"\n }\n self.file_path = \"test.json\"\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n # key exists\n def test_process_json_1(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n remove_key = \"key2\"\n self.processor.process_json(self.file_path, remove_key)\n with open(self.file_path, 'r') as file:\n processed_data = json.load(file)\n expected_data = {\n \"key1\": \"value1\",\n \"key3\": \"value3\"\n }\n self.assertEqual(processed_data, expected_data)\n\n # key not exists\n def test_process_json_2(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n remove_key = \"nonexistent_key\"\n self.processor.process_json(self.file_path, remove_key)\n with open(self.file_path, 'r') as file:\n processed_data = json.load(file)\n self.assertEqual(processed_data, self.test_data)\n\n # file is empty\n def test_process_json_3(self):\n # Create an empty JSON file\n with open(self.file_path, 'w') as file:\n pass\n remove_key = \"key1\"\n self.assertEqual(self.processor.process_json(self.file_path, remove_key), 0)\n\n def test_process_json_4(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n remove_key = \"aaa\"\n self.processor.process_json(self.file_path, remove_key)\n with open(self.file_path, 'r') as file:\n processed_data = json.load(file)\n self.assertEqual(processed_data, self.test_data)\n\n def test_process_json_5(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n remove_key = \"bbb\"\n self.processor.process_json(self.file_path, remove_key)\n with open(self.file_path, 'r') as file:\n processed_data = json.load(file)\n self.assertEqual(processed_data, self.test_data)",
"solution_code": "def process_json(self, file_path, remove_key):\n data = self.read_json(file_path)\n if data == 0 or data == -1:\n return 0\n if remove_key in data:\n del data[remove_key]\n self.write_json(data, file_path)\n return 1\n else:\n return 0",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"json"
],
"field_dependencies": [],
"method_dependencies": [
"read_json",
"write_json"
]
}
}
] | JSONProcessor | [
"JSONProcessorTestReadJson",
"JSONProcessorTestWriteJson",
"JSONProcessorTestProcessJsonExistingKey",
"JSONProcessorTestMain"
] | class JSONProcessor:
| [] |
ClassEval_51 | import numpy as np
class KappaCalculator:
"""
This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient.
"""
@staticmethod
def kappa(testData, k):
"""
Calculate the cohens kappa value of a k-dimensional matrix
:param testData: The k-dimensional matrix that needs to calculate the cohens kappa value
:param k: int, Matrix dimension
:return:float, the cohens kappa value of the matrix
>>> KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3)
0.25
"""
@staticmethod
def fleiss_kappa(testData, N, k, n):
"""
Calculate the fliss kappa value of an N * k matrix
:param testData: Input data matrix, N * k
:param N: int, Number of samples
:param k: int, Number of categories
:param n: int, Number of raters
:return: float, fleiss kappa value
>>> KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14],
>>> [0, 2, 6, 4, 2],
>>> [0, 0, 3, 5, 6],
>>> [0, 3, 9, 2, 0],
>>> [2, 2, 8, 1, 1],
>>> [7, 7, 0, 0, 0],
>>> [3, 2, 6, 3, 0],
>>> [2, 5, 3, 2, 2],
>>> [6, 5, 2, 1, 0],
>>> [0, 2, 2, 3, 7]], 10, 5, 14)
0.20993070442195522
""" | import unittest
class KappaCalculatorTestKappa(unittest.TestCase):
def test_kappa_1(self):
self.assertEqual(KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3), 0.25)
def test_kappa_2(self):
self.assertAlmostEqual(KappaCalculator.kappa([[2, 2, 1], [1, 2, 1], [1, 1, 2]], 3), 0.19469026548672572)
def test_kappa_3(self):
self.assertAlmostEqual(KappaCalculator.kappa([[2, 1, 2], [1, 2, 1], [1, 1, 2]], 3), 0.19469026548672572)
def test_kappa_4(self):
self.assertAlmostEqual(KappaCalculator.kappa([[2, 1, 1], [2, 2, 1], [1, 1, 2]], 3), 0.19469026548672572)
def test_kappa_5(self):
self.assertAlmostEqual(KappaCalculator.kappa([[2, 1, 1], [1, 2, 2], [1, 1, 2]], 3), 0.19469026548672572)
class KappaCalculatorTestFleissKappa(unittest.TestCase):
def test_fleiss_kappa_1(self):
self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14],
[0, 2, 6, 4, 2],
[0, 0, 3, 5, 6],
[0, 3, 9, 2, 0],
[2, 2, 8, 1, 1],
[7, 7, 0, 0, 0],
[3, 2, 6, 3, 0],
[2, 5, 3, 2, 2],
[6, 5, 2, 1, 0],
[0, 2, 2, 3, 7]], 10, 5, 14), 0.20993070442195522)
def test_fleiss_kappa_2(self):
self.assertEqual(KappaCalculator.fleiss_kappa([[1, 0, 0, 0, 14],
[0, 2, 6, 4, 2],
[0, 0, 3, 5, 6],
[0, 3, 9, 2, 0],
[2, 2, 8, 1, 1],
[7, 7, 0, 0, 0],
[3, 2, 6, 3, 0],
[2, 5, 3, 2, 2],
[6, 5, 2, 1, 0],
[0, 2, 2, 3, 7]], 10, 5, 14), 0.2115748928799344)
def test_fleiss_kappa_3(self):
self.assertEqual(KappaCalculator.fleiss_kappa([[0, 1, 0, 0, 14],
[0, 2, 6, 4, 2],
[0, 0, 3, 5, 6],
[0, 3, 9, 2, 0],
[2, 2, 8, 1, 1],
[7, 7, 0, 0, 0],
[3, 2, 6, 3, 0],
[2, 5, 3, 2, 2],
[6, 5, 2, 1, 0],
[0, 2, 2, 3, 7]], 10, 5, 14), 0.21076904123090398)
def test_fleiss_kappa_4(self):
self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 1, 0, 14],
[0, 2, 6, 4, 2],
[0, 0, 3, 5, 6],
[0, 3, 9, 2, 0],
[2, 2, 8, 1, 1],
[7, 7, 0, 0, 0],
[3, 2, 6, 3, 0],
[2, 5, 3, 2, 2],
[6, 5, 2, 1, 0],
[0, 2, 2, 3, 7]], 10, 5, 14), 0.2096583016522883)
def test_fleiss_kappa_5(self):
self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 0, 1, 14],
[0, 2, 6, 4, 2],
[0, 0, 3, 5, 6],
[0, 3, 9, 2, 0],
[2, 2, 8, 1, 1],
[7, 7, 0, 0, 0],
[3, 2, 6, 3, 0],
[2, 5, 3, 2, 2],
[6, 5, 2, 1, 0],
[0, 2, 2, 3, 7]], 10, 5, 14), 0.21147425143148907)
class KappaCalculatorTest(unittest.TestCase):
def test_kappacalculator(self):
self.assertEqual(KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3), 0.25)
self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14],
[0, 2, 6, 4, 2],
[0, 0, 3, 5, 6],
[0, 3, 9, 2, 0],
[2, 2, 8, 1, 1],
[7, 7, 0, 0, 0],
[3, 2, 6, 3, 0],
[2, 5, 3, 2, 2],
[6, 5, 2, 1, 0],
[0, 2, 2, 3, 7]], 10, 5, 14), 0.20993070442195522) | import numpy as np
class KappaCalculator:
@staticmethod
def kappa(testData, k):
dataMat = np.mat(testData)
P0 = 0.0
for i in range(k):
P0 += dataMat[i, i] * 1.0
xsum = np.sum(dataMat, axis=1)
ysum = np.sum(dataMat, axis=0)
sum = np.sum(dataMat)
Pe = float(ysum * xsum) / sum / sum
P0 = float(P0 / sum * 1.0)
cohens_coefficient = float((P0 - Pe) / (1 - Pe))
return cohens_coefficient
@staticmethod
def fleiss_kappa(testData, N, k, n):
dataMat = np.mat(testData, float)
oneMat = np.ones((k, 1))
sum = 0.0
P0 = 0.0
for i in range(N):
temp = 0.0
for j in range(k):
sum += dataMat[i, j]
temp += 1.0 * dataMat[i, j] ** 2
temp -= n
temp /= (n - 1) * n
P0 += temp
P0 = 1.0 * P0 / N
ysum = np.sum(dataMat, axis=0)
for i in range(k):
ysum[0, i] = (ysum[0, i] / sum) ** 2
Pe = ysum * oneMat * 1.0
ans = (P0 - Pe) / (1 - Pe)
return ans[0, 0] | [
"import numpy as np"
] | """
This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient.
"""
| [
{
"method_name": "kappa",
"method_description": "def kappa(testData, k):\n \"\"\"\n Calculate the cohens kappa value of a k-dimensional matrix\n :param testData: The k-dimensional matrix that needs to calculate the cohens kappa value\n :param k: int, Matrix dimension\n :return:float, the cohens kappa value of the matrix\n >>> KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3)\n 0.25\n \"\"\"",
"test_class": "KappaCalculatorTestKappa",
"test_code": "class KappaCalculatorTestKappa(unittest.TestCase):\n def test_kappa_1(self):\n self.assertEqual(KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3), 0.25)\n\n def test_kappa_2(self):\n self.assertAlmostEqual(KappaCalculator.kappa([[2, 2, 1], [1, 2, 1], [1, 1, 2]], 3), 0.19469026548672572)\n\n def test_kappa_3(self):\n self.assertAlmostEqual(KappaCalculator.kappa([[2, 1, 2], [1, 2, 1], [1, 1, 2]], 3), 0.19469026548672572)\n\n def test_kappa_4(self):\n self.assertAlmostEqual(KappaCalculator.kappa([[2, 1, 1], [2, 2, 1], [1, 1, 2]], 3), 0.19469026548672572)\n\n def test_kappa_5(self):\n self.assertAlmostEqual(KappaCalculator.kappa([[2, 1, 1], [1, 2, 2], [1, 1, 2]], 3), 0.19469026548672572)",
"solution_code": "def kappa(testData, k):\n dataMat = np.mat(testData)\n P0 = 0.0\n for i in range(k):\n P0 += dataMat[i, i] * 1.0\n xsum = np.sum(dataMat, axis=1)\n ysum = np.sum(dataMat, axis=0)\n sum = np.sum(dataMat)\n Pe = float(ysum * xsum) / sum / sum\n P0 = float(P0 / sum * 1.0)\n cohens_coefficient = float((P0 - Pe) / (1 - Pe))\n return cohens_coefficient",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "fleiss_kappa",
"method_description": "@staticmethod\n def fleiss_kappa(testData, N, k, n):\n \"\"\"\n Calculate the fliss kappa value of an N * k matrix\n :param testData: Input data matrix, N * k\n :param N: int, Number of samples\n :param k: int, Number of categories\n :param n: int, Number of raters\n :return: float, fleiss kappa value\n >>> KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14],\n >>> [0, 2, 6, 4, 2],\n >>> [0, 0, 3, 5, 6],\n >>> [0, 3, 9, 2, 0],\n >>> [2, 2, 8, 1, 1],\n >>> [7, 7, 0, 0, 0],\n >>> [3, 2, 6, 3, 0],\n >>> [2, 5, 3, 2, 2],\n >>> [6, 5, 2, 1, 0],\n >>> [0, 2, 2, 3, 7]], 10, 5, 14)\n 0.20993070442195522\n \"\"\"",
"test_class": "KappaCalculatorTestFleissKappa",
"test_code": "class KappaCalculatorTestFleissKappa(unittest.TestCase):\n def test_fleiss_kappa_1(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.20993070442195522)\n\n def test_fleiss_kappa_2(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[1, 0, 0, 0, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.2115748928799344)\n\n def test_fleiss_kappa_3(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[0, 1, 0, 0, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.21076904123090398)\n\n def test_fleiss_kappa_4(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 1, 0, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.2096583016522883)\n\n def test_fleiss_kappa_5(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 0, 1, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.21147425143148907)",
"solution_code": "@staticmethod\n def fleiss_kappa(testData, N, k, n):\n dataMat = np.mat(testData, float)\n oneMat = np.ones((k, 1))\n sum = 0.0\n P0 = 0.0\n for i in range(N):\n temp = 0.0\n for j in range(k):\n sum += dataMat[i, j]\n temp += 1.0 * dataMat[i, j] ** 2\n temp -= n\n temp /= (n - 1) * n\n P0 += temp\n P0 = 1.0 * P0 / N\n ysum = np.sum(dataMat, axis=0)\n for i in range(k):\n ysum[0, i] = (ysum[0, i] / sum) ** 2\n Pe = ysum * oneMat * 1.0\n ans = (P0 - Pe) / (1 - Pe)\n return ans[0, 0]",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | KappaCalculator | [
"KappaCalculatorTestKappa",
"KappaCalculatorTestFleissKappa",
"KappaCalculatorTest"
] | class KappaCalculator:
| [] |
ClassEval_52 | import nltk
from nltk.stem import WordNetLemmatizer
from nltk import pos_tag, word_tokenize
import string
nltk.download('averaged_perceptron_tagger')
nltk.download('punkt')
nltk.download('wordnet')
class Lemmatization:
"""
This is a class about Lemmatization, which utilizes the nltk library to perform lemmatization and part-of-speech tagging on sentences, as well as remove punctuation.
"""
def __init__(self):
"""
creates a WordNetLemmatizer object and stores it in the self.lemmatizer member variable.
"""
self.lemmatizer = WordNetLemmatizer()
def lemmatize_sentence(self, sentence):
"""
Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word,
lemmatizes the words with different parameters based on their parts of speech, and stores in a list.
:param sentence: a sentence str
:return: a list of words which have been lemmatized.
>>> lemmatization = Lemmatization()
>>> lemmatization.lemmatize_sentence("I am running in a race.")
['I', 'be', 'run', 'in', 'a', 'race']
"""
def get_pos_tag(self, sentence):
"""
Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word.
:param sentence: a sentence str
:return: list, part of speech tag of each word in the sentence.
>>> lemmatization = Lemmatization()
>>> lemmatization.get_pos_tag("I am running in a race.")
['PRP', 'VBP', 'VBG', 'IN', 'DT', 'NN']
"""
def remove_punctuation(self, sentence):
"""
Removes punctuation from the input text.
:param sentence: a sentence str
:return: str, sentence without any punctuation
>>> lemmatization = Lemmatization()
>>> lemmatization.remove_punctuation("I am running in a race.")
'I am running in a race'
""" | import unittest
class LemmatizationTestLemmatizeSentence(unittest.TestCase):
def test_lemmatize_sentence_1(self):
lemmatization = Lemmatization()
result = lemmatization.lemmatize_sentence("I am running in a race.")
expected = ['I', 'be', 'run', 'in', 'a', 'race']
self.assertEqual(result, expected)
def test_lemmatize_sentence_2(self):
lemmatization = Lemmatization()
result = lemmatization.lemmatize_sentence("Until the beating, Cantanco's eyesight had been weak, but adequate.")
expected = ['Until', 'the', 'beating', 'Cantancos', 'eyesight', 'have', 'be', 'weak', 'but', 'adequate']
self.assertEqual(result, expected)
def test_lammatize_sentence_3(self):
lemmatization = Lemmatization()
result = lemmatization.lemmatize_sentence("The dog's barked at the mailman.")
expected = ['The', 'dog', 'bark', 'at', 'the', 'mailman']
self.assertEqual(result, expected)
def test_lemmatize_sentence_4(self):
lemmatization = Lemmatization()
result = lemmatization.lemmatize_sentence("He was running and eating at same time. ")
expected = ['He', 'be', 'run', 'and', 'eat', 'at', 'same', 'time']
self.assertEqual(result, expected)
def test_lemmatize_sentence_5(self):
lemmatization = Lemmatization()
result = lemmatization.lemmatize_sentence("I was taking a ride in the car.")
expected = ['I', 'be', 'take', 'a', 'ride', 'in', 'the', 'car']
self.assertEqual(result, expected)
class LemmatizationTestGetPosTag(unittest.TestCase):
def test_get_pos_tag_1(self):
lemmatization = Lemmatization()
result = lemmatization.get_pos_tag("I am running in a race.")
expected = ['PRP', 'VBP', 'VBG', 'IN', 'DT', 'NN']
self.assertEqual(result, expected)
def test_get_pos_tag_2(self):
lemmatization = Lemmatization()
result = lemmatization.get_pos_tag("Cantanco's eyesight had been weak, but adequate.")
expected = ['NNP', 'NN', 'VBD', 'VBN', 'JJ', 'CC', 'JJ']
self.assertEqual(result, expected)
def test_get_pos_tag_3(self):
lemmatization = Lemmatization()
result = lemmatization.get_pos_tag("The dog's barked at the mailman.")
expected = ['DT', 'NNS', 'VBD', 'IN', 'DT', 'NN']
self.assertEqual(result, expected)
def test_get_pos_tag_4(self):
lemmatization = Lemmatization()
result = lemmatization.get_pos_tag("He was running and eating at same time. ")
expected = ['PRP', 'VBD', 'VBG', 'CC', 'VBG', 'IN', 'JJ', 'NN']
self.assertEqual(result, expected)
def test_get_pos_tag_5(self):
lemmatization = Lemmatization()
result = lemmatization.get_pos_tag("I was taking a ride in the car.")
expected = ['PRP', 'VBD', 'VBG', 'DT', 'NN', 'IN', 'DT', 'NN']
self.assertEqual(result, expected)
class LemmatizationTestRemovePunctuation(unittest.TestCase):
def test_remove_punctuation_1(self):
lemmatization = Lemmatization()
result = lemmatization.remove_punctuation("I am running in a race.")
expected = "I am running in a race"
self.assertEqual(result, expected)
def test_remove_punctuation_2(self):
lemmatization = Lemmatization()
result = lemmatization.remove_punctuation("Until the beating, Cantanco's eyesight had been weak, but adequate.")
expected = 'Until the beating Cantancos eyesight had been weak but adequate'
self.assertEqual(result, expected)
def test_remove_punctuation_3(self):
lemmatization = Lemmatization()
result = lemmatization.remove_punctuation("The dog's barked at the mailman!!!")
expected = 'The dogs barked at the mailman'
self.assertEqual(result, expected)
def test_remove_punctuation_4(self):
lemmatization = Lemmatization()
result = lemmatization.remove_punctuation("He was running and eating at same time... ")
expected = 'He was running and eating at same time '
self.assertEqual(result, expected)
def test_remove_punctuation_5(self):
lemmatization = Lemmatization()
result = lemmatization.remove_punctuation("Is this a test? I hope it is...")
expected = 'Is this a test I hope it is'
self.assertEqual(result, expected)
class LemmatizationTestMain(unittest.TestCase):
def test_main(self):
lemmatization = Lemmatization()
result = lemmatization.lemmatize_sentence("Until the beating, Cantanco's eyesight had been weak, but adequate.")
expected = ['Until', 'the', 'beating', 'Cantancos', 'eyesight', 'have', 'be', 'weak', 'but', 'adequate']
self.assertEqual(result, expected)
result = lemmatization.get_pos_tag("Cantanco's eyesight had been weak, but adequate.")
expected = ['NNP', 'NN', 'VBD', 'VBN', 'JJ', 'CC', 'JJ']
self.assertEqual(result, expected) | import nltk
from nltk.stem import WordNetLemmatizer
from nltk import pos_tag, word_tokenize
import string
nltk.download('averaged_perceptron_tagger')
nltk.download('punkt')
nltk.download('wordnet')
class Lemmatization:
def __init__(self):
self.lemmatizer = WordNetLemmatizer()
def lemmatize_sentence(self, sentence):
lemmatized_words = []
sentence = self.remove_punctuation(sentence)
words = word_tokenize(sentence)
tagged_words = pos_tag(words)
for word, tag in tagged_words:
if tag.startswith('V'):
lemmatized_word = self.lemmatizer.lemmatize(word, pos='v')
elif tag.startswith('J'):
lemmatized_word = self.lemmatizer.lemmatize(word, pos='a')
elif tag.startswith('R'):
lemmatized_word = self.lemmatizer.lemmatize(word, pos='r')
else:
lemmatized_word = self.lemmatizer.lemmatize(word)
lemmatized_words.append(lemmatized_word)
return lemmatized_words
def get_pos_tag(self, sentence):
pos_tags = []
sentence = self.remove_punctuation(sentence)
words = word_tokenize(sentence)
tagged_words = pos_tag(words)
for tagged_word in tagged_words:
pos_tags.append(tagged_word[1])
return pos_tags
def remove_punctuation(self, sentence):
return sentence.translate(str.maketrans('', '', string.punctuation)) | [
"import nltk",
"from nltk.stem import WordNetLemmatizer",
"from nltk import pos_tag, word_tokenize",
"import string"
] | """
This is a class about Lemmatization, which utilizes the nltk library to perform lemmatization and part-of-speech tagging on sentences, as well as remove punctuation.
"""
| [
{
"method_name": "lemmatize_sentence",
"method_description": "def lemmatize_sentence(self, sentence):\n \"\"\"\n Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word,\n lemmatizes the words with different parameters based on their parts of speech, and stores in a list.\n :param sentence: a sentence str\n :return: a list of words which have been lemmatized.\n >>> lemmatization = Lemmatization()\n >>> lemmatization.lemmatize_sentence(\"I am running in a race.\")\n ['I', 'be', 'run', 'in', 'a', 'race']\n\n \"\"\"",
"test_class": "LemmatizationTestLemmatizeSentence",
"test_code": "class LemmatizationTestLemmatizeSentence(unittest.TestCase):\n def test_lemmatize_sentence_1(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"I am running in a race.\")\n expected = ['I', 'be', 'run', 'in', 'a', 'race']\n self.assertEqual(result, expected)\n\n def test_lemmatize_sentence_2(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"Until the beating, Cantanco's eyesight had been weak, but adequate.\")\n expected = ['Until', 'the', 'beating', 'Cantancos', 'eyesight', 'have', 'be', 'weak', 'but', 'adequate']\n self.assertEqual(result, expected)\n\n def test_lammatize_sentence_3(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"The dog's barked at the mailman.\")\n expected = ['The', 'dog', 'bark', 'at', 'the', 'mailman']\n self.assertEqual(result, expected)\n\n def test_lemmatize_sentence_4(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"He was running and eating at same time. \")\n expected = ['He', 'be', 'run', 'and', 'eat', 'at', 'same', 'time']\n self.assertEqual(result, expected)\n\n def test_lemmatize_sentence_5(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"I was taking a ride in the car.\")\n expected = ['I', 'be', 'take', 'a', 'ride', 'in', 'the', 'car']\n self.assertEqual(result, expected)",
"solution_code": "def lemmatize_sentence(self, sentence):\n lemmatized_words = []\n sentence = self.remove_punctuation(sentence)\n words = word_tokenize(sentence)\n tagged_words = pos_tag(words)\n for word, tag in tagged_words:\n if tag.startswith('V'):\n lemmatized_word = self.lemmatizer.lemmatize(word, pos='v')\n elif tag.startswith('J'):\n lemmatized_word = self.lemmatizer.lemmatize(word, pos='a')\n elif tag.startswith('R'):\n lemmatized_word = self.lemmatizer.lemmatize(word, pos='r')\n else:\n lemmatized_word = self.lemmatizer.lemmatize(word)\n lemmatized_words.append(lemmatized_word)\n return lemmatized_words",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.lemmatizer"
],
"method_dependencies": [
"remove_punctuation"
]
}
},
{
"method_name": "get_pos_tag",
"method_description": "def get_pos_tag(self, sentence):\n \"\"\"\n Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word.\n :param sentence: a sentence str\n :return: list, part of speech tag of each word in the sentence.\n >>> lemmatization = Lemmatization()\n >>> lemmatization.get_pos_tag(\"I am running in a race.\")\n ['PRP', 'VBP', 'VBG', 'IN', 'DT', 'NN']\n\n \"\"\"",
"test_class": "LemmatizationTestGetPosTag",
"test_code": "class LemmatizationTestGetPosTag(unittest.TestCase):\n def test_get_pos_tag_1(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"I am running in a race.\")\n expected = ['PRP', 'VBP', 'VBG', 'IN', 'DT', 'NN']\n self.assertEqual(result, expected)\n\n def test_get_pos_tag_2(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"Cantanco's eyesight had been weak, but adequate.\")\n expected = ['NNP', 'NN', 'VBD', 'VBN', 'JJ', 'CC', 'JJ']\n self.assertEqual(result, expected)\n\n def test_get_pos_tag_3(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"The dog's barked at the mailman.\")\n expected = ['DT', 'NNS', 'VBD', 'IN', 'DT', 'NN']\n self.assertEqual(result, expected)\n\n def test_get_pos_tag_4(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"He was running and eating at same time. \")\n expected = ['PRP', 'VBD', 'VBG', 'CC', 'VBG', 'IN', 'JJ', 'NN']\n self.assertEqual(result, expected)\n\n def test_get_pos_tag_5(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"I was taking a ride in the car.\")\n expected = ['PRP', 'VBD', 'VBG', 'DT', 'NN', 'IN', 'DT', 'NN']\n self.assertEqual(result, expected)",
"solution_code": "def get_pos_tag(self, sentence):\n pos_tags = []\n sentence = self.remove_punctuation(sentence)\n words = word_tokenize(sentence)\n tagged_words = pos_tag(words)\n for tagged_word in tagged_words:\n pos_tags.append(tagged_word[1])\n return pos_tags",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"remove_punctuation"
]
}
},
{
"method_name": "remove_punctuation",
"method_description": "def remove_punctuation(self, sentence):\n \"\"\"\n Removes punctuation from the input text.\n :param sentence: a sentence str\n :return: str, sentence without any punctuation\n >>> lemmatization = Lemmatization()\n >>> lemmatization.remove_punctuation(\"I am running in a race.\")\n 'I am running in a race'\n\n \"\"\"",
"test_class": "LemmatizationTestRemovePunctuation",
"test_code": "class LemmatizationTestRemovePunctuation(unittest.TestCase):\n def test_remove_punctuation_1(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"I am running in a race.\")\n expected = \"I am running in a race\"\n self.assertEqual(result, expected)\n\n def test_remove_punctuation_2(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"Until the beating, Cantanco's eyesight had been weak, but adequate.\")\n expected = 'Until the beating Cantancos eyesight had been weak but adequate'\n self.assertEqual(result, expected)\n\n def test_remove_punctuation_3(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"The dog's barked at the mailman!!!\")\n expected = 'The dogs barked at the mailman'\n self.assertEqual(result, expected)\n\n def test_remove_punctuation_4(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"He was running and eating at same time... \")\n expected = 'He was running and eating at same time '\n self.assertEqual(result, expected)\n\n def test_remove_punctuation_5(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"Is this a test? I hope it is...\")\n expected = 'Is this a test I hope it is'\n self.assertEqual(result, expected)",
"solution_code": "def remove_punctuation(self, sentence):\n return sentence.translate(str.maketrans('', '', string.punctuation))",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"string"
],
"field_dependencies": [],
"method_dependencies": []
}
}
] | Lemmatization | [
"LemmatizationTestLemmatizeSentence",
"LemmatizationTestGetPosTag",
"LemmatizationTestRemovePunctuation",
"LemmatizationTestMain"
] | class Lemmatization:
def __init__(self):
"""
creates a WordNetLemmatizer object and stores it in the self.lemmatizer member variable.
"""
self.lemmatizer = WordNetLemmatizer()
| [
"self.lemmatizer"
] |
ClassEval_53 | import re
import string
class LongestWord:
"""
This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list.
"""
def __init__(self):
"""
Initialize a list of word.
"""
self.word_list = []
def add_word(self, word):
"""
append the input word into self.word_list
:param word: str, input word
"""
def find_longest_word(self, sentence):
"""
Remove punctuation marks and split a sentence into a list of word. Find the longest splited word that is in the self.word_list.
Words are strictly case sensitive.
:param sentence: a sentence str
:return str: longest splited word that is in the self.word_list. return '' if self.word_list is empty.
>>> longestWord = LongestWord()
>>> longestWord.add_word('A')
>>> longestWord.add_word('aM')
>>> longestWord.find_longest_word('I am a student.')
'a'
""" | import unittest
class LongestWordTestAddWord(unittest.TestCase):
def test_add_word_1(self):
longestWord = LongestWord()
longestWord.add_word("hello")
self.assertEqual(['hello'], longestWord.word_list)
def test_add_word_2(self):
longestWord = LongestWord()
longestWord.add_word("hello")
longestWord.add_word("world")
self.assertEqual(['hello', 'world'], longestWord.word_list)
def test_add_word_3(self):
longestWord = LongestWord()
longestWord.add_word("hello")
longestWord.add_word("world")
longestWord.add_word("!")
self.assertEqual(['hello', 'world', '!'], longestWord.word_list)
def test_add_word_4(self):
longestWord = LongestWord()
longestWord.add_word("hello")
longestWord.add_word("world")
longestWord.add_word("!")
longestWord.add_word("!")
self.assertEqual(['hello', 'world', '!', '!'], longestWord.word_list)
def test_add_word_5(self):
longestWord = LongestWord()
longestWord.add_word("hello")
longestWord.add_word("world")
longestWord.add_word("!")
longestWord.add_word("!")
longestWord.add_word("!")
self.assertEqual(['hello', 'world', '!', '!', '!'], longestWord.word_list)
class LongestWordTestFindLongestWord(unittest.TestCase):
def test_find_longest_word_1(self):
longestWord = LongestWord()
longestWord.add_word("a")
sentence = 'I am a student.'
self.assertEqual('a', longestWord.find_longest_word(sentence))
def test_find_longest_word_2(self):
longestWord = LongestWord()
sentence = 'I am a student.'
self.assertEqual('', longestWord.find_longest_word(sentence))
def test_find_longest_word_3(self):
longestWord = LongestWord()
longestWord.add_word("student")
sentence = 'I am a student.'
self.assertEqual('student', longestWord.find_longest_word(sentence))
def test_find_longest_word_4(self):
longestWord = LongestWord()
longestWord.add_word("apple")
sentence = 'Apple is red.'
self.assertEqual('apple', longestWord.find_longest_word(sentence))
def test_find_longest_word_5(self):
longestWord = LongestWord()
longestWord.add_word("apple")
longestWord.add_word("red")
sentence = 'Apple is red.'
self.assertEqual('apple', longestWord.find_longest_word(sentence)) | import re
import string
class LongestWord:
def __init__(self):
self.word_list = []
def add_word(self, word):
self.word_list.append(word)
def find_longest_word(self, sentence):
longest_word = ""
sentence = sentence.lower()
sentence = re.sub('[%s]' % re.escape(string.punctuation), '', sentence)
sentence = re.split(' ', sentence)
for word in sentence:
if word in self.word_list and len(word) > len(longest_word):
longest_word = word
return longest_word | [
"import re",
"import string"
] | """
This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list.
"""
| [
{
"method_name": "add_word",
"method_description": "def add_word(self, word):\n \"\"\"\n append the input word into self.word_list\n :param word: str, input word\n \"\"\"",
"test_class": "LongestWordTestAddWord",
"test_code": "class LongestWordTestAddWord(unittest.TestCase):\n def test_add_word_1(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n self.assertEqual(['hello'], longestWord.word_list)\n\n def test_add_word_2(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n longestWord.add_word(\"world\")\n self.assertEqual(['hello', 'world'], longestWord.word_list)\n\n def test_add_word_3(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n longestWord.add_word(\"world\")\n longestWord.add_word(\"!\")\n self.assertEqual(['hello', 'world', '!'], longestWord.word_list)\n\n def test_add_word_4(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n longestWord.add_word(\"world\")\n longestWord.add_word(\"!\")\n longestWord.add_word(\"!\")\n self.assertEqual(['hello', 'world', '!', '!'], longestWord.word_list)\n\n def test_add_word_5(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n longestWord.add_word(\"world\")\n longestWord.add_word(\"!\")\n longestWord.add_word(\"!\")\n longestWord.add_word(\"!\")\n self.assertEqual(['hello', 'world', '!', '!', '!'], longestWord.word_list)",
"solution_code": "def add_word(self, word):\n self.word_list.append(word)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.word_list"
],
"method_dependencies": []
}
},
{
"method_name": "find_longest_word",
"method_description": "def find_longest_word(self, sentence):\n \"\"\"\n Remove punctuation marks and split a sentence into a list of word. Find the longest splited word that is in the self.word_list.\n Words are strictly case sensitive.\n :param sentence: a sentence str\n :return str: longest splited word that is in the self.word_list. return '' if self.word_list is empty.\n >>> longestWord = LongestWord()\n >>> longestWord.add_word('A')\n >>> longestWord.add_word('aM')\n >>> longestWord.find_longest_word('I am a student.')\n 'a'\n \"\"\"",
"test_class": "LongestWordTestFindLongestWord",
"test_code": "class LongestWordTestFindLongestWord(unittest.TestCase):\n def test_find_longest_word_1(self):\n longestWord = LongestWord()\n longestWord.add_word(\"a\")\n sentence = 'I am a student.'\n self.assertEqual('a', longestWord.find_longest_word(sentence))\n\n def test_find_longest_word_2(self):\n longestWord = LongestWord()\n sentence = 'I am a student.'\n self.assertEqual('', longestWord.find_longest_word(sentence))\n\n def test_find_longest_word_3(self):\n longestWord = LongestWord()\n longestWord.add_word(\"student\")\n sentence = 'I am a student.'\n self.assertEqual('student', longestWord.find_longest_word(sentence))\n\n def test_find_longest_word_4(self):\n longestWord = LongestWord()\n longestWord.add_word(\"apple\")\n sentence = 'Apple is red.'\n self.assertEqual('apple', longestWord.find_longest_word(sentence))\n\n def test_find_longest_word_5(self):\n longestWord = LongestWord()\n longestWord.add_word(\"apple\")\n longestWord.add_word(\"red\")\n sentence = 'Apple is red.'\n self.assertEqual('apple', longestWord.find_longest_word(sentence))",
"solution_code": "def find_longest_word(self, sentence):\n longest_word = \"\"\n sentence = sentence.lower()\n sentence = re.sub('[%s]' % re.escape(string.punctuation), '', sentence)\n sentence = re.split(' ', sentence)\n for word in sentence:\n if word in self.word_list and len(word) > len(longest_word):\n longest_word = word\n return longest_word",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"re",
"string"
],
"field_dependencies": [
"self.word_list"
],
"method_dependencies": []
}
}
] | LongestWord | [
"LongestWordTestAddWord",
"LongestWordTestFindLongestWord"
] | class LongestWord:
def __init__(self):
"""
Initialize a list of word.
"""
self.word_list = []
| [
"self.word_list"
] |
ClassEval_54 | import random
class MahjongConnect:
"""
MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over.
"""
def __init__(self, BOARD_SIZE, ICONS):
"""
initialize the board size and the icon list, create the game board
:param BOARD_SIZE: list of two integer numbers, representing the number of rows and columns of the game board
:param ICONS: list of string, representing the icons
>>>mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.BOARD_SIZE = [4, 4]
mc.ICONS = ['a', 'b', 'c']
mc.board = mc.create_board()
"""
self.BOARD_SIZE = BOARD_SIZE
self.ICONS = ICONS
self.board = self.create_board()
def create_board(self):
"""
create the game board with the given board size and icons
:return: 2-dimensional list, the game board
>>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
>>> mc.create_board()
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
"""
def is_valid_move(self, pos1, pos2):
"""
check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions)
:param pos1: position tuple(x, y) of the first icon
:param pos2: position tuple(x, y) of the second icon
:return:True or False ,representing whether the move of two icons is valid
>>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
>>> mc.is_valid_move((0, 0), (1, 0))
True
"""
def has_path(self, pos1, pos2):
"""
check if there is a path between two icons
:param pos1: position tuple(x, y) of the first icon
:param pos2: position tuple(x, y) of the second icon
:return: True or False ,representing whether there is a path between two icons
>>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
>>> mc.is_valid_move((0, 0), (1, 0))
True
"""
def remove_icons(self, pos1, pos2):
"""
remove the connected icons on the game board
:param pos1: position tuple(x, y) of the first icon to be removed
:param pos2: position tuple(x, y) of the second icon to be removed
:return: None
>>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
>>> mc.remove_icons((0, 0), (1, 0))
mc.board = [[' ', 'b', 'c', 'a'],
[' ', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
"""
def is_game_over(self):
"""
Check if the game is over (i.e., if there are no more icons on the game board)
:return: True or False ,representing whether the game is over
>>> mc = MahjongConnect([4, 4] ['a', 'b', 'c'])
>>> mc.board = [[' ', ' ', ' ', ' '],
>>> [' ', ' ', ' ', ' '],
>>> [' ', ' ', ' ', ' '],
>>> [' ', ' ', ' ', ' ']]
>>> mc.is_game_over()
True
""" | import unittest
class MahjongConnectTestCreateBoard(unittest.TestCase):
def test_create_board_1(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
self.assertEqual(mc.BOARD_SIZE, [4, 4])
self.assertEqual(mc.ICONS, ['a', 'b', 'c'])
for row in mc.board:
for icon in row:
self.assertIn(icon, mc.ICONS)
def test_create_board_2(self):
mc = MahjongConnect([2, 2], ['a', 'b', 'c'])
self.assertEqual(mc.BOARD_SIZE, [2, 2])
self.assertEqual(mc.ICONS, ['a', 'b', 'c'])
for row in mc.board:
for icon in row:
self.assertIn(icon, mc.ICONS)
def test_create_board_3(self):
mc = MahjongConnect([3, 3], ['a', 'b', 'c'])
self.assertEqual(mc.BOARD_SIZE, [3, 3])
self.assertEqual(mc.ICONS, ['a', 'b', 'c'])
for row in mc.board:
for icon in row:
self.assertIn(icon, mc.ICONS)
def test_create_board_4(self):
mc = MahjongConnect([1, 1], ['a', 'b', 'c'])
self.assertEqual(mc.BOARD_SIZE, [1, 1])
self.assertEqual(mc.ICONS, ['a', 'b', 'c'])
for row in mc.board:
for icon in row:
self.assertIn(icon, mc.ICONS)
def test_create_board_5(self):
mc = MahjongConnect([5, 5], ['a', 'b', 'c'])
self.assertEqual(mc.BOARD_SIZE, [5, 5])
self.assertEqual(mc.ICONS, ['a', 'b', 'c'])
for row in mc.board:
for icon in row:
self.assertIn(icon, mc.ICONS)
class MahjongConnectTestIsValidMove(unittest.TestCase):
def test_is_valid_move_1(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
res = mc.is_valid_move((0, 0), (1, 0))
self.assertEqual(res, True)
def test_is_valid_move_2(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
res = mc.is_valid_move((0, 0), (0, 1))
self.assertEqual(res, False)
def test_is_valid_move_3(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
res = mc.is_valid_move((-1, 0), (0, 1))
self.assertEqual(res, False)
def test_is_valid_move_4(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
res = mc.is_valid_move((0, 0), (0, 0))
self.assertEqual(res, False)
def test_is_valid_move_5(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
res = mc.is_valid_move((300, 0), (0, 0))
self.assertEqual(res, False)
def test_is_valid_move_6(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'a', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
res = mc.is_valid_move((0, 2), (0, 0))
self.assertEqual(res, False)
class MahjongConnectTestHasPath(unittest.TestCase):
def test_has_path_1(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
res = mc.has_path((0, 0), (1, 0))
self.assertEqual(res, True)
def test_has_path_2(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
res = mc.has_path((0, 0), (0, 0))
self.assertEqual(res, True)
def test_has_path_3(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
res = mc.has_path((0, 0), (3, 0))
self.assertEqual(res, True)
def test_has_path_4(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
res = mc.has_path((0, 0), (1, 1))
self.assertEqual(res, False)
def test_has_path_5(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
res = mc.has_path((300, 0), (1, 1))
self.assertEqual(res, False)
def test_has_path_6(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'a', 'a', 'a'],
['a', 'a', 'a', 'a'],
['a', 'a', 'a', 'a'],
['a', 'a', 'a', 'a']]
res = mc.has_path((0, 0), (3, 3))
self.assertEqual(res, True)
class MahjongConnectTestRemoveIcons(unittest.TestCase):
def test_remove_icons_1(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
mc.remove_icons((0, 0), (1, 0))
self.assertEqual(mc.board, [[' ', 'b', 'c', 'a'],
[' ', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']])
def test_remove_icons_2(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
mc.remove_icons((2, 0), (1, 0))
self.assertEqual(mc.board, [['a', 'b', 'c', 'a'],
[' ', 'b', 'c', 'a'],
[' ', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']])
def test_remove_icons_3(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
mc.remove_icons((1, 1), (0, 1))
self.assertEqual(mc.board, [['a', ' ', 'c', 'a'],
['a', ' ', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']])
def test_remove_icons_4(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
mc.remove_icons((3, 0), (2, 0))
self.assertEqual(mc.board, [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
[' ', 'b', 'c', 'a'],
[' ', 'b', 'c', 'a']])
def test_remove_icons_5(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
mc.remove_icons((3, 3), (2, 3))
self.assertEqual(mc.board, [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', ' '],
['a', 'b', 'c', ' ']])
class MahjongConnectTestIsGameOver(unittest.TestCase):
def test_is_game_over_1(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ']]
res = mc.is_game_over()
self.assertEqual(res, True)
def test_is_game_over_2(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', ' ', ' ', ' '],
['a', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ']]
res = mc.is_game_over()
self.assertEqual(res, False)
def test_is_game_over_3(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [[' ', ' ', ' ', ' '],
['a', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ']]
res = mc.is_game_over()
self.assertEqual(res, False)
def test_is_game_over_4(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['1', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ']]
res = mc.is_game_over()
self.assertEqual(res, False)
def test_is_game_over_5(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.board = [['a', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ']]
res = mc.is_game_over()
self.assertEqual(res, False)
class MahjongConnectTest(unittest.TestCase):
def test_mahjongconnect(self):
mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
self.assertEqual(mc.BOARD_SIZE, [4, 4])
self.assertEqual(mc.ICONS, ['a', 'b', 'c'])
for row in mc.board:
for icon in row:
self.assertIn(icon, mc.ICONS)
mc.board = [['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']]
res = mc.is_valid_move((0, 0), (1, 0))
self.assertEqual(res, True)
res = mc.has_path((0, 0), (1, 0))
self.assertEqual(res, True)
mc.remove_icons((0, 0), (1, 0))
self.assertEqual(mc.board, [[' ', 'b', 'c', 'a'],
[' ', 'b', 'c', 'a'],
['a', 'b', 'c', 'a'],
['a', 'b', 'c', 'a']])
mc.board = [[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ']]
res = mc.is_game_over()
self.assertEqual(res, True) | import random
class MahjongConnect:
def __init__(self, BOARD_SIZE, ICONS):
self.BOARD_SIZE = BOARD_SIZE
self.ICONS = ICONS
self.board = self.create_board()
def create_board(self):
board = [[random.choice(self.ICONS) for _ in range(self.BOARD_SIZE[1])] for _ in range(self.BOARD_SIZE[0])]
return board
def is_valid_move(self, pos1, pos2):
x1, y1 = pos1
x2, y2 = pos2
# Check if positions are within the game board range
if not (0 <= x1 < self.BOARD_SIZE[0] and 0 <= y1 < self.BOARD_SIZE[1] and 0 <= x2 < self.BOARD_SIZE[
0] and 0 <= y2 <
self.BOARD_SIZE[1]):
return False
# Check if the two positions are the same
if pos1 == pos2:
return False
# Check if the two positions have the same icon
if self.board[x1][y1] != self.board[x2][y2]:
return False
# Check if there is a valid path between the two positions
if not self.has_path(pos1, pos2):
return False
return True
def has_path(self, pos1, pos2):
visited = set()
stack = [pos1]
while stack:
current_pos = stack.pop()
if current_pos == pos2:
return True
if current_pos in visited:
continue
visited.add(current_pos)
x, y = current_pos
# Check adjacent positions (up, down, left, right)
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
new_x, new_y = x + dx, y + dy
if 0 <= new_x < self.BOARD_SIZE[0] and 0 <= new_y < self.BOARD_SIZE[1]:
if (new_x, new_y) not in visited and self.board[new_x][new_y] == self.board[x][y]:
stack.append((new_x, new_y))
return False
def remove_icons(self, pos1, pos2):
x1, y1 = pos1
x2, y2 = pos2
self.board[x1][y1] = ' '
self.board[x2][y2] = ' '
def is_game_over(self):
for row in self.board:
if any(icon != ' ' for icon in row):
return False
return True | [
"import random"
] | """
MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over.
"""
| [
{
"method_name": "create_board",
"method_description": "def create_board(self):\n \"\"\"\n create the game board with the given board size and icons\n :return: 2-dimensional list, the game board\n >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n >>> mc.create_board()\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n \"\"\"",
"test_class": "MahjongConnectTestCreateBoard",
"test_code": "class MahjongConnectTestCreateBoard(unittest.TestCase):\n def test_create_board_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [4, 4])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n def test_create_board_2(self):\n mc = MahjongConnect([2, 2], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [2, 2])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n def test_create_board_3(self):\n mc = MahjongConnect([3, 3], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [3, 3])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n def test_create_board_4(self):\n mc = MahjongConnect([1, 1], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [1, 1])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n def test_create_board_5(self):\n mc = MahjongConnect([5, 5], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [5, 5])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)",
"solution_code": "def create_board(self):\n board = [[random.choice(self.ICONS) for _ in range(self.BOARD_SIZE[1])] for _ in range(self.BOARD_SIZE[0])]\n return board",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"random"
],
"field_dependencies": [
"self.BOARD_SIZE",
"self.ICONS"
],
"method_dependencies": []
}
},
{
"method_name": "is_valid_move",
"method_description": "def is_valid_move(self, pos1, pos2):\n \"\"\"\n check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions)\n :param pos1: position tuple(x, y) of the first icon\n :param pos2: position tuple(x, y) of the second icon\n :return:True or False ,representing whether the move of two icons is valid\n >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n >>> mc.is_valid_move((0, 0), (1, 0))\n True\n \"\"\"",
"test_class": "MahjongConnectTestIsValidMove",
"test_code": "class MahjongConnectTestIsValidMove(unittest.TestCase):\n def test_is_valid_move_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((0, 0), (1, 0))\n self.assertEqual(res, True)\n\n def test_is_valid_move_2(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((0, 0), (0, 1))\n self.assertEqual(res, False)\n\n def test_is_valid_move_3(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((-1, 0), (0, 1))\n self.assertEqual(res, False)\n\n def test_is_valid_move_4(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((0, 0), (0, 0))\n self.assertEqual(res, False)\n\n def test_is_valid_move_5(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((300, 0), (0, 0))\n self.assertEqual(res, False)\n\n def test_is_valid_move_6(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'a', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((0, 2), (0, 0))\n self.assertEqual(res, False)",
"solution_code": "def is_valid_move(self, pos1, pos2):\n x1, y1 = pos1\n x2, y2 = pos2\n\n # Check if positions are within the game board range\n if not (0 <= x1 < self.BOARD_SIZE[0] and 0 <= y1 < self.BOARD_SIZE[1] and 0 <= x2 < self.BOARD_SIZE[\n 0] and 0 <= y2 <\n self.BOARD_SIZE[1]):\n return False\n\n # Check if the two positions are the same\n if pos1 == pos2:\n return False\n\n # Check if the two positions have the same icon\n if self.board[x1][y1] != self.board[x2][y2]:\n return False\n\n # Check if there is a valid path between the two positions\n if not self.has_path(pos1, pos2):\n return False\n\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.BOARD_SIZE",
"self.board"
],
"method_dependencies": [
"has_path"
]
}
},
{
"method_name": "has_path",
"method_description": "def has_path(self, pos1, pos2):\n \"\"\"\n check if there is a path between two icons\n :param pos1: position tuple(x, y) of the first icon\n :param pos2: position tuple(x, y) of the second icon\n :return: True or False ,representing whether there is a path between two icons\n >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n >>> mc.is_valid_move((0, 0), (1, 0))\n True\n \"\"\"",
"test_class": "MahjongConnectTestHasPath",
"test_code": "class MahjongConnectTestHasPath(unittest.TestCase):\n def test_has_path_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((0, 0), (1, 0))\n self.assertEqual(res, True)\n\n def test_has_path_2(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((0, 0), (0, 0))\n self.assertEqual(res, True)\n\n def test_has_path_3(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((0, 0), (3, 0))\n self.assertEqual(res, True)\n\n def test_has_path_4(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((0, 0), (1, 1))\n self.assertEqual(res, False)\n\n def test_has_path_5(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((300, 0), (1, 1))\n self.assertEqual(res, False)\n\n def test_has_path_6(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'a', 'a', 'a'],\n ['a', 'a', 'a', 'a'],\n ['a', 'a', 'a', 'a'],\n ['a', 'a', 'a', 'a']]\n res = mc.has_path((0, 0), (3, 3))\n self.assertEqual(res, True)",
"solution_code": "def has_path(self, pos1, pos2):\n visited = set()\n stack = [pos1]\n\n while stack:\n current_pos = stack.pop()\n if current_pos == pos2:\n return True\n\n if current_pos in visited:\n continue\n\n visited.add(current_pos)\n x, y = current_pos\n\n # Check adjacent positions (up, down, left, right)\n for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n new_x, new_y = x + dx, y + dy\n if 0 <= new_x < self.BOARD_SIZE[0] and 0 <= new_y < self.BOARD_SIZE[1]:\n if (new_x, new_y) not in visited and self.board[new_x][new_y] == self.board[x][y]:\n stack.append((new_x, new_y))\n\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.BOARD_SIZE",
"self.board"
],
"method_dependencies": []
}
},
{
"method_name": "remove_icons",
"method_description": "def remove_icons(self, pos1, pos2):\n \"\"\"\n remove the connected icons on the game board\n :param pos1: position tuple(x, y) of the first icon to be removed\n :param pos2: position tuple(x, y) of the second icon to be removed\n :return: None\n >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n >>> mc.remove_icons((0, 0), (1, 0))\n mc.board = [[' ', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n \"\"\"",
"test_class": "MahjongConnectTestRemoveIcons",
"test_code": "class MahjongConnectTestRemoveIcons(unittest.TestCase):\n def test_remove_icons_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((0, 0), (1, 0))\n self.assertEqual(mc.board, [[' ', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']])\n\n def test_remove_icons_2(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((2, 0), (1, 0))\n self.assertEqual(mc.board, [['a', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']])\n\n def test_remove_icons_3(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((1, 1), (0, 1))\n self.assertEqual(mc.board, [['a', ' ', 'c', 'a'],\n ['a', ' ', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']])\n\n def test_remove_icons_4(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((3, 0), (2, 0))\n self.assertEqual(mc.board, [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a']])\n\n def test_remove_icons_5(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((3, 3), (2, 3))\n self.assertEqual(mc.board, [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', ' '],\n ['a', 'b', 'c', ' ']])",
"solution_code": "def remove_icons(self, pos1, pos2):\n x1, y1 = pos1\n x2, y2 = pos2\n self.board[x1][y1] = ' '\n self.board[x2][y2] = ' '",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.board"
],
"method_dependencies": []
}
},
{
"method_name": "is_game_over",
"method_description": "def is_game_over(self):\n \"\"\"\n Check if the game is over (i.e., if there are no more icons on the game board)\n :return: True or False ,representing whether the game is over\n >>> mc = MahjongConnect([4, 4] ['a', 'b', 'c'])\n >>> mc.board = [[' ', ' ', ' ', ' '],\n >>> [' ', ' ', ' ', ' '],\n >>> [' ', ' ', ' ', ' '],\n >>> [' ', ' ', ' ', ' ']]\n >>> mc.is_game_over()\n True\n \"\"\"",
"test_class": "MahjongConnectTestIsGameOver",
"test_code": "class MahjongConnectTestIsGameOver(unittest.TestCase):\n def test_is_game_over_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [[' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, True)\n\n def test_is_game_over_2(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', ' ', ' ', ' '],\n ['a', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, False)\n\n def test_is_game_over_3(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [[' ', ' ', ' ', ' '],\n ['a', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, False)\n\n def test_is_game_over_4(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['1', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, False)\n\n def test_is_game_over_5(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, False)",
"solution_code": "def is_game_over(self):\n for row in self.board:\n if any(icon != ' ' for icon in row):\n return False\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.board"
],
"method_dependencies": []
}
}
] | MahjongConnect | [
"MahjongConnectTestCreateBoard",
"MahjongConnectTestIsValidMove",
"MahjongConnectTestHasPath",
"MahjongConnectTestRemoveIcons",
"MahjongConnectTestIsGameOver",
"MahjongConnectTest"
] | class MahjongConnect:
def __init__(self, BOARD_SIZE, ICONS):
"""
initialize the board size and the icon list, create the game board
:param BOARD_SIZE: list of two integer numbers, representing the number of rows and columns of the game board
:param ICONS: list of string, representing the icons
>>>mc = MahjongConnect([4, 4], ['a', 'b', 'c'])
mc.BOARD_SIZE = [4, 4]
mc.ICONS = ['a', 'b', 'c']
mc.board = mc.create_board()
"""
self.BOARD_SIZE = BOARD_SIZE
self.ICONS = ICONS
self.board = self.create_board()
| [
"self.BOARD_SIZE",
"self.ICONS",
"self.board"
] |
ClassEval_55 | class Manacher:
"""
his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string.
"""
def __init__(self, input_string) -> None:
"""
Initializes the Manacher class with the given input_string.
:param input_string: The input_string to be searched, str.
"""
self.input_string = input_string
def palindromic_length(self, center, diff, string):
"""
Recursively calculates the length of the palindromic substring based on a given center, difference value, and input string.
:param center: The center of the palindromic substring, int.
:param diff: The difference between the center and the current position, int.
:param string: The string to be searched, str.
:return: The length of the palindromic substring, int.
>>> manacher = Manacher('ababa')
>>> manacher.palindromic_length(2, 1, 'a|b|a|b|a')
2
"""
def palindromic_string(self):
"""
Finds the longest palindromic substring in the given string.
:return: The longest palindromic substring, str.
>>> manacher = Manacher('ababaxse')
>>> manacher.palindromic_string()
'ababa'
""" | import unittest
class ManacherTestPalindromicLength(unittest.TestCase):
def test_palindromic_length(self):
manacher = Manacher('ababa')
self.assertEqual(manacher.palindromic_length(2, 1, 'a|b|a|b|a'), 2)
def test_palindromic_length_2(self):
manacher = Manacher('ababaxse')
self.assertEqual(manacher.palindromic_length(2, 1, 'a|b|a|b|a|x|s|e'), 2)
def test_palindromic_length_3(self):
manacher = Manacher('ababax')
self.assertEqual(manacher.palindromic_length(2, 3, 'a|b|a|b|a|x'), 0)
def test_palindromic_length_4(self):
manacher = Manacher('ababax')
self.assertEqual(manacher.palindromic_length(9, 2, 'a|b|a|b|a|x'), 0)
def test_palindromic_length_5(self):
manacher = Manacher('ababax')
self.assertEqual(manacher.palindromic_length(4, 1, 'a|b|a|b|a|x'), 4)
class ManacherTestPalindromicString(unittest.TestCase):
def test_palindromic_string(self):
manacher = Manacher('ababaxse')
self.assertEqual(manacher.palindromic_string(), 'ababa')
def test_palindromic_string_2(self):
manacher = Manacher('ababax')
self.assertEqual(manacher.palindromic_string(), 'ababa')
def test_palindromic_string_3(self):
manacher = Manacher('ababax')
self.assertEqual(manacher.palindromic_string(), 'ababa')
def test_palindromic_string_4(self):
manacher = Manacher('ababaxssss')
self.assertEqual(manacher.palindromic_string(), 'ababa')
def test_palindromic_string_5(self):
manacher = Manacher('abab')
self.assertEqual(manacher.palindromic_string(), 'aba')
class ManacherTestMain(unittest.TestCase):
def test_main(self):
manacher = Manacher('ababa')
self.assertEqual(manacher.palindromic_length(2, 1, 'a|b|a|b|a'), 2)
self.assertEqual(manacher.palindromic_string(), 'ababa') | class Manacher:
def __init__(self, input_string) -> None:
self.input_string = input_string
def palindromic_length(self, center, diff, string):
if (center - diff == -1 or center + diff == len(string)
or string[center - diff] != string[center + diff]):
return 0
return 1 + self.palindromic_length(center, diff + 1, string)
def palindromic_string(self):
max_length = 0
new_input_string = ""
output_string = ""
for i in self.input_string[:len(self.input_string) - 1]:
new_input_string += i + "|"
new_input_string += self.input_string[-1]
for i in range(len(new_input_string)):
length =self.palindromic_length(i, 1, new_input_string)
if max_length < length:
max_length = length
start = i
for i in new_input_string[start - max_length:start + max_length + 1]:
if i != "|":
output_string += i
return output_string | [] | """
his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string.
"""
| [
{
"method_name": "palindromic_length",
"method_description": "def palindromic_length(self, center, diff, string):\n \"\"\"\n Recursively calculates the length of the palindromic substring based on a given center, difference value, and input string.\n :param center: The center of the palindromic substring, int.\n :param diff: The difference between the center and the current position, int.\n :param string: The string to be searched, str.\n :return: The length of the palindromic substring, int.\n >>> manacher = Manacher('ababa')\n >>> manacher.palindromic_length(2, 1, 'a|b|a|b|a')\n 2\n\n \"\"\"",
"test_class": "ManacherTestPalindromicLength",
"test_code": "class ManacherTestPalindromicLength(unittest.TestCase):\n def test_palindromic_length(self):\n manacher = Manacher('ababa')\n self.assertEqual(manacher.palindromic_length(2, 1, 'a|b|a|b|a'), 2)\n def test_palindromic_length_2(self):\n manacher = Manacher('ababaxse')\n self.assertEqual(manacher.palindromic_length(2, 1, 'a|b|a|b|a|x|s|e'), 2)\n\n def test_palindromic_length_3(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_length(2, 3, 'a|b|a|b|a|x'), 0)\n\n def test_palindromic_length_4(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_length(9, 2, 'a|b|a|b|a|x'), 0)\n\n def test_palindromic_length_5(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_length(4, 1, 'a|b|a|b|a|x'), 4)",
"solution_code": "def palindromic_length(self, center, diff, string):\n if (center - diff == -1 or center + diff == len(string)\n or string[center - diff] != string[center + diff]):\n return 0\n return 1 + self.palindromic_length(center, diff + 1, string)",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "palindromic_string",
"method_description": "def palindromic_string(self):\n \"\"\"\n Finds the longest palindromic substring in the given string.\n :return: The longest palindromic substring, str.\n >>> manacher = Manacher('ababaxse')\n >>> manacher.palindromic_string()\n 'ababa'\n\n \"\"\"",
"test_class": "ManacherTestPalindromicString",
"test_code": "class ManacherTestPalindromicString(unittest.TestCase):\n def test_palindromic_string(self):\n manacher = Manacher('ababaxse')\n self.assertEqual(manacher.palindromic_string(), 'ababa')\n\n def test_palindromic_string_2(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_string(), 'ababa')\n\n def test_palindromic_string_3(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_string(), 'ababa')\n\n def test_palindromic_string_4(self):\n manacher = Manacher('ababaxssss')\n self.assertEqual(manacher.palindromic_string(), 'ababa')\n\n def test_palindromic_string_5(self):\n manacher = Manacher('abab')\n self.assertEqual(manacher.palindromic_string(), 'aba')",
"solution_code": "def palindromic_string(self):\n max_length = 0\n\n new_input_string = \"\"\n output_string = \"\"\n\n for i in self.input_string[:len(self.input_string) - 1]:\n new_input_string += i + \"|\"\n new_input_string += self.input_string[-1]\n\n for i in range(len(new_input_string)):\n\n length =self.palindromic_length(i, 1, new_input_string)\n\n if max_length < length:\n max_length = length\n start = i\n\n for i in new_input_string[start - max_length:start + max_length + 1]:\n if i != \"|\":\n output_string += i\n\n return output_string",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.input_string"
],
"method_dependencies": [
"palindromic_length"
]
}
}
] | Manacher | [
"ManacherTestPalindromicLength",
"ManacherTestPalindromicString",
"ManacherTestMain"
] | class Manacher:
def __init__(self, input_string) -> None:
"""
Initializes the Manacher class with the given input_string.
:param input_string: The input_string to be searched, str.
"""
self.input_string = input_string
| [
"self.input_string"
] |
ClassEval_56 | class MetricsCalculator:
"""
The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels.
"""
def __init__(self):
"""
Initialize the number of all four samples to 0
"""
self.true_positives = 0
self.false_positives = 0
self.false_negatives = 0
self.true_negatives = 0
def update(self, predicted_labels, true_labels):
"""
Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives)
:param predicted_labels: list, predicted results
:param true_labels: list, true labels
:return: None, change the number of corresponding samples
>>> mc = MetricsCalculator()
>>> mc.update([1, 1, 0, 0], [1, 0, 0, 1])
(self.true_positives, self.false_positives, self.false_negatives, self.true_negatives) = (1, 1, 1, 1)
"""
def precision(self, predicted_labels, true_labels):
"""
Calculate precision
:param predicted_labels: list, predicted results
:param true_labels: list, true labels
:return: float
>>> mc = MetricsCalculator()
>>> mc.precision([1, 1, 0, 0], [1, 0, 0, 1])
0.5
"""
def recall(self, predicted_labels, true_labels):
"""
Calculate recall
:param predicted_labels: list, predicted results
:param true_labels: list, true labels
:return: float
>>> mc = MetricsCalculator()
>>> mc.recall([1, 1, 0, 0], [1, 0, 0, 1])
0.5
"""
def f1_score(self, predicted_labels, true_labels):
"""
Calculate f1 score, which is the harmonic mean of precision and recall
:param predicted_labels: list, predicted results
:param true_labels: list, true labels
:return: float
>>> mc = MetricsCalculator()
>>> mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1])
0.5
"""
def accuracy(self, predicted_labels, true_labels):
"""
Calculate accuracy
:param predicted_labels: list, predicted results
:param true_labels: list, true labels
:return: float
>>> mc = MetricsCalculator()
>>>mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1])
0.5
""" | import unittest
class MetricsCalculatorTestUpdate(unittest.TestCase):
def test_update_1(self):
mc = MetricsCalculator()
self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))
mc.update([1, 1, 0, 0], [1, 0, 0, 1])
self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 1, 1, 1))
def test_update_2(self):
mc = MetricsCalculator()
self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))
mc.update([1, 1, 1, 0], [1, 0, 0, 1])
self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 2, 1, 0))
def test_update_3(self):
mc = MetricsCalculator()
self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))
mc.update([1, 1, 0, 1], [1, 0, 0, 1])
self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (2, 1, 0, 1))
def test_update_4(self):
mc = MetricsCalculator()
self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))
mc.update([1, 1, 0, 0], [1, 1, 0, 1])
self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (2, 0, 1, 1))
def test_update_5(self):
mc = MetricsCalculator()
self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))
mc.update([1, 1, 0, 0], [1, 0, 1, 1])
self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 1, 2, 0))
class MetricsCalculatorTestPrecision(unittest.TestCase):
def test_precision_1(self):
mc = MetricsCalculator()
temp = mc.precision([1, 1, 0, 0], [1, 0, 0, 1])
self.assertEqual(temp, 0.5)
def test_precision_2(self):
mc = MetricsCalculator()
temp = mc.precision([1, 1, 1, 0], [1, 0, 0, 1])
self.assertAlmostEqual(temp, 0.3333333333333333)
def test_precision_3(self):
mc = MetricsCalculator()
temp = mc.precision([1, 1, 0, 1], [1, 0, 0, 1])
self.assertAlmostEqual(temp, 0.6666666666666666)
def test_precision_4(self):
mc = MetricsCalculator()
temp = mc.precision([1, 1, 0, 0], [1, 1, 0, 1])
self.assertAlmostEqual(temp, 1.0)
def test_precision_5(self):
mc = MetricsCalculator()
temp = mc.precision([1, 1, 0, 0], [1, 0, 1, 1])
self.assertAlmostEqual(temp, 0.5)
def test_precision_6(self):
mc = MetricsCalculator()
temp = mc.precision([0, 0, 0, 0], [1, 0, 1, 1])
self.assertAlmostEqual(temp, 0.0)
class MetricsCalculatorTestRecall(unittest.TestCase):
def test_recall_1(self):
mc = MetricsCalculator()
temp = mc.recall([1, 1, 0, 0], [1, 0, 0, 1])
self.assertEqual(temp, 0.5)
def test_recall_2(self):
mc = MetricsCalculator()
temp = mc.recall([1, 1, 1, 0], [1, 0, 0, 1])
self.assertEqual(temp, 0.5)
def test_recall_3(self):
mc = MetricsCalculator()
temp = mc.recall([1, 1, 0, 1], [1, 0, 0, 1])
self.assertEqual(temp, 1.0)
def test_recall_4(self):
mc = MetricsCalculator()
temp = mc.recall([1, 1, 0, 0], [1, 1, 0, 1])
self.assertAlmostEqual(temp, 0.6666666666666666)
def test_recall_5(self):
mc = MetricsCalculator()
temp = mc.recall([1, 1, 0, 0], [1, 0, 1, 1])
self.assertAlmostEqual(temp, 0.3333333333333333)
def test_recall_6(self):
mc = MetricsCalculator()
temp = mc.recall([1, 1, 0, 0], [0, 0, 0, 0])
self.assertEqual(temp, 0.0)
class MetricsCalculatorTestF1Score(unittest.TestCase):
def test_f1_score_1(self):
mc = MetricsCalculator()
temp = mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1])
self.assertEqual(temp, 0.5)
def test_f1_score_2(self):
mc = MetricsCalculator()
temp = mc.f1_score([1, 1, 1, 0], [1, 0, 0, 1])
self.assertEqual(temp, 0.4)
def test_f1_score_3(self):
mc = MetricsCalculator()
temp = mc.f1_score([1, 1, 0, 1], [1, 0, 0, 1])
self.assertEqual(temp, 0.8)
def test_f1_score_4(self):
mc = MetricsCalculator()
temp = mc.f1_score([1, 1, 0, 0], [1, 1, 0, 1])
self.assertEqual(temp, 0.8)
def test_f1_score_5(self):
mc = MetricsCalculator()
temp = mc.f1_score([1, 1, 0, 0], [1, 0, 1, 1])
self.assertEqual(temp, 0.4)
def test_f1_score_6(self):
mc = MetricsCalculator()
temp = mc.f1_score([0, 0, 0, 0], [0, 0, 0, 0])
self.assertEqual(temp, 0.0)
class MetricsCalculatorTestAccuracy(unittest.TestCase):
def test_accuracy_1(self):
mc = MetricsCalculator()
temp = mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1])
self.assertEqual(temp, 0.5)
def test_accuracy_2(self):
mc = MetricsCalculator()
temp = mc.accuracy([1, 1, 2, 0], [1, 0, 0, 1])
self.assertAlmostEqual(temp, 0.3333333333333333)
def test_accuracy_3(self):
mc = MetricsCalculator()
temp = mc.accuracy([1, 1, 0, 1], [1, 0, 0, 1])
self.assertEqual(temp, 0.75)
def test_accuracy_4(self):
mc = MetricsCalculator()
temp = mc.accuracy([1, 1, 0, 0], [1, 1, 0, 1])
self.assertEqual(temp, 0.75)
def test_accuracy_5(self):
mc = MetricsCalculator()
temp = mc.accuracy([1, 1, 0, 0], [1, 0, 1, 1])
self.assertEqual(temp, 0.25)
def test_accuracy_6(self):
mc = MetricsCalculator()
temp = mc.accuracy([], [])
self.assertEqual(temp, 0.0)
class MetricsCalculatorTest(unittest.TestCase):
def test_metricscalculator(self):
mc = MetricsCalculator()
self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))
mc.update([1, 1, 0, 0], [1, 0, 0, 1])
self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 1, 1, 1))
temp = mc.precision([1, 1, 0, 0], [1, 0, 0, 1])
self.assertEqual(temp, 0.5)
temp = mc.recall([1, 1, 0, 0], [1, 0, 0, 1])
self.assertEqual(temp, 0.5)
temp = mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1])
self.assertEqual(temp, 0.5)
temp = mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1])
self.assertEqual(temp, 0.5) | class MetricsCalculator:
def __init__(self):
self.true_positives = 0
self.false_positives = 0
self.false_negatives = 0
self.true_negatives = 0
def update(self, predicted_labels, true_labels):
for predicted, true in zip(predicted_labels, true_labels):
if predicted == 1 and true == 1:
self.true_positives += 1
elif predicted == 1 and true == 0:
self.false_positives += 1
elif predicted == 0 and true == 1:
self.false_negatives += 1
elif predicted == 0 and true == 0:
self.true_negatives += 1
def precision(self, predicted_labels, true_labels):
self.update(predicted_labels, true_labels)
if self.true_positives + self.false_positives == 0:
return 0.0
return self.true_positives / (self.true_positives + self.false_positives)
def recall(self, predicted_labels, true_labels):
self.update(predicted_labels, true_labels)
if self.true_positives + self.false_negatives == 0:
return 0.0
return self.true_positives / (self.true_positives + self.false_negatives)
def f1_score(self, predicted_labels, true_labels):
self.update(predicted_labels, true_labels)
precision = self.precision(predicted_labels, true_labels)
recall = self.recall(predicted_labels, true_labels)
if precision + recall == 0.0:
return 0.0
return (2 * precision * recall) / (precision + recall)
def accuracy(self, predicted_labels, true_labels):
self.update(predicted_labels, true_labels)
total = self.true_positives + self.true_negatives + self.false_positives + self.false_negatives
if total == 0:
return 0.0
return (self.true_positives + self.true_negatives) / total | [] | """
The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels.
"""
| [
{
"method_name": "update",
"method_description": "def update(self, predicted_labels, true_labels):\n \"\"\"\n Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives)\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: None, change the number of corresponding samples\n >>> mc = MetricsCalculator()\n >>> mc.update([1, 1, 0, 0], [1, 0, 0, 1])\n (self.true_positives, self.false_positives, self.false_negatives, self.true_negatives) = (1, 1, 1, 1)\n \"\"\"",
"test_class": "MetricsCalculatorTestUpdate",
"test_code": "class MetricsCalculatorTestUpdate(unittest.TestCase):\n def test_update_1(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 1, 1, 1))\n\n def test_update_2(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 1, 0], [1, 0, 0, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 2, 1, 0))\n\n def test_update_3(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (2, 1, 0, 1))\n\n def test_update_4(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (2, 0, 1, 1))\n\n def test_update_5(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 1, 2, 0))",
"solution_code": "def update(self, predicted_labels, true_labels):\n for predicted, true in zip(predicted_labels, true_labels):\n if predicted == 1 and true == 1:\n self.true_positives += 1\n elif predicted == 1 and true == 0:\n self.false_positives += 1\n elif predicted == 0 and true == 1:\n self.false_negatives += 1\n elif predicted == 0 and true == 0:\n self.true_negatives += 1",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.false_negatives",
"self.false_positives",
"self.true_negatives",
"self.true_positives"
],
"method_dependencies": []
}
},
{
"method_name": "precision",
"method_description": "def precision(self, predicted_labels, true_labels):\n \"\"\"\n Calculate precision\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: float\n >>> mc = MetricsCalculator()\n >>> mc.precision([1, 1, 0, 0], [1, 0, 0, 1])\n 0.5\n \"\"\"",
"test_class": "MetricsCalculatorTestPrecision",
"test_code": "class MetricsCalculatorTestPrecision(unittest.TestCase):\n def test_precision_1(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_precision_2(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 1, 0], [1, 0, 0, 1])\n self.assertAlmostEqual(temp, 0.3333333333333333)\n\n def test_precision_3(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertAlmostEqual(temp, 0.6666666666666666)\n\n def test_precision_4(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertAlmostEqual(temp, 1.0)\n\n def test_precision_5(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertAlmostEqual(temp, 0.5)\n\n def test_precision_6(self):\n mc = MetricsCalculator()\n temp = mc.precision([0, 0, 0, 0], [1, 0, 1, 1])\n self.assertAlmostEqual(temp, 0.0)",
"solution_code": "def precision(self, predicted_labels, true_labels):\n self.update(predicted_labels, true_labels)\n if self.true_positives + self.false_positives == 0:\n return 0.0\n return self.true_positives / (self.true_positives + self.false_positives)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.false_positives",
"self.true_positives"
],
"method_dependencies": [
"update"
]
}
},
{
"method_name": "recall",
"method_description": "def recall(self, predicted_labels, true_labels):\n \"\"\"\n Calculate recall\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: float\n >>> mc = MetricsCalculator()\n >>> mc.recall([1, 1, 0, 0], [1, 0, 0, 1])\n 0.5\n \"\"\"",
"test_class": "MetricsCalculatorTestRecall",
"test_code": "class MetricsCalculatorTestRecall(unittest.TestCase):\n def test_recall_1(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_recall_2(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 1, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_recall_3(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertEqual(temp, 1.0)\n\n def test_recall_4(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertAlmostEqual(temp, 0.6666666666666666)\n\n def test_recall_5(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertAlmostEqual(temp, 0.3333333333333333)\n\n def test_recall_6(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 0], [0, 0, 0, 0])\n self.assertEqual(temp, 0.0)",
"solution_code": "def recall(self, predicted_labels, true_labels):\n self.update(predicted_labels, true_labels)\n if self.true_positives + self.false_negatives == 0:\n return 0.0\n return self.true_positives / (self.true_positives + self.false_negatives)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.false_negatives",
"self.true_positives"
],
"method_dependencies": [
"update"
]
}
},
{
"method_name": "f1_score",
"method_description": "def f1_score(self, predicted_labels, true_labels):\n \"\"\"\n Calculate f1 score, which is the harmonic mean of precision and recall\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: float\n >>> mc = MetricsCalculator()\n >>> mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1])\n 0.5\n \"\"\"",
"test_class": "MetricsCalculatorTestF1Score",
"test_code": "class MetricsCalculatorTestF1Score(unittest.TestCase):\n def test_f1_score_1(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_f1_score_2(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 1, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.4)\n\n def test_f1_score_3(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertEqual(temp, 0.8)\n\n def test_f1_score_4(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertEqual(temp, 0.8)\n\n def test_f1_score_5(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertEqual(temp, 0.4)\n\n def test_f1_score_6(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([0, 0, 0, 0], [0, 0, 0, 0])\n self.assertEqual(temp, 0.0)",
"solution_code": "def f1_score(self, predicted_labels, true_labels):\n self.update(predicted_labels, true_labels)\n precision = self.precision(predicted_labels, true_labels)\n recall = self.recall(predicted_labels, true_labels)\n if precision + recall == 0.0:\n return 0.0\n return (2 * precision * recall) / (precision + recall)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"update",
"precision",
"recall"
]
}
},
{
"method_name": "accuracy",
"method_description": "def accuracy(self, predicted_labels, true_labels):\n \"\"\"\n Calculate accuracy\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: float\n >>> mc = MetricsCalculator()\n >>>mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1])\n 0.5\n \"\"\"",
"test_class": "MetricsCalculatorTestAccuracy",
"test_code": "class MetricsCalculatorTestAccuracy(unittest.TestCase):\n def test_accuracy_1(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_accuracy_2(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 2, 0], [1, 0, 0, 1])\n self.assertAlmostEqual(temp, 0.3333333333333333)\n\n def test_accuracy_3(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertEqual(temp, 0.75)\n\n def test_accuracy_4(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertEqual(temp, 0.75)\n\n def test_accuracy_5(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertEqual(temp, 0.25)\n\n def test_accuracy_6(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([], [])\n self.assertEqual(temp, 0.0)",
"solution_code": "def accuracy(self, predicted_labels, true_labels):\n self.update(predicted_labels, true_labels)\n total = self.true_positives + self.true_negatives + self.false_positives + self.false_negatives\n if total == 0:\n return 0.0\n return (self.true_positives + self.true_negatives) / total",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.false_negatives",
"self.false_positives",
"self.true_negatives",
"self.true_positives"
],
"method_dependencies": [
"update"
]
}
}
] | MetricsCalculator | [
"MetricsCalculatorTestUpdate",
"MetricsCalculatorTestPrecision",
"MetricsCalculatorTestRecall",
"MetricsCalculatorTestF1Score",
"MetricsCalculatorTestAccuracy",
"MetricsCalculatorTest"
] | class MetricsCalculator:
def __init__(self):
"""
Initialize the number of all four samples to 0
"""
self.true_positives = 0
self.false_positives = 0
self.false_negatives = 0
self.true_negatives = 0
| [
"self.false_negatives",
"self.false_positives",
"self.true_negatives",
"self.true_positives"
] |
ClassEval_57 | import numpy as np
class MetricsCalculator2:
"""
The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision.
"""
def __init__(self):
pass
@staticmethod
def mrr(data):
"""
compute the MRR of the input data. MRR is a widely used evaluation index. It is the mean of reciprocal rank.
:param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground truth num),ground truth num is the total ground num.
([1,0,...],5),
or list of tuple eg. [([1,0,1,...],5),([1,0,...],6),([0,0,...],5)].
1 stands for a correct answer, 0 stands for a wrong answer.
:return: if input data is list, return the recall of this list. if the input data is list of list, return the
average recall on all list. The second return value is a list of precision for each input.
>>> MetricsCalculator2.mrr(([1, 0, 1, 0], 4))
>>> MetricsCalculator2.mrr([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])
1.0, [1.0]
0.75, [1.0, 0.5]
"""
@staticmethod
def map(data):
"""
compute the MAP of the input data. MAP is a widely used evaluation index. It is the mean of AP (average precision).
:param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground truth num),ground truth num is the total ground num.
([1,0,...],5),
or list of tuple eg. [([1,0,1,...],5),([1,0,...],6),([0,0,...],5)].
1 stands for a correct answer, 0 stands for a wrong answer.
:return: if input data is list, return the recall of this list. if the input data is list of list, return the
average recall on all list. The second return value is a list of precision for each input.
>>> MetricsCalculator2.map(([1, 0, 1, 0], 4))
>>> MetricsCalculator2.map([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])
0.41666666666666663, [0.41666666666666663]
0.3333333333333333, [0.41666666666666663, 0.25]
""" | import unittest
class MetricsCalculator2TestMrr(unittest.TestCase):
def test_mrr_1(self):
mc2 = MetricsCalculator2()
res1, res2 = MetricsCalculator2.mrr(([1, 0, 1, 0], 4))
self.assertEqual(res1, 1.0)
self.assertEqual(res2, [1.0])
def test_mrr_2(self):
res1, res2 = MetricsCalculator2.mrr(([0, 0, 0, 1], 4))
self.assertEqual(res1, 0.25)
self.assertEqual(res2, [0.25])
def test_mrr_3(self):
res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])
self.assertEqual(res1, 0.75)
self.assertEqual(res2, [1.0, 0.5])
def test_mrr_4(self):
res1, res2 = MetricsCalculator2.mrr([([1, 1, 1, 0], 4), ([0, 0, 0, 1], 4)])
self.assertEqual(res1, 0.625)
self.assertEqual(res2, [1.0, 0.25])
def test_mrr_5(self):
res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 1], 4), ([0, 1, 0, 0], 4)])
self.assertEqual(res1, 0.75)
self.assertEqual(res2, [1.0, 0.5])
def test_mrr_6(self):
try:
MetricsCalculator2.mrr(1)
except:
pass
def test_mrr_7(self):
res1, res2 = MetricsCalculator2.mrr([])
self.assertEqual(res1, 0.0)
self.assertEqual(res2, [0.0])
def test_mrr_8(self):
res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 1], 0), ([0, 1, 0, 0], 0)])
self.assertEqual(res1, 0.0)
self.assertEqual(res2, [0.0, 0.0])
class MetricsCalculator2TestMap(unittest.TestCase):
def test_map_1(self):
res1, res2 = MetricsCalculator2.map(([1, 0, 1, 0], 4))
self.assertEqual(res1, 0.41666666666666663)
self.assertEqual(res2, [0.41666666666666663])
def test_map_2(self):
res1, res2 = MetricsCalculator2.map(([0, 0, 0, 1], 4))
self.assertEqual(res1, 0.0625)
self.assertEqual(res2, [0.0625])
def test_map_3(self):
res1, res2 = MetricsCalculator2.map([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])
self.assertEqual(res1, 0.3333333333333333)
self.assertEqual(res2, [0.41666666666666663, 0.25])
def test_map_4(self):
res1, res2 = MetricsCalculator2.map([([1, 1, 1, 0], 4), ([0, 0, 0, 1], 4)])
self.assertEqual(res1, 0.40625)
self.assertEqual(res2, [0.75, 0.0625])
def test_map_5(self):
res1, res2 = MetricsCalculator2.map([([1, 0, 1, 1], 4), ([0, 1, 0, 0], 4)])
self.assertEqual(res1, 0.3645833333333333)
self.assertEqual(res2, [0.6041666666666666, 0.125])
def test_map_6(self):
try:
MetricsCalculator2.map(1)
except:
pass
def test_map_7(self):
res1, res2 = MetricsCalculator2.map([])
self.assertEqual(res1, 0.0)
self.assertEqual(res2, [0.0])
def test_map_8(self):
res1, res2 = MetricsCalculator2.map([([1, 0, 1, 1], 0), ([0, 1, 0, 0], 0)])
self.assertEqual(res1, 0.0)
self.assertEqual(res2, [0.0, 0.0])
class MetricsCalculator2Test(unittest.TestCase):
def test_metricscalculator2_1(self):
res1, res2 = MetricsCalculator2.mrr(([1, 0, 1, 0], 4))
self.assertEqual(res1, 1.0)
self.assertEqual(res2, [1.0])
def test_metricscalculator2_2(self):
res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])
self.assertEqual(res1, 0.75)
self.assertEqual(res2, [1.0, 0.5])
def test_metricscalculator2_3(self):
res1, res2 = MetricsCalculator2.map(([1, 0, 1, 0], 4))
self.assertEqual(res1, 0.41666666666666663)
self.assertEqual(res2, [0.41666666666666663])
def test_metricscalculator2_4(self):
res1, res2 = MetricsCalculator2.map([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])
self.assertEqual(res1, 0.3333333333333333)
self.assertEqual(res2, [0.41666666666666663, 0.25]) | import numpy as np
class MetricsCalculator2:
def __init__(self):
pass
@staticmethod
def mrr(data):
if type(data) != list and type(data) != tuple:
raise Exception("the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple")
if len(data) == 0:
return 0.0, [0.0]
if type(data) == tuple:
(sub_list, total_num) = data
sub_list = np.array(sub_list)
if total_num == 0:
return 0.0, [0.0]
else:
ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)
mr_np = sub_list * ranking_array
mr = 0.0
for team in mr_np:
if team > 0:
mr = team
break
return mr, [mr]
if type(data) == list:
separate_result = []
for (sub_list, total_num) in data:
sub_list = np.array(sub_list)
if total_num == 0:
mr = 0.0
else:
ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)
mr_np = sub_list * ranking_array
mr = 0.0
for team in mr_np:
if team > 0:
mr = team
break
separate_result.append(mr)
return np.mean(separate_result), separate_result
@staticmethod
def map(data):
if type(data) != list and type(data) != tuple:
raise Exception("the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple")
if len(data) == 0:
return 0.0, [0.0]
if type(data) == tuple:
(sub_list, total_num) = data
sub_list = np.array(sub_list)
if total_num == 0:
return 0.0, [0.0]
else:
ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)
right_ranking_list = []
count = 1
for t in sub_list:
if t == 0:
right_ranking_list.append(0)
else:
right_ranking_list.append(count)
count += 1
ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num
return ap, [ap]
if type(data) == list:
separate_result = []
for (sub_list, total_num) in data:
sub_list = np.array(sub_list)
if total_num == 0:
ap = 0.0
else:
ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)
right_ranking_list = []
count = 1
for t in sub_list:
if t == 0:
right_ranking_list.append(0)
else:
right_ranking_list.append(count)
count += 1
ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num
separate_result.append(ap)
return np.mean(separate_result), separate_result | [
"import numpy as np"
] | """
The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision.
"""
| [
{
"method_name": "mrr",
"method_description": "def mrr(data):\n \"\"\"\n compute the MRR of the input data. MRR is a widely used evaluation index. It is the mean of reciprocal rank.\n :param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground truth num),ground truth num is the total ground num.\n ([1,0,...],5),\n or list of tuple eg. [([1,0,1,...],5),([1,0,...],6),([0,0,...],5)].\n 1 stands for a correct answer, 0 stands for a wrong answer.\n :return: if input data is list, return the recall of this list. if the input data is list of list, return the\n average recall on all list. The second return value is a list of precision for each input.\n >>> MetricsCalculator2.mrr(([1, 0, 1, 0], 4))\n >>> MetricsCalculator2.mrr([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n 1.0, [1.0]\n 0.75, [1.0, 0.5]\n \"\"\"",
"test_class": "MetricsCalculator2TestMrr",
"test_code": "class MetricsCalculator2TestMrr(unittest.TestCase):\n def test_mrr_1(self):\n mc2 = MetricsCalculator2()\n res1, res2 = MetricsCalculator2.mrr(([1, 0, 1, 0], 4))\n self.assertEqual(res1, 1.0)\n self.assertEqual(res2, [1.0])\n\n def test_mrr_2(self):\n res1, res2 = MetricsCalculator2.mrr(([0, 0, 0, 1], 4))\n self.assertEqual(res1, 0.25)\n self.assertEqual(res2, [0.25])\n\n def test_mrr_3(self):\n res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n self.assertEqual(res1, 0.75)\n self.assertEqual(res2, [1.0, 0.5])\n\n def test_mrr_4(self):\n res1, res2 = MetricsCalculator2.mrr([([1, 1, 1, 0], 4), ([0, 0, 0, 1], 4)])\n self.assertEqual(res1, 0.625)\n self.assertEqual(res2, [1.0, 0.25])\n\n def test_mrr_5(self):\n res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 1], 4), ([0, 1, 0, 0], 4)])\n self.assertEqual(res1, 0.75)\n self.assertEqual(res2, [1.0, 0.5])\n\n def test_mrr_6(self):\n try:\n MetricsCalculator2.mrr(1)\n except:\n pass\n\n def test_mrr_7(self):\n res1, res2 = MetricsCalculator2.mrr([])\n self.assertEqual(res1, 0.0)\n self.assertEqual(res2, [0.0])\n\n def test_mrr_8(self):\n res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 1], 0), ([0, 1, 0, 0], 0)])\n self.assertEqual(res1, 0.0)\n self.assertEqual(res2, [0.0, 0.0])",
"solution_code": "def mrr(data):\n if type(data) != list and type(data) != tuple:\n raise Exception(\"the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple\")\n\n if len(data) == 0:\n return 0.0, [0.0]\n if type(data) == tuple:\n (sub_list, total_num) = data\n sub_list = np.array(sub_list)\n if total_num == 0:\n return 0.0, [0.0]\n else:\n ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)\n mr_np = sub_list * ranking_array\n\n mr = 0.0\n for team in mr_np:\n if team > 0:\n mr = team\n break\n return mr, [mr]\n\n if type(data) == list:\n separate_result = []\n for (sub_list, total_num) in data:\n sub_list = np.array(sub_list)\n\n if total_num == 0:\n mr = 0.0\n else:\n ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)\n mr_np = sub_list * ranking_array\n\n mr = 0.0\n for team in mr_np:\n if team > 0:\n mr = team\n break\n\n separate_result.append(mr)\n return np.mean(separate_result), separate_result",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "map",
"method_description": "@staticmethod\n def map(data):\n \"\"\"\n compute the MAP of the input data. MAP is a widely used evaluation index. It is the mean of AP (average precision).\n :param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground truth num),ground truth num is the total ground num.\n ([1,0,...],5),\n or list of tuple eg. [([1,0,1,...],5),([1,0,...],6),([0,0,...],5)].\n 1 stands for a correct answer, 0 stands for a wrong answer.\n :return: if input data is list, return the recall of this list. if the input data is list of list, return the\n average recall on all list. The second return value is a list of precision for each input.\n >>> MetricsCalculator2.map(([1, 0, 1, 0], 4))\n >>> MetricsCalculator2.map([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n 0.41666666666666663, [0.41666666666666663]\n 0.3333333333333333, [0.41666666666666663, 0.25]\n \"\"\"",
"test_class": "MetricsCalculator2TestMap",
"test_code": "class MetricsCalculator2TestMap(unittest.TestCase):\n def test_map_1(self):\n res1, res2 = MetricsCalculator2.map(([1, 0, 1, 0], 4))\n self.assertEqual(res1, 0.41666666666666663)\n self.assertEqual(res2, [0.41666666666666663])\n\n def test_map_2(self):\n res1, res2 = MetricsCalculator2.map(([0, 0, 0, 1], 4))\n self.assertEqual(res1, 0.0625)\n self.assertEqual(res2, [0.0625])\n\n def test_map_3(self):\n res1, res2 = MetricsCalculator2.map([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n self.assertEqual(res1, 0.3333333333333333)\n self.assertEqual(res2, [0.41666666666666663, 0.25])\n\n def test_map_4(self):\n res1, res2 = MetricsCalculator2.map([([1, 1, 1, 0], 4), ([0, 0, 0, 1], 4)])\n self.assertEqual(res1, 0.40625)\n self.assertEqual(res2, [0.75, 0.0625])\n\n def test_map_5(self):\n res1, res2 = MetricsCalculator2.map([([1, 0, 1, 1], 4), ([0, 1, 0, 0], 4)])\n self.assertEqual(res1, 0.3645833333333333)\n self.assertEqual(res2, [0.6041666666666666, 0.125])\n\n def test_map_6(self):\n try:\n MetricsCalculator2.map(1)\n except:\n pass\n\n def test_map_7(self):\n res1, res2 = MetricsCalculator2.map([])\n self.assertEqual(res1, 0.0)\n self.assertEqual(res2, [0.0])\n\n def test_map_8(self):\n res1, res2 = MetricsCalculator2.map([([1, 0, 1, 1], 0), ([0, 1, 0, 0], 0)])\n self.assertEqual(res1, 0.0)\n self.assertEqual(res2, [0.0, 0.0])",
"solution_code": "@staticmethod\n def map(data):\n if type(data) != list and type(data) != tuple:\n raise Exception(\"the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple\")\n\n if len(data) == 0:\n return 0.0, [0.0]\n if type(data) == tuple:\n (sub_list, total_num) = data\n sub_list = np.array(sub_list)\n if total_num == 0:\n return 0.0, [0.0]\n else:\n ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)\n\n right_ranking_list = []\n count = 1\n for t in sub_list:\n if t == 0:\n right_ranking_list.append(0)\n else:\n right_ranking_list.append(count)\n count += 1\n\n ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num\n return ap, [ap]\n\n if type(data) == list:\n separate_result = []\n for (sub_list, total_num) in data:\n sub_list = np.array(sub_list)\n\n if total_num == 0:\n ap = 0.0\n else:\n ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)\n\n right_ranking_list = []\n count = 1\n for t in sub_list:\n if t == 0:\n right_ranking_list.append(0)\n else:\n right_ranking_list.append(count)\n count += 1\n\n ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num\n\n separate_result.append(ap)\n return np.mean(separate_result), separate_result",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | MetricsCalculator2 | [
"MetricsCalculator2TestMrr",
"MetricsCalculator2TestMap",
"MetricsCalculator2Test"
] | class MetricsCalculator2:
def __init__(self):
pass
| [] |
ClassEval_58 | import random
class MinesweeperGame:
"""
This is a class that implements mine sweeping games including minesweeping and winning judgment.
"""
def __init__(self, n, k) -> None:
"""
Initializes the MinesweeperGame class with the size of the board and the number of mines.
:param n: The size of the board, int.
:param k: The number of mines, int.
"""
self.n = n
self.k = k
self.minesweeper_map = self.generate_mine_sweeper_map()
self.player_map = self.generate_playerMap()
self.score = 0
def generate_mine_sweeper_map(self):
"""
Generates a minesweeper map with the given size of the board and the number of mines,the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'X' represents the mine,other numbers represent the number of mines around the position.
:return: The minesweeper map, list.
>>> minesweeper_game = MinesweeperGame(3, 1)
>>> minesweeper_game.generate_mine_sweeper_map()
[['X', 1, 0], [1, 1, 0], [0, 0, 0]]
"""
def generate_playerMap(self):
"""
Generates a player map with the given size of the board, the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'-' represents the unknown position.
:return: The player map, list.
>>> minesweeper_game = MinesweeperGame(3, 1)
>>> minesweeper_game.generate_playerMap()
[['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
"""
def check_won(self,map):
"""
Checks whether the player has won the game,if there are just mines in the player map,return True,otherwise return False.
:return: True if the player has won the game, False otherwise.
>>> minesweeper_game = MinesweeperGame(3, 1)
>>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]
>>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
>>> minesweeper_game.check_won(minesweeper_game.player_map)
False
"""
def sweep(self, x, y):
"""
Sweeps the given position.
:param x: The x coordinate of the position, int.
:param y: The y coordinate of the position, int.
:return: True if the player has won the game, False otherwise,if the game still continues, return the player map, list.
>>> minesweeper_game = MinesweeperGame(3, 1)
>>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]
>>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
>>> minesweeper_game.sweep(1, 1)
[['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']]
""" | import unittest
class MinesweeperGameTestGenerateMineSweeperMap(unittest.TestCase):
def test_generate_mine_sweeper_map(self):
minesweeper_game = MinesweeperGame(3, 2)
length = len(minesweeper_game.minesweeper_map)
mine_num = 0
for row in minesweeper_game.minesweeper_map:
for cell in row:
if cell == 'X':
mine_num += 1
self.assertEqual(3, length)
self.assertEqual(2, mine_num)
def test_generate_mine_sweeper_map_2(self):
minesweeper_game = MinesweeperGame(3, 1)
length = len(minesweeper_game.minesweeper_map)
mine_num = 0
for row in minesweeper_game.minesweeper_map:
for cell in row:
if cell == 'X':
mine_num += 1
self.assertEqual(3, length)
self.assertEqual(1, mine_num)
def test_generate_mine_sweeper_map_3(self):
minesweeper_game = MinesweeperGame(3, 0)
length = len(minesweeper_game.minesweeper_map)
mine_num = 0
for row in minesweeper_game.minesweeper_map:
for cell in row:
if cell == 'X':
mine_num += 1
self.assertEqual(3, length)
self.assertEqual(0, mine_num)
def test_generate_mine_sweeper_map_4(self):
minesweeper_game = MinesweeperGame(5, 1)
length = len(minesweeper_game.minesweeper_map)
mine_num = 0
for row in minesweeper_game.minesweeper_map:
for cell in row:
if cell == 'X':
mine_num += 1
self.assertEqual(length,5)
self.assertEqual(mine_num, 1)
def test_generate_mine_sweeper_map_5(self):
minesweeper_game = MinesweeperGame(4, 1)
length = len(minesweeper_game.minesweeper_map)
mine_num = 0
for row in minesweeper_game.minesweeper_map:
for cell in row:
if cell == 'X':
mine_num += 1
self.assertEqual(length, 4)
self.assertEqual(mine_num, 1)
class MinesweeperGameTestGeneratePlayerMap(unittest.TestCase):
def test_generate_playerMap(self):
minesweeper_game = MinesweeperGame(3, 2)
self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])
def test_generate_playerMap_2(self):
minesweeper_game = MinesweeperGame(3, 1)
self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])
def test_generate_playerMap_3(self):
minesweeper_game = MinesweeperGame(4, 2)
self.assertEqual(minesweeper_game.generate_playerMap(),[['-', '-', '-', '-'],['-', '-', '-', '-'],['-', '-', '-', '-'],['-', '-', '-', '-']])
def test_generate_playerMap_4(self):
minesweeper_game = MinesweeperGame(1, 4)
self.assertEqual(minesweeper_game.generate_playerMap(), [['-']])
def test_generate_playerMap_5(self):
minesweeper_game = MinesweeperGame(2, 5)
self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-'], ['-', '-']])
class MinesweeperGameTestCheckWon(unittest.TestCase):
def test_check_won(self):
minesweeper_game = MinesweeperGame(3, 1)
minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]
minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)
def test_check_won_2(self):
minesweeper_game = MinesweeperGame(3, 1)
minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]
minesweeper_game.player_map = [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']]
self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)
def test_check_won_3(self):
minesweeper_game = MinesweeperGame(3, 0)
minesweeper_game.minesweeper_map = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
minesweeper_game.player_map = [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']]
self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)
def test_check_won_4(self):
minesweeper_game = MinesweeperGame(3, 1)
minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]
minesweeper_game.player_map = [['-', '1', '0'], ['1', 1, '0'], ['0', '0', '0']]
self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), True)
def test_check_won_5(self):
minesweeper_game = MinesweeperGame(3, 1)
minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]
minesweeper_game.player_map = [['X', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)
class MinesweeperGameTestSweep(unittest.TestCase):
def test_sweep(self):
minesweeper_game = MinesweeperGame(3, 1)
minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]
minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
self.assertEqual(minesweeper_game.sweep(1,1), [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']])
self.assertEqual(minesweeper_game.score, 1)
def test_sweep_2(self):
minesweeper_game = MinesweeperGame(3, 1)
minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]
minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
self.assertEqual(minesweeper_game.sweep(0,0), False)
self.assertEqual(minesweeper_game.score, 0)
def test_sweep_3(self):
minesweeper_game = MinesweeperGame(3, 1)
minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]
minesweeper_game.player_map = [['-', '-', '0'], ['1', '1', '0'], ['0', '0', '0']]
self.assertEqual(minesweeper_game.sweep(0,1), True)
self.assertEqual(minesweeper_game.score, 1)
def test_sweep_4(self):
minesweeper_game = MinesweeperGame(3, 1)
minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]
minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '0'], ['0', '0', '0']]
self.assertEqual(minesweeper_game.sweep(0,2), [['-', '-', 0], ['-', '-', '0'], ['0', '0', '0']])
self.assertEqual(minesweeper_game.score, 1)
def test_sweep_5(self):
minesweeper_game = MinesweeperGame(3, 1)
minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]
minesweeper_game.player_map = [['-', '-', '0'], ['-', '1', '0'], ['0', '0', '0']]
self.assertEqual(minesweeper_game.sweep(1,0), [['-', '-', '0'], [1, '1', '0'], ['0', '0', '0']])
self.assertEqual(minesweeper_game.score, 1)
class MinesweeperGameTestMain(unittest.TestCase):
def test_minesweeper_main(self):
minesweeper_game = MinesweeperGame(3, 1)
length = len(minesweeper_game.minesweeper_map)
mine_num = 0
for row in minesweeper_game.minesweeper_map:
for cell in row:
if cell == 'X':
mine_num += 1
self.assertEqual(3, length)
self.assertEqual(1, mine_num)
self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])
minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]
minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)
self.assertEqual(minesweeper_game.sweep(1,1), [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']])
self.assertEqual(minesweeper_game.score, 1)
def test_minesweeper_main_2(self):
minesweeper_game = MinesweeperGame(3, 2)
length = len(minesweeper_game.minesweeper_map)
mine_num = 0
for row in minesweeper_game.minesweeper_map:
for cell in row:
if cell == 'X':
mine_num += 1
self.assertEqual(3, length)
self.assertEqual(2, mine_num)
self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])
minesweeper_game.minesweeper_map = [['X', 1, 1], [1, 'X', 1], [1, 1, 1]]
self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)
self.assertEqual(minesweeper_game.sweep(0, 1), [['-', 1, '-'], ['-','-', '-'], ['-', '-', '-']])
self.assertEqual(minesweeper_game.score, 1)
self.assertEqual(minesweeper_game.sweep(0, 2), [['-', 1, 1], ['-', '-', '-'], ['-', '-', '-']])
self.assertEqual(minesweeper_game.score, 2) | import random
class MinesweeperGame:
def __init__(self, n, k) -> None:
self.n = n
self.k = k
self.minesweeper_map = self.generate_mine_sweeper_map()
self.player_map = self.generate_playerMap()
self.score = 0
def generate_mine_sweeper_map(self):
arr = [[0 for row in range(self.n)] for column in range(self.n)]
for num in range(self.k):
x = random.randint(0, self.n-1)
y = random.randint(0, self.n-1)
arr[y][x] = 'X'
if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-1):
if arr[y][x+1] != 'X':
arr[y][x+1] += 1
if (x >=1 and x <= self.n-1) and (y >= 0 and y <= self.n-1):
if arr[y][x-1] != 'X':
arr[y][x-1] += 1
if (x >= 1 and x <= self.n-1) and (y >= 1 and y <= self.n-1):
if arr[y-1][x-1] != 'X':
arr[y-1][x-1] += 1
if (x >= 0 and x <= self.n-2) and (y >= 1 and y <= self.n-1):
if arr[y-1][x+1] != 'X':
arr[y-1][x+1] += 1
if (x >= 0 and x <= self.n-1) and (y >= 1 and y <= self.n-1):
if arr[y-1][x] != 'X':
arr[y-1][x] += 1
if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-2):
if arr[y+1][x+1] != 'X':
arr[y+1][x+1] += 1
if (x >= 1 and x <= self.n-1) and (y >= 0 and y <= self.n-2):
if arr[y+1][x-1] != 'X':
arr[y+1][x-1] += 1
if (x >= 0 and x <= self.n-1) and (y >= 0 and y <= self.n-2):
if arr[y+1][x] != 'X':
arr[y+1][x] += 1
return arr
def generate_playerMap(self):
arr = [['-' for row in range(self.n)] for column in range(self.n)]
return arr
def check_won(self, map):
for i in range(self.n):
for j in range(self.n):
if map[i][j] == '-' and self.minesweeper_map[i][j] != 'X':
return False
return True
def sweep(self, x, y):
if (self.minesweeper_map[x][y] == 'X'):
return False
else:
self.player_map[x][y] = self.minesweeper_map[x][y]
self.score += 1
if self.check_won(self.player_map) == True:
return True
return self.player_map | [
"import random"
] | """
This is a class that implements mine sweeping games including minesweeping and winning judgment.
"""
| [
{
"method_name": "generate_mine_sweeper_map",
"method_description": "def generate_mine_sweeper_map(self):\n \"\"\"\n Generates a minesweeper map with the given size of the board and the number of mines,the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'X' represents the mine,other numbers represent the number of mines around the position.\n :return: The minesweeper map, list.\n >>> minesweeper_game = MinesweeperGame(3, 1)\n >>> minesweeper_game.generate_mine_sweeper_map()\n [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n\n \"\"\"",
"test_class": "MinesweeperGameTestGenerateMineSweeperMap",
"test_code": "class MinesweeperGameTestGenerateMineSweeperMap(unittest.TestCase):\n def test_generate_mine_sweeper_map(self):\n minesweeper_game = MinesweeperGame(3, 2)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(3, length)\n self.assertEqual(2, mine_num)\n\n def test_generate_mine_sweeper_map_2(self):\n minesweeper_game = MinesweeperGame(3, 1)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(3, length)\n self.assertEqual(1, mine_num)\n\n def test_generate_mine_sweeper_map_3(self):\n minesweeper_game = MinesweeperGame(3, 0)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(3, length)\n self.assertEqual(0, mine_num)\n\n def test_generate_mine_sweeper_map_4(self):\n minesweeper_game = MinesweeperGame(5, 1)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(length,5)\n self.assertEqual(mine_num, 1)\n\n def test_generate_mine_sweeper_map_5(self):\n minesweeper_game = MinesweeperGame(4, 1)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(length, 4)\n self.assertEqual(mine_num, 1)",
"solution_code": "def generate_mine_sweeper_map(self):\n arr = [[0 for row in range(self.n)] for column in range(self.n)]\n for num in range(self.k):\n x = random.randint(0, self.n-1)\n y = random.randint(0, self.n-1)\n arr[y][x] = 'X'\n if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-1):\n if arr[y][x+1] != 'X':\n arr[y][x+1] += 1\n if (x >=1 and x <= self.n-1) and (y >= 0 and y <= self.n-1):\n if arr[y][x-1] != 'X':\n arr[y][x-1] += 1\n if (x >= 1 and x <= self.n-1) and (y >= 1 and y <= self.n-1):\n if arr[y-1][x-1] != 'X':\n arr[y-1][x-1] += 1\n \n if (x >= 0 and x <= self.n-2) and (y >= 1 and y <= self.n-1):\n if arr[y-1][x+1] != 'X':\n arr[y-1][x+1] += 1 \n if (x >= 0 and x <= self.n-1) and (y >= 1 and y <= self.n-1):\n if arr[y-1][x] != 'X':\n arr[y-1][x] += 1\n \n if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-2):\n if arr[y+1][x+1] != 'X':\n arr[y+1][x+1] += 1\n if (x >= 1 and x <= self.n-1) and (y >= 0 and y <= self.n-2):\n if arr[y+1][x-1] != 'X':\n arr[y+1][x-1] += 1\n if (x >= 0 and x <= self.n-1) and (y >= 0 and y <= self.n-2):\n if arr[y+1][x] != 'X':\n arr[y+1][x] += 1\n return arr",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"random"
],
"field_dependencies": [
"self.k",
"self.n"
],
"method_dependencies": []
}
},
{
"method_name": "generate_playerMap",
"method_description": "def generate_playerMap(self):\n \"\"\"\n Generates a player map with the given size of the board, the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'-' represents the unknown position.\n :return: The player map, list.\n >>> minesweeper_game = MinesweeperGame(3, 1)\n >>> minesweeper_game.generate_playerMap()\n [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n\n \"\"\"",
"test_class": "MinesweeperGameTestGeneratePlayerMap",
"test_code": "class MinesweeperGameTestGeneratePlayerMap(unittest.TestCase):\n def test_generate_playerMap(self):\n minesweeper_game = MinesweeperGame(3, 2)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])\n\n def test_generate_playerMap_2(self):\n minesweeper_game = MinesweeperGame(3, 1)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])\n\n def test_generate_playerMap_3(self):\n minesweeper_game = MinesweeperGame(4, 2)\n self.assertEqual(minesweeper_game.generate_playerMap(),[['-', '-', '-', '-'],['-', '-', '-', '-'],['-', '-', '-', '-'],['-', '-', '-', '-']])\n\n def test_generate_playerMap_4(self):\n minesweeper_game = MinesweeperGame(1, 4)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-']])\n\n def test_generate_playerMap_5(self):\n minesweeper_game = MinesweeperGame(2, 5)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-'], ['-', '-']])",
"solution_code": "def generate_playerMap(self):\n arr = [['-' for row in range(self.n)] for column in range(self.n)]\n return arr",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.n"
],
"method_dependencies": []
}
},
{
"method_name": "check_won",
"method_description": "def check_won(self,map):\n \"\"\"\n Checks whether the player has won the game,if there are just mines in the player map,return True,otherwise return False.\n :return: True if the player has won the game, False otherwise.\n >>> minesweeper_game = MinesweeperGame(3, 1)\n >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n >>> minesweeper_game.check_won(minesweeper_game.player_map)\n False\n\n \"\"\"",
"test_class": "MinesweeperGameTestCheckWon",
"test_code": "class MinesweeperGameTestCheckWon(unittest.TestCase):\n def test_check_won(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)\n\n def test_check_won_2(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)\n\n def test_check_won_3(self):\n minesweeper_game = MinesweeperGame(3, 0)\n minesweeper_game.minesweeper_map = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)\n\n def test_check_won_4(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '1', '0'], ['1', 1, '0'], ['0', '0', '0']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), True)\n\n def test_check_won_5(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['X', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)",
"solution_code": "def check_won(self, map):\n for i in range(self.n):\n for j in range(self.n):\n if map[i][j] == '-' and self.minesweeper_map[i][j] != 'X':\n return False\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.minesweeper_map",
"self.n"
],
"method_dependencies": [
"sweep"
]
}
},
{
"method_name": "sweep",
"method_description": "def sweep(self, x, y):\n \"\"\"\n Sweeps the given position.\n :param x: The x coordinate of the position, int.\n :param y: The y coordinate of the position, int.\n :return: True if the player has won the game, False otherwise,if the game still continues, return the player map, list.\n >>> minesweeper_game = MinesweeperGame(3, 1)\n >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n >>> minesweeper_game.sweep(1, 1)\n [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']]\n\n \"\"\"",
"test_class": "MinesweeperGameTestSweep",
"test_code": "class MinesweeperGameTestSweep(unittest.TestCase):\n def test_sweep(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.sweep(1,1), [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']])\n self.assertEqual(minesweeper_game.score, 1)\n\n def test_sweep_2(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.sweep(0,0), False)\n self.assertEqual(minesweeper_game.score, 0)\n\n def test_sweep_3(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '0'], ['1', '1', '0'], ['0', '0', '0']]\n self.assertEqual(minesweeper_game.sweep(0,1), True)\n self.assertEqual(minesweeper_game.score, 1)\n\n def test_sweep_4(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '0'], ['0', '0', '0']]\n self.assertEqual(minesweeper_game.sweep(0,2), [['-', '-', 0], ['-', '-', '0'], ['0', '0', '0']])\n self.assertEqual(minesweeper_game.score, 1)\n\n def test_sweep_5(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '0'], ['-', '1', '0'], ['0', '0', '0']]\n self.assertEqual(minesweeper_game.sweep(1,0), [['-', '-', '0'], [1, '1', '0'], ['0', '0', '0']])\n self.assertEqual(minesweeper_game.score, 1)",
"solution_code": "def sweep(self, x, y):\n\n if (self.minesweeper_map[x][y] == 'X'):\n return False\n else:\n self.player_map[x][y] = self.minesweeper_map[x][y]\n self.score += 1\n if self.check_won(self.player_map) == True:\n return True\n return self.player_map",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.minesweeper_map",
"self.player_map",
"self.score"
],
"method_dependencies": [
"check_won"
]
}
}
] | MinesweeperGame | [
"MinesweeperGameTestGenerateMineSweeperMap",
"MinesweeperGameTestGeneratePlayerMap",
"MinesweeperGameTestCheckWon",
"MinesweeperGameTestSweep",
"MinesweeperGameTestMain"
] | class MinesweeperGame:
def __init__(self, n, k) -> None:
"""
Initializes the MinesweeperGame class with the size of the board and the number of mines.
:param n: The size of the board, int.
:param k: The number of mines, int.
"""
self.n = n
self.k = k
self.minesweeper_map = self.generate_mine_sweeper_map()
self.player_map = self.generate_playerMap()
self.score = 0
| [
"self.k",
"self.minesweeper_map",
"self.n",
"self.player_map",
"self.score"
] |
ClassEval_59 | from datetime import datetime
import numpy as np
class MovieBookingSystem:
"""
this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range.
"""
def __init__(self):
"""
Initialize movies contains the information about movies
>>> system.movies
[{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25),
'seats': array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])}]
"""
self.movies = []
def add_movie(self, name, price, start_time, end_time, n):
"""
Add a new movie into self.movies
:param name: str, movie name
:param price: float, price for one ticket
:param start_time: str
:param end_time: str
:param n: int, the size of seats(n*n)
>>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3)
>>> system.movies
[{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25),
'seats': array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])}]
"""
def book_ticket(self, name, seats_to_book):
"""
Book tickets for a movie. Change the seats value in self.movies if book successfully.
:param name: str, movie name
:param seats_to_book: list of tuples, representing seats to book [(row1, col1), (row2, col2), ...]
:return: str, booking status message. "Movie not found." for no such movie.
"Booking success." for successfully booking, or "Booking failed." otherwise
>>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3)
>>> system.book_ticket('Batman', [(0, 0), (0, 1)])
'Booking success.'
>>> system.book_ticket('Batman', [(0, 0)])
'Booking failed.'
>>> system.book_ticket('batman', [(0, 0)])
'Movie not found.'
"""
def available_movies(self, start_time, end_time):
"""
Get a list of available movies within the specified time range
:param start_time: str, start time in HH:MM format
:param end_time: str, end time in HH:MM format
:return: list of str, names of available movies
>>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3)
>>> system.available_movies('12:00', '22:00')
['Batman']
""" | import unittest
class MovieBookingSystemTestAddMovie(unittest.TestCase):
def setUp(self):
self.system = MovieBookingSystem()
def tearDown(self):
self.system = None
def test_add_movie_1(self):
self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)
self.assertEqual(len(self.system.movies), 1)
self.assertEqual(self.system.movies[0]['name'], 'Batman')
self.assertEqual(self.system.movies[0]['price'], 49.9)
self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))
self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))
self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))
def test_add_movie_2(self):
self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)
self.system.add_movie('Superman', 49.9, '17:05', '19:25', 3)
self.assertEqual(len(self.system.movies), 2)
self.assertEqual(self.system.movies[0]['name'], 'Batman')
self.assertEqual(self.system.movies[1]['name'], 'Superman')
def test_add_movie_3(self):
self.system.add_movie('Batman', 39.9, '17:05', '19:25', 3)
self.assertEqual(len(self.system.movies), 1)
self.assertEqual(self.system.movies[0]['name'], 'Batman')
self.assertEqual(self.system.movies[0]['price'], 39.9)
self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))
self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))
self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))
def test_add_movie_4(self):
self.system.add_movie('Batman', 29.9, '17:05', '19:25', 3)
self.assertEqual(len(self.system.movies), 1)
self.assertEqual(self.system.movies[0]['name'], 'Batman')
self.assertEqual(self.system.movies[0]['price'], 29.9)
self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))
self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))
self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))
def test_add_movie_5(self):
self.system.add_movie('Batman', 19.9, '17:05', '19:25', 3)
self.assertEqual(len(self.system.movies), 1)
self.assertEqual(self.system.movies[0]['name'], 'Batman')
self.assertEqual(self.system.movies[0]['price'], 19.9)
self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))
self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))
self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))
class MovieBookingSystemTestBookTicket(unittest.TestCase):
def setUp(self):
self.system = MovieBookingSystem()
self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)
# book successfully
def test_book_ticket_1(self):
result = self.system.book_ticket('Batman', [(0, 0), (1, 1), (2, 2)])
self.assertEqual(result, 'Booking success.')
self.assertEqual(self.system.movies[0]['seats'][0][0], 1)
self.assertEqual(self.system.movies[0]['seats'][1][1], 1)
self.assertEqual(self.system.movies[0]['seats'][2][2], 1)
# seat is not available
def test_book_ticket_2(self):
self.system.book_ticket('Batman', [(0, 0)])
result = self.system.book_ticket('Batman', [(0, 0)])
self.assertEqual(result, 'Booking failed.')
self.assertEqual(self.system.movies[0]['seats'][0][0], 1)
def test_book_ticket_3(self):
result = self.system.book_ticket('batman', [(0, 0)])
self.assertEqual(result, 'Movie not found.')
self.assertEqual(self.system.movies[0]['seats'][0][0], 0)
def test_book_ticket_4(self):
result = self.system.book_ticket('Batman', [(0, 0), (1, 1)])
self.assertEqual(result, 'Booking success.')
self.assertEqual(self.system.movies[0]['seats'][0][0], 1)
self.assertEqual(self.system.movies[0]['seats'][1][1], 1)
def test_book_ticket_5(self):
result = self.system.book_ticket('Batman', [(0, 0)])
self.assertEqual(result, 'Booking success.')
self.assertEqual(self.system.movies[0]['seats'][0][0], 1)
class MovieBookingSystemTestAvailableMovies(unittest.TestCase):
def setUp(self):
self.system = MovieBookingSystem()
self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)
self.system.add_movie('Spiderman', 59.9, '20:00', '22:30', 4)
def test_available_movies_1(self):
result = self.system.available_movies('16:00', '23:00')
self.assertEqual(result, ['Batman', 'Spiderman'])
def test_available_movies_2(self):
result = self.system.available_movies('23:00', '23:59')
self.assertEqual(result, [])
def test_available_movies_3(self):
result = self.system.available_movies('17:00', '20:00')
self.assertEqual(result, ['Batman'])
def test_available_movies_4(self):
result = self.system.available_movies('10:00', '23:00')
self.assertEqual(result, ['Batman', 'Spiderman'])
def test_available_movies_5(self):
result = self.system.available_movies('20:00', '23:00')
self.assertEqual(result, ['Spiderman'])
class MovieBookingSystemTestMain(unittest.TestCase):
def test_main(self):
system = MovieBookingSystem()
system.add_movie('Batman', 49.9, '17:05', '19:25', 3)
self.assertEqual(len(system.movies), 1)
self.assertEqual(system.movies[0]['name'], 'Batman')
self.assertEqual(system.movies[0]['price'], 49.9)
self.assertEqual(system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))
self.assertEqual(system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))
self.assertEqual(system.movies[0]['seats'].shape, (3, 3))
result = system.book_ticket('Batman', [(0, 0), (1, 1), (2, 2)])
self.assertEqual(result, 'Booking success.')
self.assertEqual(system.movies[0]['seats'][0][0], 1)
self.assertEqual(system.movies[0]['seats'][1][1], 1)
self.assertEqual(system.movies[0]['seats'][2][2], 1)
result = system.available_movies('16:00', '23:00')
self.assertEqual(result, ['Batman']) | from datetime import datetime
import numpy as np
class MovieBookingSystem:
def __init__(self):
self.movies = []
def add_movie(self, name, price, start_time, end_time, n):
movie = {
'name': name,
'price': price,
'start_time': datetime.strptime(start_time, '%H:%M'),
'end_time': datetime.strptime(end_time, '%H:%M'),
'seats': np.zeros((n, n))
}
self.movies.append(movie)
def book_ticket(self, name, seats_to_book):
for movie in self.movies:
if movie['name'] == name:
for seat in seats_to_book:
if movie['seats'][seat[0]][seat[1]] == 0:
movie['seats'][seat[0]][seat[1]] = 1
else:
return "Booking failed."
return "Booking success."
return "Movie not found."
def available_movies(self, start_time, end_time):
start_time = datetime.strptime(start_time, '%H:%M')
end_time = datetime.strptime(end_time, '%H:%M')
available_movies = []
for movie in self.movies:
if start_time <= movie['start_time'] and movie['end_time'] <= end_time:
available_movies.append(movie['name'])
return available_movies | [
"from datetime import datetime",
"import numpy as np"
] | """
this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range.
"""
| [
{
"method_name": "add_movie",
"method_description": "def add_movie(self, name, price, start_time, end_time, n):\n \"\"\"\n Add a new movie into self.movies\n :param name: str, movie name\n :param price: float, price for one ticket\n :param start_time: str\n :param end_time: str\n :param n: int, the size of seats(n*n)\n >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n >>> system.movies\n [{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25),\n 'seats': array([[0., 0., 0.],\n [0., 0., 0.],\n [0., 0., 0.]])}]\n \"\"\"",
"test_class": "MovieBookingSystemTestAddMovie",
"test_code": "class MovieBookingSystemTestAddMovie(unittest.TestCase):\n def setUp(self):\n self.system = MovieBookingSystem()\n\n def tearDown(self):\n self.system = None\n\n def test_add_movie_1(self):\n self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 1)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[0]['price'], 49.9)\n self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\n self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))\n self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))\n\n def test_add_movie_2(self):\n self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n self.system.add_movie('Superman', 49.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 2)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[1]['name'], 'Superman')\n\n def test_add_movie_3(self):\n self.system.add_movie('Batman', 39.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 1)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[0]['price'], 39.9)\n self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\n self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))\n self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))\n\n def test_add_movie_4(self):\n self.system.add_movie('Batman', 29.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 1)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[0]['price'], 29.9)\n self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\n self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))\n self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))\n\n def test_add_movie_5(self):\n self.system.add_movie('Batman', 19.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 1)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[0]['price'], 19.9)\n self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\n self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))\n self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))",
"solution_code": "def add_movie(self, name, price, start_time, end_time, n):\n movie = {\n 'name': name,\n 'price': price,\n 'start_time': datetime.strptime(start_time, '%H:%M'),\n 'end_time': datetime.strptime(end_time, '%H:%M'),\n 'seats': np.zeros((n, n))\n }\n self.movies.append(movie)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"datetime"
],
"field_dependencies": [
"self.movies"
],
"method_dependencies": []
}
},
{
"method_name": "book_ticket",
"method_description": "def book_ticket(self, name, seats_to_book):\n \"\"\"\n Book tickets for a movie. Change the seats value in self.movies if book successfully.\n :param name: str, movie name\n :param seats_to_book: list of tuples, representing seats to book [(row1, col1), (row2, col2), ...]\n :return: str, booking status message. \"Movie not found.\" for no such movie.\n \"Booking success.\" for successfully booking, or \"Booking failed.\" otherwise\n >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n >>> system.book_ticket('Batman', [(0, 0), (0, 1)])\n 'Booking success.'\n >>> system.book_ticket('Batman', [(0, 0)])\n 'Booking failed.'\n >>> system.book_ticket('batman', [(0, 0)])\n 'Movie not found.'\n \"\"\"",
"test_class": "MovieBookingSystemTestBookTicket",
"test_code": "class MovieBookingSystemTestBookTicket(unittest.TestCase):\n def setUp(self):\n self.system = MovieBookingSystem()\n self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n\n # book successfully\n def test_book_ticket_1(self):\n result = self.system.book_ticket('Batman', [(0, 0), (1, 1), (2, 2)])\n self.assertEqual(result, 'Booking success.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 1)\n self.assertEqual(self.system.movies[0]['seats'][1][1], 1)\n self.assertEqual(self.system.movies[0]['seats'][2][2], 1)\n\n # seat is not available\n def test_book_ticket_2(self):\n self.system.book_ticket('Batman', [(0, 0)])\n result = self.system.book_ticket('Batman', [(0, 0)])\n self.assertEqual(result, 'Booking failed.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 1)\n\n def test_book_ticket_3(self):\n result = self.system.book_ticket('batman', [(0, 0)])\n self.assertEqual(result, 'Movie not found.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 0)\n\n def test_book_ticket_4(self):\n result = self.system.book_ticket('Batman', [(0, 0), (1, 1)])\n self.assertEqual(result, 'Booking success.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 1)\n self.assertEqual(self.system.movies[0]['seats'][1][1], 1)\n\n def test_book_ticket_5(self):\n result = self.system.book_ticket('Batman', [(0, 0)])\n self.assertEqual(result, 'Booking success.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 1)",
"solution_code": "def book_ticket(self, name, seats_to_book):\n for movie in self.movies:\n if movie['name'] == name:\n for seat in seats_to_book:\n if movie['seats'][seat[0]][seat[1]] == 0:\n movie['seats'][seat[0]][seat[1]] = 1\n else:\n return \"Booking failed.\"\n return \"Booking success.\"\n return \"Movie not found.\"",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.movies"
],
"method_dependencies": []
}
},
{
"method_name": "available_movies",
"method_description": "def available_movies(self, start_time, end_time):\n \"\"\"\n Get a list of available movies within the specified time range\n :param start_time: str, start time in HH:MM format\n :param end_time: str, end time in HH:MM format\n :return: list of str, names of available movies\n >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n >>> system.available_movies('12:00', '22:00')\n ['Batman']\n \"\"\"",
"test_class": "MovieBookingSystemTestAvailableMovies",
"test_code": "class MovieBookingSystemTestAvailableMovies(unittest.TestCase):\n def setUp(self):\n self.system = MovieBookingSystem()\n self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n self.system.add_movie('Spiderman', 59.9, '20:00', '22:30', 4)\n\n def test_available_movies_1(self):\n result = self.system.available_movies('16:00', '23:00')\n self.assertEqual(result, ['Batman', 'Spiderman'])\n\n def test_available_movies_2(self):\n result = self.system.available_movies('23:00', '23:59')\n self.assertEqual(result, [])\n\n def test_available_movies_3(self):\n result = self.system.available_movies('17:00', '20:00')\n self.assertEqual(result, ['Batman'])\n\n def test_available_movies_4(self):\n result = self.system.available_movies('10:00', '23:00')\n self.assertEqual(result, ['Batman', 'Spiderman'])\n\n def test_available_movies_5(self):\n result = self.system.available_movies('20:00', '23:00')\n self.assertEqual(result, ['Spiderman'])",
"solution_code": "def available_movies(self, start_time, end_time):\n start_time = datetime.strptime(start_time, '%H:%M')\n end_time = datetime.strptime(end_time, '%H:%M')\n\n available_movies = []\n for movie in self.movies:\n if start_time <= movie['start_time'] and movie['end_time'] <= end_time:\n available_movies.append(movie['name'])\n\n return available_movies",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"datetime"
],
"field_dependencies": [
"self.movies"
],
"method_dependencies": []
}
}
] | MovieBookingSystem | [
"MovieBookingSystemTestAddMovie",
"MovieBookingSystemTestBookTicket",
"MovieBookingSystemTestAvailableMovies",
"MovieBookingSystemTestMain"
] | class MovieBookingSystem:
def __init__(self):
"""
Initialize movies contains the information about movies
>>> system.movies
[{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25),
'seats': array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])}]
"""
self.movies = []
| [
"self.movies"
] |
ClassEval_60 | import sqlite3
class MovieTicketDB:
"""
This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name.
"""
def __init__(self, db_name):
"""
Initializes the MovieTicketDB object with the specified database name.
:param db_name: str, the name of the SQLite database.
"""
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
self.create_table()
def create_table(self):
"""
Creates a "tickets" table in the database if it does not exist already.Fields include ID of type int, movie name of type str, theater name of type str, seat number of type str, and customer name of type str
:return: None
"""
def insert_ticket(self, movie_name, theater_name, seat_number, customer_name):
"""
Inserts a new ticket into the "tickets" table.
:param movie_name: str, the name of the movie.
:param theater_name: str, the name of the theater.
:param seat_number: str, the seat number.
:param customer_name: str, the name of the customer.
:return: None
"""
def search_tickets_by_customer(self, customer_name):
"""
Searches for tickets in the "tickets" table by customer name.
:param customer_name: str, the name of the customer to search for.
:return: list of tuples, the rows from the "tickets" table that match the search criteria.
>>> ticket_db = MovieTicketDB("ticket_database.db")
>>> ticket_db.create_table()
>>> ticket_db.insert_ticket("Movie A", "Theater 1", "A1", "John Doe")
>>> result = ticket_db.search_tickets_by_customer("John Doe")
len(result) = 1
"""
def delete_ticket(self, ticket_id):
"""
Deletes a ticket from the "tickets" table by ticket ID.
:param ticket_id: int, the ID of the ticket to delete.
:return: None
""" | import unittest
import os
class MovieTicketDBTestInsertTicket(unittest.TestCase):
def setUp(self):
self.db_name = 'test_database.db'
self.db = MovieTicketDB(self.db_name)
def tearDown(self):
self.db.connection.close()
os.remove(self.db_name)
def test_insert_ticket_1(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')
tickets = self.db.search_tickets_by_customer('John Doe')
self.assertEqual(len(tickets), 1)
ticket = tickets[0]
self.assertEqual(ticket[1], 'Avengers: Endgame')
self.assertEqual(ticket[2], 'Cinema 1')
self.assertEqual(ticket[3], 'A1')
self.assertEqual(ticket[4], 'John Doe')
def test_insert_ticket_2(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'aaa')
tickets = self.db.search_tickets_by_customer('aaa')
self.assertEqual(len(tickets), 1)
ticket = tickets[0]
self.assertEqual(ticket[1], 'Avengers: Endgame')
self.assertEqual(ticket[2], 'Cinema 1')
self.assertEqual(ticket[3], 'A1')
self.assertEqual(ticket[4], 'aaa')
def test_insert_ticket_3(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'bbb')
tickets = self.db.search_tickets_by_customer('bbb')
self.assertEqual(len(tickets), 1)
ticket = tickets[0]
self.assertEqual(ticket[1], 'Avengers: Endgame')
self.assertEqual(ticket[2], 'Cinema 1')
self.assertEqual(ticket[3], 'A1')
self.assertEqual(ticket[4], 'bbb')
def test_insert_ticket_4(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ccc')
tickets = self.db.search_tickets_by_customer('ccc')
self.assertEqual(len(tickets), 1)
ticket = tickets[0]
self.assertEqual(ticket[1], 'Avengers: Endgame')
self.assertEqual(ticket[2], 'Cinema 1')
self.assertEqual(ticket[3], 'A1')
self.assertEqual(ticket[4], 'ccc')
def test_insert_ticket_5(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ddd')
tickets = self.db.search_tickets_by_customer('ddd')
self.assertEqual(len(tickets), 1)
ticket = tickets[0]
self.assertEqual(ticket[1], 'Avengers: Endgame')
self.assertEqual(ticket[2], 'Cinema 1')
self.assertEqual(ticket[3], 'A1')
self.assertEqual(ticket[4], 'ddd')
class MovieTicketDBTestSearchTicketsByCustomer(unittest.TestCase):
def setUp(self):
self.db_name = 'test_database.db'
self.db = MovieTicketDB(self.db_name)
def tearDown(self):
self.db.connection.close()
os.remove(self.db_name)
def test_search_tickets_by_customer_1(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')
tickets = self.db.search_tickets_by_customer('John Doe')
self.assertEqual(len(tickets), 1)
ticket = tickets[0]
self.assertEqual(ticket[1], 'Avengers: Endgame')
self.assertEqual(ticket[2], 'Cinema 1')
self.assertEqual(ticket[3], 'A1')
self.assertEqual(ticket[4], 'John Doe')
def test_search_tickets_by_customer_2(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'aaa')
tickets = self.db.search_tickets_by_customer('aaa')
self.assertEqual(len(tickets), 1)
ticket = tickets[0]
self.assertEqual(ticket[1], 'Avengers: Endgame')
self.assertEqual(ticket[2], 'Cinema 1')
self.assertEqual(ticket[3], 'A1')
self.assertEqual(ticket[4], 'aaa')
def test_search_tickets_by_customer_3(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'bbb')
tickets = self.db.search_tickets_by_customer('bbb')
self.assertEqual(len(tickets), 1)
ticket = tickets[0]
self.assertEqual(ticket[1], 'Avengers: Endgame')
self.assertEqual(ticket[2], 'Cinema 1')
self.assertEqual(ticket[3], 'A1')
self.assertEqual(ticket[4], 'bbb')
def test_search_tickets_by_customer_4(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ccc')
tickets = self.db.search_tickets_by_customer('ccc')
self.assertEqual(len(tickets), 1)
ticket = tickets[0]
self.assertEqual(ticket[1], 'Avengers: Endgame')
self.assertEqual(ticket[2], 'Cinema 1')
self.assertEqual(ticket[3], 'A1')
self.assertEqual(ticket[4], 'ccc')
def test_search_tickets_by_customer_5(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ddd')
tickets = self.db.search_tickets_by_customer('ddd')
self.assertEqual(len(tickets), 1)
ticket = tickets[0]
self.assertEqual(ticket[1], 'Avengers: Endgame')
self.assertEqual(ticket[2], 'Cinema 1')
self.assertEqual(ticket[3], 'A1')
self.assertEqual(ticket[4], 'ddd')
class MovieTicketDBTestDeleteTicket(unittest.TestCase):
def setUp(self):
self.db_name = 'test_database.db'
self.db = MovieTicketDB(self.db_name)
def tearDown(self):
self.db.connection.close()
os.remove(self.db_name)
def test_delete_ticket_1(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')
tickets = self.db.search_tickets_by_customer('John Doe')
self.assertEqual(len(tickets), 1)
ticket_id = tickets[0][0]
self.db.delete_ticket(ticket_id)
tickets = self.db.search_tickets_by_customer('John Doe')
self.assertEqual(len(tickets), 0)
def test_delete_ticket_2(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'aaa')
tickets = self.db.search_tickets_by_customer('aaa')
self.assertEqual(len(tickets), 1)
ticket_id = tickets[0][0]
self.db.delete_ticket(ticket_id)
tickets = self.db.search_tickets_by_customer('aaa')
self.assertEqual(len(tickets), 0)
def test_delete_ticket_3(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'bbb')
tickets = self.db.search_tickets_by_customer('bbb')
self.assertEqual(len(tickets), 1)
ticket_id = tickets[0][0]
self.db.delete_ticket(ticket_id)
tickets = self.db.search_tickets_by_customer('bbb')
self.assertEqual(len(tickets), 0)
def test_delete_ticket_4(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ccc')
tickets = self.db.search_tickets_by_customer('ccc')
self.assertEqual(len(tickets), 1)
ticket_id = tickets[0][0]
self.db.delete_ticket(ticket_id)
tickets = self.db.search_tickets_by_customer('ccc')
self.assertEqual(len(tickets), 0)
def test_delete_ticket_5(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ddd')
tickets = self.db.search_tickets_by_customer('ddd')
self.assertEqual(len(tickets), 1)
ticket_id = tickets[0][0]
self.db.delete_ticket(ticket_id)
tickets = self.db.search_tickets_by_customer('ddd')
self.assertEqual(len(tickets), 0)
class MovieTicketDBTest(unittest.TestCase):
def setUp(self):
self.db_name = 'test_database.db'
self.db = MovieTicketDB(self.db_name)
def tearDown(self):
self.db.connection.close()
os.remove(self.db_name)
def test_MovieTicketDB(self):
self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')
tickets = self.db.search_tickets_by_customer('John Doe')
self.assertEqual(len(tickets), 1)
ticket = tickets[0]
self.assertEqual(ticket[1], 'Avengers: Endgame')
self.assertEqual(ticket[2], 'Cinema 1')
self.assertEqual(ticket[3], 'A1')
self.assertEqual(ticket[4], 'John Doe')
ticket_id = tickets[0][0]
self.db.delete_ticket(ticket_id)
tickets = self.db.search_tickets_by_customer('John Doe')
self.assertEqual(len(tickets), 0) | import sqlite3
class MovieTicketDB:
def __init__(self, db_name):
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
self.create_table()
def create_table(self):
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS tickets (
id INTEGER PRIMARY KEY,
movie_name TEXT,
theater_name TEXT,
seat_number TEXT,
customer_name TEXT
)
''')
self.connection.commit()
def insert_ticket(self, movie_name, theater_name, seat_number, customer_name):
self.cursor.execute('''
INSERT INTO tickets (movie_name, theater_name, seat_number, customer_name)
VALUES (?, ?, ?, ?)
''', (movie_name, theater_name, seat_number, customer_name))
self.connection.commit()
def search_tickets_by_customer(self, customer_name):
self.cursor.execute('''
SELECT * FROM tickets WHERE customer_name = ?
''', (customer_name,))
tickets = self.cursor.fetchall()
return tickets
def delete_ticket(self, ticket_id):
self.cursor.execute('''
DELETE FROM tickets WHERE id = ?
''', (ticket_id,))
self.connection.commit() | [
"import sqlite3"
] | """
This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name.
"""
| [
{
"method_name": "create_table",
"method_description": "def create_table(self):\n \"\"\"\n Creates a \"tickets\" table in the database if it does not exist already.Fields include ID of type int, movie name of type str, theater name of type str, seat number of type str, and customer name of type str\n :return: None\n \"\"\"",
"test_class": "MovieTicketDBTestInsertTicket",
"test_code": "class MovieTicketDBTestInsertTicket(unittest.TestCase):\n def setUp(self):\n self.db_name = 'test_database.db'\n self.db = MovieTicketDB(self.db_name)\n\n def tearDown(self):\n self.db.connection.close()\n os.remove(self.db_name)\n\n def test_insert_ticket_1(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'John Doe')\n\n def test_insert_ticket_2(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'aaa')\n tickets = self.db.search_tickets_by_customer('aaa')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'aaa')\n\n def test_insert_ticket_3(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'bbb')\n tickets = self.db.search_tickets_by_customer('bbb')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'bbb')\n\n def test_insert_ticket_4(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ccc')\n tickets = self.db.search_tickets_by_customer('ccc')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'ccc')\n\n def test_insert_ticket_5(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ddd')\n tickets = self.db.search_tickets_by_customer('ddd')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'ddd')",
"solution_code": "def create_table(self):\n self.cursor.execute('''\n CREATE TABLE IF NOT EXISTS tickets (\n id INTEGER PRIMARY KEY,\n movie_name TEXT,\n theater_name TEXT,\n seat_number TEXT,\n customer_name TEXT\n )\n ''')\n self.connection.commit()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.connection",
"self.cursor"
],
"method_dependencies": []
}
},
{
"method_name": "insert_ticket",
"method_description": "def insert_ticket(self, movie_name, theater_name, seat_number, customer_name):\n \"\"\"\n Inserts a new ticket into the \"tickets\" table.\n :param movie_name: str, the name of the movie.\n :param theater_name: str, the name of the theater.\n :param seat_number: str, the seat number.\n :param customer_name: str, the name of the customer.\n :return: None\n \"\"\"",
"test_class": "MovieTicketDBTestSearchTicketsByCustomer",
"test_code": "class MovieTicketDBTestSearchTicketsByCustomer(unittest.TestCase):\n def setUp(self):\n self.db_name = 'test_database.db'\n self.db = MovieTicketDB(self.db_name)\n\n def tearDown(self):\n self.db.connection.close()\n os.remove(self.db_name)\n\n def test_search_tickets_by_customer_1(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'John Doe')\n\n def test_search_tickets_by_customer_2(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'aaa')\n tickets = self.db.search_tickets_by_customer('aaa')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'aaa')\n\n def test_search_tickets_by_customer_3(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'bbb')\n tickets = self.db.search_tickets_by_customer('bbb')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'bbb')\n\n def test_search_tickets_by_customer_4(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ccc')\n tickets = self.db.search_tickets_by_customer('ccc')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'ccc')\n\n def test_search_tickets_by_customer_5(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ddd')\n tickets = self.db.search_tickets_by_customer('ddd')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'ddd')",
"solution_code": "def insert_ticket(self, movie_name, theater_name, seat_number, customer_name):\n self.cursor.execute('''\n INSERT INTO tickets (movie_name, theater_name, seat_number, customer_name)\n VALUES (?, ?, ?, ?)\n ''', (movie_name, theater_name, seat_number, customer_name))\n self.connection.commit()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.connection",
"self.cursor"
],
"method_dependencies": []
}
},
{
"method_name": "search_tickets_by_customer",
"method_description": "def search_tickets_by_customer(self, customer_name):\n \"\"\"\n Searches for tickets in the \"tickets\" table by customer name.\n :param customer_name: str, the name of the customer to search for.\n :return: list of tuples, the rows from the \"tickets\" table that match the search criteria.\n >>> ticket_db = MovieTicketDB(\"ticket_database.db\")\n >>> ticket_db.create_table()\n >>> ticket_db.insert_ticket(\"Movie A\", \"Theater 1\", \"A1\", \"John Doe\")\n >>> result = ticket_db.search_tickets_by_customer(\"John Doe\")\n len(result) = 1\n \"\"\"",
"test_class": "MovieTicketDBTestDeleteTicket",
"test_code": "class MovieTicketDBTestDeleteTicket(unittest.TestCase):\n def setUp(self):\n self.db_name = 'test_database.db'\n self.db = MovieTicketDB(self.db_name)\n\n def tearDown(self):\n self.db.connection.close()\n os.remove(self.db_name)\n\n def test_delete_ticket_1(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 0)\n\n def test_delete_ticket_2(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'aaa')\n tickets = self.db.search_tickets_by_customer('aaa')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('aaa')\n self.assertEqual(len(tickets), 0)\n\n def test_delete_ticket_3(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'bbb')\n tickets = self.db.search_tickets_by_customer('bbb')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('bbb')\n self.assertEqual(len(tickets), 0)\n\n def test_delete_ticket_4(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ccc')\n tickets = self.db.search_tickets_by_customer('ccc')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('ccc')\n self.assertEqual(len(tickets), 0)\n\n def test_delete_ticket_5(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ddd')\n tickets = self.db.search_tickets_by_customer('ddd')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('ddd')\n self.assertEqual(len(tickets), 0)",
"solution_code": "def search_tickets_by_customer(self, customer_name):\n self.cursor.execute('''\n SELECT * FROM tickets WHERE customer_name = ?\n ''', (customer_name,))\n tickets = self.cursor.fetchall()\n return tickets",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.cursor"
],
"method_dependencies": []
}
},
{
"method_name": "delete_ticket",
"method_description": "def delete_ticket(self, ticket_id):\n \"\"\"\n Deletes a ticket from the \"tickets\" table by ticket ID.\n :param ticket_id: int, the ID of the ticket to delete.\n :return: None\n \"\"\"",
"test_class": "MovieTicketDBTest",
"test_code": "class MovieTicketDBTest(unittest.TestCase):\n def setUp(self):\n self.db_name = 'test_database.db'\n self.db = MovieTicketDB(self.db_name)\n\n def tearDown(self):\n self.db.connection.close()\n os.remove(self.db_name)\n\n def test_MovieTicketDB(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'John Doe')\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 0)",
"solution_code": "def delete_ticket(self, ticket_id):\n self.cursor.execute('''\n DELETE FROM tickets WHERE id = ?\n ''', (ticket_id,))\n self.connection.commit()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.connection",
"self.cursor"
],
"method_dependencies": []
}
}
] | MovieTicketDB | [
"MovieTicketDBTestInsertTicket",
"MovieTicketDBTestSearchTicketsByCustomer",
"MovieTicketDBTestDeleteTicket",
"MovieTicketDBTest"
] | class MovieTicketDB:
def __init__(self, db_name):
"""
Initializes the MovieTicketDB object with the specified database name.
:param db_name: str, the name of the SQLite database.
"""
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
self.create_table()
| [
"self.connection",
"self.cursor"
] |
ClassEval_61 | class MusicPlayer:
"""
This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song.
"""
def __init__(self):
"""
Initializes the music player with an empty playlist, no current song, and a default volume of 50.
"""
self.playlist = []
self.current_song = None
self.volume = 50
def add_song(self, song):
"""
Adds a song to the playlist.
:param song: The song to add to the playlist, str.
>>> musicPlayer = MusicPlayer()
>>> musicPlayer.add_song("song1")
>>> musicPlayer.playlist
['song1']
"""
def remove_song(self, song):
"""
Removes a song from the playlist.
:param song: The song to remove from the playlist, str.
>>> musicPlayer = MusicPlayer()
>>> musicPlayer.playlist = ["song1", "song2"]
>>> musicPlayer.remove_song("song1")
>>> musicPlayer.playlist
['song2']
"""
def play(self):
"""
Plays the current song in the playlist.
:return: The current song in the playlist, or False if there is no current song.
>>> musicPlayer = MusicPlayer()
>>> musicPlayer.playlist = ["song1", "song2"]
>>> musicPlayer.current_song = "song1"
>>> musicPlayer.play()
'song1'
"""
def stop(self):
"""
Stops the current song in the playlist.
:return: True if the current song was stopped, False if there was no current song.
>>> musicPlayer = MusicPlayer()
>>> musicPlayer.playlist = ["song1", "song2"]
>>> musicPlayer.current_song = "song1"
>>> musicPlayer.stop()
True
"""
def switch_song(self):
"""
Switches to the next song in the playlist.
:return: True if the next song was switched to, False if there was no next song.
>>> musicPlayer = MusicPlayer()
>>> musicPlayer.playlist = ["song1", "song2"]
>>> musicPlayer.current_song = "song1"
>>> musicPlayer.switch_song()
True
"""
def previous_song(self):
"""
Switches to the previous song in the playlist.
:return: True if the previous song was switched to, False if there was no previous song.
>>> musicPlayer = MusicPlayer()
>>> musicPlayer.playlist = ["song1", "song2"]
>>> musicPlayer.current_song = "song2"
>>> musicPlayer.previous_song()
True
"""
def set_volume(self, volume):
"""
Sets the volume of the music player,ifthe volume is between 0 and 100 is valid.
:param volume: The volume to set the music player to,int.
:return: True if the volume was set, False if the volume was invalid.
>>> musicPlayer = MusicPlayer()
>>> musicPlayer.set_volume(50)
>>> musicPlayer.volume
50
"""
def shuffle(self):
"""
Shuffles the playlist.
:return: True if the playlist was shuffled, False if the playlist was empty.
>>> musicPlayer = MusicPlayer()
>>> musicPlayer.playlist = ["song1", "song2"]
>>> musicPlayer.shuffle()
True
""" | import unittest
class MusicPlayerTestAddSong(unittest.TestCase):
def test_add_song(self):
musicPlayer = MusicPlayer()
musicPlayer.add_song("song1")
self.assertEqual(musicPlayer.playlist, ["song1"])
def test_add_song2(self):
musicPlayer = MusicPlayer()
musicPlayer.add_song("song1")
musicPlayer.add_song("song2")
self.assertEqual(musicPlayer.playlist, ["song1", "song2"])
def test_add_song3(self):
musicPlayer = MusicPlayer()
musicPlayer.add_song("song1")
musicPlayer.add_song("song2")
musicPlayer.add_song("song3")
self.assertEqual(musicPlayer.playlist, ["song1", "song2", "song3"])
def test_add_song4(self):
musicPlayer = MusicPlayer()
musicPlayer.add_song("song1")
musicPlayer.add_song("song2")
musicPlayer.add_song("song3")
musicPlayer.add_song("song4")
self.assertEqual(musicPlayer.playlist, ["song1", "song2", "song3", "song4"])
def test_add_song5(self):
musicPlayer = MusicPlayer()
musicPlayer.add_song("song1")
musicPlayer.add_song("song2")
musicPlayer.add_song("song3")
musicPlayer.add_song("song4")
musicPlayer.add_song("song5")
self.assertEqual(musicPlayer.playlist, ["song1", "song2", "song3", "song4", "song5"])
class MusicPlayerTestRemoveSong(unittest.TestCase):
def test_remove_song(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.remove_song("song1")
self.assertEqual(musicPlayer.playlist, ["song2"])
def test_remove_song2(self):
musicPlayer = MusicPlayer()
musicPlayer.current_song = "song1"
musicPlayer.playlist = ["song1", "song2", "song3"]
musicPlayer.remove_song("song1")
self.assertEqual(musicPlayer.playlist, ["song2", "song3"])
def test_remove_song3(self):
musicPlayer = MusicPlayer()
musicPlayer.current_song = "song1"
musicPlayer.playlist = ["song1", "song2", "song3", "song4"]
musicPlayer.remove_song("song1")
self.assertEqual(musicPlayer.playlist, ["song2", "song3", "song4"])
def test_remove_song4(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2", "song3", "song4", "song5"]
musicPlayer.remove_song("song1")
self.assertEqual(musicPlayer.playlist, ["song2", "song3", "song4", "song5"])
def test_remove_song5(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2", "song3", "song4", "song5"]
musicPlayer.remove_song("song1")
musicPlayer.remove_song("song2")
self.assertEqual(musicPlayer.playlist, ["song3", "song4", "song5"])
def test_remove_song6(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = []
musicPlayer.remove_song("song1")
self.assertEqual(musicPlayer.playlist, [])
class MusicPlayerTestPlay(unittest.TestCase):
def test_play(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.current_song = "song1"
self.assertEqual(musicPlayer.play(), "song1")
def test_play_2(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = []
musicPlayer.current_song = "song2"
self.assertEqual(musicPlayer.play(), None)
def test_play_3(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
self.assertEqual(musicPlayer.play(),False)
def test_play_4(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.current_song = "song3"
self.assertEqual(musicPlayer.play(), "song1")
def test_play_5(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.current_song = "song1"
self.assertEqual(musicPlayer.play(), "song1")
class MusicPlayerTestStop(unittest.TestCase):
def test_stop(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.current_song = "song1"
self.assertEqual(musicPlayer.stop(), True)
def test_stop_2(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = []
musicPlayer.current_song = "song1"
self.assertEqual(musicPlayer.stop(), True)
def test_stop_3(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
self.assertEqual(musicPlayer.stop(), False)
def test_stop_4(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.current_song = "song1"
self.assertEqual(musicPlayer.stop(), True)
def test_stop_5(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.current_song = "song2"
self.assertEqual(musicPlayer.stop(), True)
class MusicPlayerTestSwitchSong(unittest.TestCase):
def test_switch_song(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.current_song = "song1"
self.assertEqual(musicPlayer.switch_song(), True)
def test_switch_song2(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.current_song = "song2"
self.assertEqual(musicPlayer.switch_song(), False)
def test_switch_song3(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2", "song3"]
musicPlayer.current_song = "song3"
self.assertEqual(musicPlayer.switch_song(), False)
def test_switch_song4(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
self.assertEqual(musicPlayer.switch_song(), False)
def test_switch_song5(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = []
self.assertEqual(musicPlayer.switch_song(), False)
class MusicPlayerTestPreviousSong(unittest.TestCase):
def test_previous_song(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2", "song3"]
musicPlayer.current_song = "song2"
self.assertEqual(musicPlayer.previous_song(), True)
def test_previous_song2(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2", "song3"]
musicPlayer.current_song = "song1"
self.assertEqual(musicPlayer.previous_song(), False)
def test_previous_song3(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2", "song3"]
musicPlayer.current_song = "song3"
self.assertEqual(musicPlayer.previous_song(), True)
def test_previous_song4(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2", "song3"]
self.assertEqual(musicPlayer.previous_song(), False)
def test_previous_song5(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = []
self.assertEqual(musicPlayer.previous_song(), False)
class MusicPlayerTestSetVolume(unittest.TestCase):
def test_set_volume(self):
musicPlayer = MusicPlayer()
self.assertEqual(musicPlayer.set_volume(50), None)
self.assertEqual(musicPlayer.volume, 50)
def test_set_volume2(self):
musicPlayer = MusicPlayer()
self.assertEqual(musicPlayer.set_volume(100), None)
self.assertEqual(musicPlayer.volume, 100)
def test_set_volume3(self):
musicPlayer = MusicPlayer()
self.assertEqual(musicPlayer.set_volume(0), None)
self.assertEqual(musicPlayer.volume, 0)
def test_set_volume4(self):
musicPlayer = MusicPlayer()
self.assertEqual(musicPlayer.set_volume(101), False)
self.assertEqual(musicPlayer.volume, 50)
def test_set_volume5(self):
musicPlayer = MusicPlayer()
self.assertEqual(musicPlayer.set_volume(-1), False)
self.assertEqual(musicPlayer.volume, 50)
class MusicPlayerTestShuffle(unittest.TestCase):
def test_shuffle(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
self.assertEqual(musicPlayer.shuffle(), True)
def test_shuffle_2(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = []
musicPlayer.current_song = "song1"
self.assertEqual(musicPlayer.shuffle(), False)
def test_shuffle_3(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.current_song = "song2"
self.assertEqual(musicPlayer.shuffle(), True)
def test_shuffle_4(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.current_song = "song3"
self.assertEqual(musicPlayer.shuffle(), True)
def test_shuffle_5(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.current_song = "song1"
self.assertEqual(musicPlayer.shuffle(), True)
class MusicPlayerTestMain(unittest.TestCase):
def test_main(self):
musicPlayer = MusicPlayer()
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.current_song = "song1"
self.assertEqual(musicPlayer.play(), "song1")
self.assertEqual(musicPlayer.stop(), True)
musicPlayer.playlist = ["song1", "song2"]
musicPlayer.current_song = "song1"
self.assertEqual(musicPlayer.switch_song(), True)
self.assertEqual(musicPlayer.previous_song(), True)
musicPlayer.set_volume(50)
self.assertEqual(musicPlayer.volume, 50) | class MusicPlayer:
def __init__(self):
self.playlist = []
self.current_song = None
self.volume = 50
def add_song(self, song):
self.playlist.append(song)
def remove_song(self, song):
if song in self.playlist:
self.playlist.remove(song)
if self.current_song == song:
self.stop()
def play(self):
if self.playlist and self.current_song:
return self.playlist[0]
elif len(self.playlist):
return False
def stop(self):
if self.current_song:
self.current_song = None
return True
else:
return False
def switch_song(self):
if self.current_song:
current_index = self.playlist.index(self.current_song)
if current_index < len(self.playlist) - 1:
self.current_song = self.playlist[current_index + 1]
return True
else:
return False
else:
return False
def previous_song(self):
if self.current_song:
current_index = self.playlist.index(self.current_song)
if current_index > 0:
self.current_song = self.playlist[current_index - 1]
return True
else:
return False
else:
return False
def set_volume(self, volume):
if 0 <= volume <= 100:
self.volume = volume
else:
return False
def shuffle(self):
if self.playlist:
import random
random.shuffle(self.playlist)
return True
else:
return False | [
"import random"
] | """
This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song.
"""
| [
{
"method_name": "add_song",
"method_description": "def add_song(self, song):\n \"\"\"\n Adds a song to the playlist.\n :param song: The song to add to the playlist, str.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.add_song(\"song1\")\n >>> musicPlayer.playlist\n ['song1']\n\n \"\"\"",
"test_class": "MusicPlayerTestAddSong",
"test_code": "class MusicPlayerTestAddSong(unittest.TestCase):\n def test_add_song(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song1\"])\n\n def test_add_song2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n musicPlayer.add_song(\"song2\")\n self.assertEqual(musicPlayer.playlist, [\"song1\", \"song2\"])\n\n def test_add_song3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n musicPlayer.add_song(\"song2\")\n musicPlayer.add_song(\"song3\")\n self.assertEqual(musicPlayer.playlist, [\"song1\", \"song2\", \"song3\"])\n\n def test_add_song4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n musicPlayer.add_song(\"song2\")\n musicPlayer.add_song(\"song3\")\n musicPlayer.add_song(\"song4\")\n self.assertEqual(musicPlayer.playlist, [\"song1\", \"song2\", \"song3\", \"song4\"])\n\n def test_add_song5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n musicPlayer.add_song(\"song2\")\n musicPlayer.add_song(\"song3\")\n musicPlayer.add_song(\"song4\")\n musicPlayer.add_song(\"song5\")\n self.assertEqual(musicPlayer.playlist, [\"song1\", \"song2\", \"song3\", \"song4\", \"song5\"])",
"solution_code": "def add_song(self, song):\n self.playlist.append(song)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.playlist"
],
"method_dependencies": [
"play"
]
}
},
{
"method_name": "remove_song",
"method_description": "def remove_song(self, song):\n \"\"\"\n Removes a song from the playlist.\n :param song: The song to remove from the playlist, str.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.remove_song(\"song1\")\n >>> musicPlayer.playlist\n ['song2']\n\n \"\"\"",
"test_class": "MusicPlayerTestRemoveSong",
"test_code": "class MusicPlayerTestRemoveSong(unittest.TestCase):\n def test_remove_song(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song2\"])\n\n def test_remove_song2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.current_song = \"song1\"\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song2\", \"song3\"])\n\n def test_remove_song3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.current_song = \"song1\"\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\", \"song4\"]\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song2\", \"song3\", \"song4\"])\n\n def test_remove_song4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\", \"song4\", \"song5\"]\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song2\", \"song3\", \"song4\", \"song5\"])\n\n def test_remove_song5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\", \"song4\", \"song5\"]\n musicPlayer.remove_song(\"song1\")\n musicPlayer.remove_song(\"song2\")\n self.assertEqual(musicPlayer.playlist, [\"song3\", \"song4\", \"song5\"])\n\n def test_remove_song6(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [])",
"solution_code": "def remove_song(self, song):\n if song in self.playlist:\n self.playlist.remove(song)\n if self.current_song == song:\n self.stop()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.current_song",
"self.playlist"
],
"method_dependencies": [
"play",
"stop"
]
}
},
{
"method_name": "play",
"method_description": "def play(self):\n \"\"\"\n Plays the current song in the playlist.\n :return: The current song in the playlist, or False if there is no current song.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.current_song = \"song1\"\n >>> musicPlayer.play()\n 'song1'\n\n \"\"\"",
"test_class": "MusicPlayerTestPlay",
"test_code": "class MusicPlayerTestPlay(unittest.TestCase):\n def test_play(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.play(), \"song1\")\n\n def test_play_2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.play(), None)\n\n def test_play_3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n self.assertEqual(musicPlayer.play(),False)\n\n def test_play_4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song3\"\n self.assertEqual(musicPlayer.play(), \"song1\")\n\n def test_play_5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.play(), \"song1\")",
"solution_code": "def play(self):\n if self.playlist and self.current_song:\n return self.playlist[0]\n elif len(self.playlist): \n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.current_song",
"self.playlist"
],
"method_dependencies": []
}
},
{
"method_name": "stop",
"method_description": "def stop(self):\n \"\"\"\n Stops the current song in the playlist.\n :return: True if the current song was stopped, False if there was no current song.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.current_song = \"song1\"\n >>> musicPlayer.stop()\n True\n\n \"\"\"",
"test_class": "MusicPlayerTestStop",
"test_code": "class MusicPlayerTestStop(unittest.TestCase):\n def test_stop(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.stop(), True)\n\n def test_stop_2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.stop(), True)\n\n def test_stop_3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n self.assertEqual(musicPlayer.stop(), False)\n\n def test_stop_4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.stop(), True)\n\n def test_stop_5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.stop(), True)",
"solution_code": "def stop(self):\n if self.current_song:\n self.current_song = None\n return True\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.current_song"
],
"method_dependencies": []
}
},
{
"method_name": "switch_song",
"method_description": "def switch_song(self):\n \"\"\"\n Switches to the next song in the playlist.\n :return: True if the next song was switched to, False if there was no next song.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.current_song = \"song1\"\n >>> musicPlayer.switch_song()\n True\n\n \"\"\"",
"test_class": "MusicPlayerTestSwitchSong",
"test_code": "class MusicPlayerTestSwitchSong(unittest.TestCase):\n def test_switch_song(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.switch_song(), True)\n\n def test_switch_song2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.switch_song(), False)\n\n def test_switch_song3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.current_song = \"song3\"\n self.assertEqual(musicPlayer.switch_song(), False)\n\n def test_switch_song4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n self.assertEqual(musicPlayer.switch_song(), False)\n\n def test_switch_song5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n self.assertEqual(musicPlayer.switch_song(), False)",
"solution_code": "def switch_song(self):\n if self.current_song:\n current_index = self.playlist.index(self.current_song)\n if current_index < len(self.playlist) - 1:\n self.current_song = self.playlist[current_index + 1]\n return True\n else:\n return False\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.current_song",
"self.playlist"
],
"method_dependencies": [
"play"
]
}
},
{
"method_name": "previous_song",
"method_description": "def previous_song(self):\n \"\"\"\n Switches to the previous song in the playlist.\n :return: True if the previous song was switched to, False if there was no previous song.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.current_song = \"song2\"\n >>> musicPlayer.previous_song()\n True\n\n \"\"\"",
"test_class": "MusicPlayerTestPreviousSong",
"test_code": "class MusicPlayerTestPreviousSong(unittest.TestCase):\n def test_previous_song(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.previous_song(), True)\n\n def test_previous_song2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.previous_song(), False)\n\n def test_previous_song3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.current_song = \"song3\"\n self.assertEqual(musicPlayer.previous_song(), True)\n\n def test_previous_song4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n self.assertEqual(musicPlayer.previous_song(), False)\n\n def test_previous_song5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n self.assertEqual(musicPlayer.previous_song(), False)",
"solution_code": "def previous_song(self):\n if self.current_song:\n current_index = self.playlist.index(self.current_song)\n if current_index > 0:\n self.current_song = self.playlist[current_index - 1]\n return True\n else:\n return False\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.current_song",
"self.playlist"
],
"method_dependencies": [
"play"
]
}
},
{
"method_name": "set_volume",
"method_description": "def set_volume(self, volume):\n \"\"\"\n Sets the volume of the music player,ifthe volume is between 0 and 100 is valid.\n :param volume: The volume to set the music player to,int.\n :return: True if the volume was set, False if the volume was invalid.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.set_volume(50)\n >>> musicPlayer.volume\n 50\n\n \"\"\"",
"test_class": "MusicPlayerTestSetVolume",
"test_code": "class MusicPlayerTestSetVolume(unittest.TestCase):\n def test_set_volume(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(50), None)\n self.assertEqual(musicPlayer.volume, 50)\n\n def test_set_volume2(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(100), None)\n self.assertEqual(musicPlayer.volume, 100)\n\n def test_set_volume3(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(0), None)\n self.assertEqual(musicPlayer.volume, 0)\n\n def test_set_volume4(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(101), False)\n self.assertEqual(musicPlayer.volume, 50)\n\n def test_set_volume5(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(-1), False)\n self.assertEqual(musicPlayer.volume, 50)",
"solution_code": "def set_volume(self, volume):\n if 0 <= volume <= 100:\n self.volume = volume\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.volume"
],
"method_dependencies": []
}
},
{
"method_name": "shuffle",
"method_description": "def shuffle(self):\n \"\"\"\n Shuffles the playlist.\n :return: True if the playlist was shuffled, False if the playlist was empty.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.shuffle()\n True\n\n \"\"\"",
"test_class": "MusicPlayerTestShuffle",
"test_code": "class MusicPlayerTestShuffle(unittest.TestCase):\n def test_shuffle(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n self.assertEqual(musicPlayer.shuffle(), True)\n\n def test_shuffle_2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.shuffle(), False)\n\n def test_shuffle_3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.shuffle(), True)\n\n def test_shuffle_4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song3\"\n self.assertEqual(musicPlayer.shuffle(), True)\n\n def test_shuffle_5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.shuffle(), True)",
"solution_code": "def shuffle(self):\n if self.playlist:\n import random\n random.shuffle(self.playlist)\n return True\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"random"
],
"field_dependencies": [
"self.playlist"
],
"method_dependencies": [
"play"
]
}
}
] | MusicPlayer | [
"MusicPlayerTestAddSong",
"MusicPlayerTestRemoveSong",
"MusicPlayerTestPlay",
"MusicPlayerTestStop",
"MusicPlayerTestSwitchSong",
"MusicPlayerTestPreviousSong",
"MusicPlayerTestSetVolume",
"MusicPlayerTestShuffle",
"MusicPlayerTestMain"
] | class MusicPlayer:
def __init__(self):
"""
Initializes the music player with an empty playlist, no current song, and a default volume of 50.
"""
self.playlist = []
self.current_song = None
self.volume = 50
| [
"self.current_song",
"self.playlist",
"self.volume"
] |
ClassEval_62 | class NLPDataProcessor:
"""
The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list.
"""
def construct_stop_word_list(self):
"""
Construct a stop word list including 'a', 'an', 'the'.
:return: a list of stop words
>>> NLPDataProcessor.construct_stop_word_list()
['a', 'an', 'the']
"""
def remove_stop_words(self, string_list, stop_word_list):
"""
Remove all the stop words from the list of strings.
:param string_list: a list of strings
:param stop_word_list: a list of stop words
:return: a list of words without stop words
>>> NLPDataProcessor.process(['This is a test.'])
[['This', 'is', 'test.']]
"""
def process(self, string_list):
"""
Construct a stop word list including 'a', 'an', 'the', and remove all the stop words from the list of strings.
:param string_list: a list of strings
:return: a list of words without stop words
>>> NLPDataProcessor.process(['This is a test.'])
[['This', 'is', 'test.']]
""" | import unittest
class NLPDataProcessorTestConstruct(unittest.TestCase):
def setUp(self):
self.processor = NLPDataProcessor()
def test_construct_stop_word_list(self):
stop_word_list = self.processor.construct_stop_word_list()
expected_stop_words = ['a', 'an', 'the']
self.assertEqual(stop_word_list, expected_stop_words)
class NLPDataProcessorTestRemove(unittest.TestCase):
def setUp(self):
self.processor = NLPDataProcessor()
def test_remove_stop_words(self):
string_list = ['This is a test', 'This is an apple', 'This is the dog']
stop_word_list = ['a', 'an', 'the']
words_list = self.processor.remove_stop_words(string_list, stop_word_list)
expected_words_list = [['This', 'is', 'test'], ['This', 'is', 'apple'], ['This', 'is', 'dog']]
self.assertEqual(words_list, expected_words_list)
def test_remove_stop_words_2(self):
string_list = ['a', 'an', 'the']
stop_word_list = ['a', 'an', 'the']
words_list = self.processor.remove_stop_words(string_list, stop_word_list)
self.assertEqual(words_list, [[], [], []])
def test_remove_stop_words_3(self):
string_list = []
stop_word_list = ['a', 'an', 'the']
words_list = self.processor.remove_stop_words(string_list, stop_word_list)
self.assertEqual(words_list, [])
def test_remove_stop_words_4(self):
string_list = ['This is a test', 'This is an apple', 'This is the dog']
stop_word_list = []
words_list = self.processor.remove_stop_words(string_list, stop_word_list)
expected_words_list = [['This', 'is', 'a', 'test'], ['This', 'is', 'an', 'apple'], ['This', 'is', 'the', 'dog']]
self.assertEqual(words_list, expected_words_list)
def test_remove_stop_words_5(self):
string_list = ['This is a test', 'This is an apple', 'This is the dog']
stop_word_list = ['a', 'an', 'the', 'This', 'is']
words_list = self.processor.remove_stop_words(string_list, stop_word_list)
expected_words_list = [['is', 'test'], ['is', 'apple'], ['is', 'dog']]
self.assertEqual(words_list, expected_words_list)
class NLPDataProcessorTestProcess(unittest.TestCase):
def setUp(self):
self.processor = NLPDataProcessor()
def test_process(self):
string_list = ['This is a test.', 'This is an apple.', 'This is the dog.']
words_list = self.processor.process(string_list)
expected_words_list = [['This', 'is', 'test.'], ['This', 'is', 'apple.'], ['This', 'is', 'dog.']]
self.assertEqual(words_list, expected_words_list)
def test_process_with_empty_string_list(self):
string_list = []
words_list = self.processor.process(string_list)
self.assertEqual(words_list, [])
def test_process_with_single_word_sentences(self):
string_list = ['Hello aa', 'World']
words_list = self.processor.process(string_list)
expected_words_list = [['Hello', 'aa'], ['World']]
self.assertEqual(words_list, expected_words_list)
def test_process_with_stop_words_only(self):
string_list = ['a', 'an', 'the']
words_list = self.processor.process(string_list)
self.assertEqual(words_list, [[], [], []])
def test_process_with_stop_words_only_2(self):
string_list = ['a', 'an', 'the','This']
words_list = self.processor.process(string_list)
self.assertEqual(words_list,[[], [], [], ['This']]) | class NLPDataProcessor:
def construct_stop_word_list(self):
stop_word_list = ['a', 'an', 'the']
return stop_word_list
def remove_stop_words(self, string_list, stop_word_list):
answer = []
for string in string_list:
string_split = string.split()
for word in string_split:
if word in stop_word_list:
string_split.remove(word)
answer.append(string_split)
return answer
def process(self, string_list):
stop_word_list = self.construct_stop_word_list()
words_list = self.remove_stop_words(string_list, stop_word_list)
return words_list | [] | """
The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list.
"""
| [
{
"method_name": "construct_stop_word_list",
"method_description": "def construct_stop_word_list(self):\n \"\"\"\n Construct a stop word list including 'a', 'an', 'the'.\n :return: a list of stop words\n >>> NLPDataProcessor.construct_stop_word_list()\n ['a', 'an', 'the']\n \"\"\"",
"test_class": "NLPDataProcessorTestConstruct",
"test_code": "class NLPDataProcessorTestConstruct(unittest.TestCase):\n def setUp(self):\n self.processor = NLPDataProcessor()\n\n def test_construct_stop_word_list(self):\n stop_word_list = self.processor.construct_stop_word_list()\n expected_stop_words = ['a', 'an', 'the']\n self.assertEqual(stop_word_list, expected_stop_words)",
"solution_code": "def construct_stop_word_list(self):\n stop_word_list = ['a', 'an', 'the']\n return stop_word_list",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "remove_stop_words",
"method_description": "def remove_stop_words(self, string_list, stop_word_list):\n \"\"\"\n Remove all the stop words from the list of strings.\n :param string_list: a list of strings\n :param stop_word_list: a list of stop words\n :return: a list of words without stop words\n >>> NLPDataProcessor.process(['This is a test.'])\n [['This', 'is', 'test.']]\n \"\"\"",
"test_class": "NLPDataProcessorTestRemove",
"test_code": "class NLPDataProcessorTestRemove(unittest.TestCase):\n def setUp(self):\n self.processor = NLPDataProcessor()\n\n def test_remove_stop_words(self):\n string_list = ['This is a test', 'This is an apple', 'This is the dog']\n stop_word_list = ['a', 'an', 'the']\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n expected_words_list = [['This', 'is', 'test'], ['This', 'is', 'apple'], ['This', 'is', 'dog']]\n self.assertEqual(words_list, expected_words_list)\n\n def test_remove_stop_words_2(self):\n string_list = ['a', 'an', 'the']\n stop_word_list = ['a', 'an', 'the']\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n self.assertEqual(words_list, [[], [], []])\n\n def test_remove_stop_words_3(self):\n string_list = []\n stop_word_list = ['a', 'an', 'the']\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n self.assertEqual(words_list, [])\n\n def test_remove_stop_words_4(self):\n string_list = ['This is a test', 'This is an apple', 'This is the dog']\n stop_word_list = []\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n expected_words_list = [['This', 'is', 'a', 'test'], ['This', 'is', 'an', 'apple'], ['This', 'is', 'the', 'dog']]\n self.assertEqual(words_list, expected_words_list)\n\n def test_remove_stop_words_5(self):\n string_list = ['This is a test', 'This is an apple', 'This is the dog']\n stop_word_list = ['a', 'an', 'the', 'This', 'is']\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n expected_words_list = [['is', 'test'], ['is', 'apple'], ['is', 'dog']]\n self.assertEqual(words_list, expected_words_list)",
"solution_code": "def remove_stop_words(self, string_list, stop_word_list):\n answer = []\n for string in string_list:\n string_split = string.split()\n for word in string_split:\n if word in stop_word_list:\n string_split.remove(word)\n answer.append(string_split)\n return answer",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "process",
"method_description": "def process(self, string_list):\n \"\"\"\n Construct a stop word list including 'a', 'an', 'the', and remove all the stop words from the list of strings.\n :param string_list: a list of strings\n :return: a list of words without stop words\n >>> NLPDataProcessor.process(['This is a test.'])\n [['This', 'is', 'test.']]\n \"\"\"",
"test_class": "NLPDataProcessorTestProcess",
"test_code": "class NLPDataProcessorTestProcess(unittest.TestCase):\n def setUp(self):\n self.processor = NLPDataProcessor()\n\n def test_process(self):\n string_list = ['This is a test.', 'This is an apple.', 'This is the dog.']\n words_list = self.processor.process(string_list)\n expected_words_list = [['This', 'is', 'test.'], ['This', 'is', 'apple.'], ['This', 'is', 'dog.']]\n self.assertEqual(words_list, expected_words_list)\n\n def test_process_with_empty_string_list(self):\n string_list = []\n words_list = self.processor.process(string_list)\n self.assertEqual(words_list, [])\n\n def test_process_with_single_word_sentences(self):\n string_list = ['Hello aa', 'World']\n words_list = self.processor.process(string_list)\n expected_words_list = [['Hello', 'aa'], ['World']]\n self.assertEqual(words_list, expected_words_list)\n\n def test_process_with_stop_words_only(self):\n string_list = ['a', 'an', 'the']\n words_list = self.processor.process(string_list)\n self.assertEqual(words_list, [[], [], []])\n\n def test_process_with_stop_words_only_2(self):\n string_list = ['a', 'an', 'the','This']\n words_list = self.processor.process(string_list)\n self.assertEqual(words_list,[[], [], [], ['This']])",
"solution_code": "def process(self, string_list):\n stop_word_list = self.construct_stop_word_list()\n words_list = self.remove_stop_words(string_list, stop_word_list)\n return words_list",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"construct_stop_word_list",
"remove_stop_words"
]
}
}
] | NLPDataProcessor | [
"NLPDataProcessorTestConstruct",
"NLPDataProcessorTestRemove",
"NLPDataProcessorTestProcess"
] | class NLPDataProcessor:
| [] |
ClassEval_63 | import re
from collections import Counter
class NLPDataProcessor2:
"""
The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words.
"""
def process_data(self, string_list):
"""
keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words.
:param string_list: a list of strings
:return: words_list: a list of words lists
>>> NLPDataProcessor.process_data(['This is a test.'])
[['this', 'is', 'a', 'test']]
"""
def calculate_word_frequency(self, words_list):
"""
Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order.
:param words_list: a list of words lists
:return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency
>>> NLPDataProcessor.calculate_word_frequency([['this', 'is', 'a', 'test'], ['this', 'is', 'another', 'test']])
{'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1}
"""
def process(self, string_list):
"""
keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order.
:param string_list: a list of strings
:return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency
>>> NLPDataProcessor.process(['This is a test.', 'This is another test.'])
{'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1}
""" | import unittest
class NLPDataProcessorTestProcessData(unittest.TestCase):
def setUp(self):
self.processor = NLPDataProcessor2()
def test_process_data(self):
string_list = ["Hello World!", "This is a test."]
expected_output = [['hello', 'world'], ['this', 'is', 'a', 'test']]
self.assertEqual(self.processor.process_data(string_list), expected_output)
def test_process_data2(self):
string_list = ["12345", "Special@Characters"]
expected_output = [[], ['specialcharacters']]
self.assertEqual(self.processor.process_data(string_list), expected_output)
def test_process_data3(self):
string_list = []
expected_output = []
self.assertEqual(self.processor.process_data(string_list), expected_output)
def test_process_data4(self):
string_list = ["Hello World!", "This is a test.", "12345", "Special@Characters"]
expected_output = [['hello', 'world'], ['this', 'is', 'a', 'test'], [], ['specialcharacters']]
self.assertEqual(self.processor.process_data(string_list), expected_output)
def test_process_data5(self):
string_list = ["Hello World!", "This is a test.", "12345", "Special@Characters", "Hello World!", "This is a test.", "12345", "Special@Characters"]
expected_output = [['hello', 'world'], ['this', 'is', 'a', 'test'], [], ['specialcharacters'], ['hello', 'world'], ['this', 'is', 'a', 'test'], [], ['specialcharacters']]
self.assertEqual(self.processor.process_data(string_list), expected_output)
class NLPDataProcessorTestCalculate(unittest.TestCase):
def setUp(self):
self.processor = NLPDataProcessor2()
def test_calculate_word_frequency(self):
words_list = [['hello', 'world'], ['this', 'is', 'a', 'test'], ['hello', 'world', 'this', 'is', 'another', 'test'],
['hello', 'hello', 'world']]
expected_output = {'hello': 4, 'world': 3, 'this': 2, 'is': 2, 'test': 2}
self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)
def test_calculate_word_frequency2(self):
words_list = [['hello', 'world'], ['this', 'is', 'a', 'test'], ['hello', 'world', 'this', 'is', 'another', 'test'],
['hello', 'hello', 'world'], ['world', 'world', 'world']]
expected_output = {'world': 6, 'hello': 4, 'this': 2, 'is': 2, 'test': 2}
self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)
def test_calculate_word_frequency3(self):
words_list = [['hello', 'world'], ['hello', 'hello', 'world'], ['world', 'world']]
expected_output = {'world': 4, 'hello': 3}
self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)
def test_calculate_word_frequency4(self):
words_list = [['hello', 'world'], ['this', 'is', 'a', '%%%'], ['hello', 'world', 'this', 'is', 'another', '%%%'],
['hello', 'hello', 'world'], ['%%%', 'world', 'a', '%%%'], ['%%%', 'hello', '%%%']]
expected_output = {'%%%': 6, 'hello': 5, 'world': 4, 'is': 2, 'this': 2}
self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)
def test_calculate_word_frequency5(self):
words_list = [['hello', 'world'], ['this', 'is', 'a', '%%%'], ['hello', 'world', 'this', 'is', 'another', '%%%'],
['hello', 'hello', 'world'], ['%%%', 'world', 'a', '%%%'], ['%%%', 'hello', '%%%'], ['hello', 'world'], ['this', 'is', 'a', '%%%'], ['hello', 'world', 'this', 'is', 'another', '%%%'],
['hello', 'hello', 'world'], ['%%%', 'world', 'a', '%%%'], ['%%%', 'hello', '%%%']]
expected_output = {'%%%': 12, 'hello': 10, 'world': 8, 'is': 4, 'this': 4}
self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)
class NLPDataProcessorTestProcess(unittest.TestCase):
def setUp(self):
self.processor = NLPDataProcessor2()
def test_process(self):
string_list = ["Hello World!", "This is a test.", "Hello World, this is a test."]
expected_output = {'hello': 2, 'world': 2, 'this': 2, 'is': 2, 'a': 2}
self.assertEqual(self.processor.process(string_list), expected_output)
def test_process2(self):
string_list = []
expected_output = []
self.assertEqual(self.processor.process_data(string_list), expected_output)
def test_calculate3(self):
words_list = []
expected_output = {}
self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)
def test_process4(self):
string_list = ["@#$%^&*", "Special_Characters", "12345"]
expected_output = [[], ['specialcharacters'], []]
self.assertEqual(self.processor.process_data(string_list), expected_output)
def test_process5(self):
string_list = ["Hello World! %%%", "This is a %%% test. %%% ", "Hello World, this is a test. %%%"]
expected_output = {'hello': 2, 'world': 2, 'this': 2, 'is': 2, 'a': 2}
self.assertEqual(self.processor.process(string_list), expected_output)
def test_process6(self):
string_list = ["12345", "67890", "98765"]
expected_output = [[], [], []]
self.assertEqual(self.processor.process_data(string_list), expected_output) | from collections import Counter
import re
class NLPDataProcessor2:
def process_data(self, string_list):
words_list = []
for string in string_list:
# Remove non-English letters and convert to lowercase
processed_string = re.sub(r'[^a-zA-Z\s]', '', string.lower())
# Split the string into words
words = processed_string.split()
words_list.append(words)
return words_list
def calculate_word_frequency(self, words_list):
word_frequency = Counter()
for words in words_list:
word_frequency.update(words)
sorted_word_frequency = dict(sorted(word_frequency.items(), key=lambda x: x[1], reverse=True))
top_5_word_frequency = dict(list(sorted_word_frequency.items())[:5])
return top_5_word_frequency
def process(self, string_list):
words_list = self.process_data(string_list)
word_frequency_dict = self.calculate_word_frequency(words_list)
return word_frequency_dict | [
"from collections import Counter",
"import re"
] | """
The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words.
"""
| [
{
"method_name": "process_data",
"method_description": "def process_data(self, string_list):\n \"\"\"\n keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words.\n :param string_list: a list of strings\n :return: words_list: a list of words lists\n >>> NLPDataProcessor.process_data(['This is a test.'])\n [['this', 'is', 'a', 'test']]\n \"\"\"",
"test_class": "NLPDataProcessorTestProcessData",
"test_code": "class NLPDataProcessorTestProcessData(unittest.TestCase):\n\n def setUp(self):\n self.processor = NLPDataProcessor2()\n\n def test_process_data(self):\n string_list = [\"Hello World!\", \"This is a test.\"]\n expected_output = [['hello', 'world'], ['this', 'is', 'a', 'test']]\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process_data2(self):\n string_list = [\"12345\", \"Special@Characters\"]\n expected_output = [[], ['specialcharacters']]\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process_data3(self):\n string_list = []\n expected_output = []\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process_data4(self):\n string_list = [\"Hello World!\", \"This is a test.\", \"12345\", \"Special@Characters\"]\n expected_output = [['hello', 'world'], ['this', 'is', 'a', 'test'], [], ['specialcharacters']]\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process_data5(self):\n string_list = [\"Hello World!\", \"This is a test.\", \"12345\", \"Special@Characters\", \"Hello World!\", \"This is a test.\", \"12345\", \"Special@Characters\"]\n expected_output = [['hello', 'world'], ['this', 'is', 'a', 'test'], [], ['specialcharacters'], ['hello', 'world'], ['this', 'is', 'a', 'test'], [], ['specialcharacters']]\n self.assertEqual(self.processor.process_data(string_list), expected_output)",
"solution_code": "def process_data(self, string_list):\n words_list = []\n for string in string_list:\n # Remove non-English letters and convert to lowercase\n processed_string = re.sub(r'[^a-zA-Z\\s]', '', string.lower())\n # Split the string into words\n words = processed_string.split()\n words_list.append(words)\n return words_list",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"re"
],
"field_dependencies": [],
"method_dependencies": [
"process"
]
}
},
{
"method_name": "calculate_word_frequency",
"method_description": "def calculate_word_frequency(self, words_list):\n \"\"\"\n Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order.\n :param words_list: a list of words lists\n :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency\n >>> NLPDataProcessor.calculate_word_frequency([['this', 'is', 'a', 'test'], ['this', 'is', 'another', 'test']])\n {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1}\n \"\"\"",
"test_class": "NLPDataProcessorTestCalculate",
"test_code": "class NLPDataProcessorTestCalculate(unittest.TestCase):\n\n def setUp(self):\n self.processor = NLPDataProcessor2()\n\n def test_calculate_word_frequency(self):\n words_list = [['hello', 'world'], ['this', 'is', 'a', 'test'], ['hello', 'world', 'this', 'is', 'another', 'test'],\n ['hello', 'hello', 'world']]\n expected_output = {'hello': 4, 'world': 3, 'this': 2, 'is': 2, 'test': 2}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_calculate_word_frequency2(self):\n words_list = [['hello', 'world'], ['this', 'is', 'a', 'test'], ['hello', 'world', 'this', 'is', 'another', 'test'],\n ['hello', 'hello', 'world'], ['world', 'world', 'world']]\n expected_output = {'world': 6, 'hello': 4, 'this': 2, 'is': 2, 'test': 2}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_calculate_word_frequency3(self):\n words_list = [['hello', 'world'], ['hello', 'hello', 'world'], ['world', 'world']]\n expected_output = {'world': 4, 'hello': 3}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_calculate_word_frequency4(self):\n words_list = [['hello', 'world'], ['this', 'is', 'a', '%%%'], ['hello', 'world', 'this', 'is', 'another', '%%%'],\n ['hello', 'hello', 'world'], ['%%%', 'world', 'a', '%%%'], ['%%%', 'hello', '%%%']]\n expected_output = {'%%%': 6, 'hello': 5, 'world': 4, 'is': 2, 'this': 2}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_calculate_word_frequency5(self):\n words_list = [['hello', 'world'], ['this', 'is', 'a', '%%%'], ['hello', 'world', 'this', 'is', 'another', '%%%'],\n ['hello', 'hello', 'world'], ['%%%', 'world', 'a', '%%%'], ['%%%', 'hello', '%%%'], ['hello', 'world'], ['this', 'is', 'a', '%%%'], ['hello', 'world', 'this', 'is', 'another', '%%%'],\n ['hello', 'hello', 'world'], ['%%%', 'world', 'a', '%%%'], ['%%%', 'hello', '%%%']]\n expected_output = {'%%%': 12, 'hello': 10, 'world': 8, 'is': 4, 'this': 4}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)",
"solution_code": "def calculate_word_frequency(self, words_list):\n word_frequency = Counter()\n for words in words_list:\n word_frequency.update(words)\n sorted_word_frequency = dict(sorted(word_frequency.items(), key=lambda x: x[1], reverse=True))\n top_5_word_frequency = dict(list(sorted_word_frequency.items())[:5])\n return top_5_word_frequency",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"Counter"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "process",
"method_description": "def process(self, string_list):\n \"\"\"\n keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order.\n :param string_list: a list of strings\n :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency\n >>> NLPDataProcessor.process(['This is a test.', 'This is another test.'])\n {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1}\n \"\"\"",
"test_class": "NLPDataProcessorTestProcess",
"test_code": "class NLPDataProcessorTestProcess(unittest.TestCase):\n\n def setUp(self):\n self.processor = NLPDataProcessor2()\n\n def test_process(self):\n string_list = [\"Hello World!\", \"This is a test.\", \"Hello World, this is a test.\"]\n expected_output = {'hello': 2, 'world': 2, 'this': 2, 'is': 2, 'a': 2}\n self.assertEqual(self.processor.process(string_list), expected_output)\n\n def test_process2(self):\n string_list = []\n expected_output = []\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_calculate3(self):\n words_list = []\n expected_output = {}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_process4(self):\n string_list = [\"@#$%^&*\", \"Special_Characters\", \"12345\"]\n expected_output = [[], ['specialcharacters'], []]\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process5(self):\n string_list = [\"Hello World! %%%\", \"This is a %%% test. %%% \", \"Hello World, this is a test. %%%\"]\n expected_output = {'hello': 2, 'world': 2, 'this': 2, 'is': 2, 'a': 2}\n self.assertEqual(self.processor.process(string_list), expected_output)\n\n def test_process6(self):\n string_list = [\"12345\", \"67890\", \"98765\"]\n expected_output = [[], [], []]\n self.assertEqual(self.processor.process_data(string_list), expected_output)",
"solution_code": "def process(self, string_list):\n words_list = self.process_data(string_list)\n word_frequency_dict = self.calculate_word_frequency(words_list)\n return word_frequency_dict",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"process_data",
"calculate_word_frequency"
]
}
}
] | NLPDataProcessor2 | [
"NLPDataProcessorTestProcessData",
"NLPDataProcessorTestCalculate",
"NLPDataProcessorTestProcess"
] | class NLPDataProcessor2:
| [] |
ClassEval_64 | class NumberConverter:
"""
The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily
"""
@staticmethod
def decimal_to_binary(decimal_num):
"""
Convert a number from decimal format to binary format.
:param decimal_num: int, decimal number
:return: str, the binary representation of an integer.
>>> NumberConverter.decimal_to_binary(42423)
'1010010110110111'
"""
@staticmethod
def binary_to_decimal(binary_num):
"""
Convert a number from binary format to decimal format.
:param binary_num: str, binary number
:return: int, the decimal representation of binary number str.
>>> NumberConverter.binary_to_decimal('1010010110110111')
42423
"""
@staticmethod
def decimal_to_octal(decimal_num):
"""
Convert a number from decimal format to octal format.
:param decimal_num: int, decimal number
:return: str, the octal representation of an integer.
>>> NumberConverter.decimal_to_octal(42423)
'122667'
"""
@staticmethod
def octal_to_decimal(octal_num):
"""
Convert a number from octal format to decimal format.
:param octal_num: str, octal num
:return: int, the decimal representation of octal number str.
>>> NumberConverter.octal_to_decimal('122667')
42423
"""
@staticmethod
def decimal_to_hex(decimal_num):
"""
Convert a number from decimal format to hex format.
:param decimal_num: int, decimal number
:return hex_num: str, the hex representation of an integer.
>>> NumberConverter.decimal_to_hex(42423)
'a5b7'
"""
@staticmethod
def hex_to_decimal(hex_num):
"""
Convert a number from hex format to decimal format.
:param hex_num: str, hex num
:return: int, the decimal representation of hex number str.
>>> NumberConverter.hex_to_decimal('a5b7')
42423
""" | import unittest
class NumberConverterTestDecimalToBinary(unittest.TestCase):
def test_decimal_to_binary(self):
self.assertEqual('1010010110110111', NumberConverter.decimal_to_binary(42423))
def test_decimal_to_binary_2(self):
self.assertEqual('101001100010111', NumberConverter.decimal_to_binary(21271))
def test_decimal_to_binary_3(self):
self.assertEqual('1010010111010111', NumberConverter.decimal_to_binary(42455))
def test_decimal_to_binary_4(self):
self.assertEqual('10100101110101011', NumberConverter.decimal_to_binary(84907))
def test_decimal_to_binary_5(self):
self.assertEqual('101001011101010111', NumberConverter.decimal_to_binary(169815))
class NumberConverterTestBinaryToDecimal(unittest.TestCase):
def test_binary_to_decimal(self):
self.assertEqual(42423, NumberConverter.binary_to_decimal('1010010110110111'))
def test_binary_to_decimal_2(self):
self.assertEqual(10615, NumberConverter.binary_to_decimal('10100101110111'))
def test_binary_to_decimal_3(self):
self.assertEqual(42455, NumberConverter.binary_to_decimal('1010010111010111'))
def test_binary_to_decimal_4(self):
self.assertEqual(169819, NumberConverter.binary_to_decimal('101001011101011011'))
def test_binary_to_decimal_5(self):
self.assertEqual(339639, NumberConverter.binary_to_decimal('1010010111010110111'))
class NumberConvertTestDecimalToOctal(unittest.TestCase):
def test_decimal_to_octal(self):
self.assertEqual('122667', NumberConverter.decimal_to_octal(42423))
def test_decimal_to_octal_2(self):
self.assertEqual('51427', NumberConverter.decimal_to_octal(21271))
def test_decimal_to_octal_3(self):
self.assertEqual('245653', NumberConverter.decimal_to_octal(84907))
def test_decimal_to_octal_4(self):
self.assertEqual('513527', NumberConverter.decimal_to_octal(169815))
def test_decimal_to_octal_5(self):
self.assertEqual('1227256', NumberConverter.decimal_to_octal(339630))
class NumberConvertTestOctalToDecimal(unittest.TestCase):
def test_octal_to_decimal(self):
self.assertEqual(42423, NumberConverter.octal_to_decimal('122667'))
def test_octal_to_decimal_2(self):
self.assertEqual(21271, NumberConverter.octal_to_decimal('51427'))
def test_octal_to_decimal_3(self):
self.assertEqual(84907, NumberConverter.octal_to_decimal('245653'))
def test_octal_to_decimal_4(self):
self.assertEqual(169815, NumberConverter.octal_to_decimal('513527'))
def test_octal_to_decimal_5(self):
self.assertEqual(339630, NumberConverter.octal_to_decimal('1227256'))
class NumberConvertTestDecimalToHex(unittest.TestCase):
def test_decimal_to_hex(self):
self.assertEqual('a5b7', NumberConverter.decimal_to_hex(42423))
def test_decimal_to_hex_2(self):
self.assertEqual('5317', NumberConverter.decimal_to_hex(21271))
def test_decimal_to_hex_3(self):
self.assertEqual('14bab', NumberConverter.decimal_to_hex(84907))
def test_decimal_to_hex_4(self):
self.assertEqual('29757', NumberConverter.decimal_to_hex(169815))
def test_decimal_to_hex_5(self):
self.assertEqual('52eb7', NumberConverter.decimal_to_hex(339639))
class NumberConvertTestHexToDecimal(unittest.TestCase):
def test_hex_to_decimal(self):
self.assertEqual(42423, NumberConverter.hex_to_decimal('a5b7'))
def test_hex_to_decimal_2(self):
self.assertEqual(21207, NumberConverter.hex_to_decimal('52d7'))
def test_hex_to_decimal_3(self):
self.assertEqual(84627, NumberConverter.hex_to_decimal('14a93'))
def test_hex_to_decimal_4(self):
self.assertEqual(170615, NumberConverter.hex_to_decimal('29a77'))
def test_hex_to_decimal_5(self):
self.assertEqual(342647, NumberConverter.hex_to_decimal('53a77'))
class NumberConvertTestMain(unittest.TestCase):
def test_main(self):
self.assertEqual('1010010110110111', NumberConverter.decimal_to_binary(42423))
self.assertEqual(42423, NumberConverter.binary_to_decimal('1010010110110111'))
self.assertEqual('122667', NumberConverter.decimal_to_octal(42423))
self.assertEqual('122667', NumberConverter.decimal_to_octal(42423))
self.assertEqual('a5b7', NumberConverter.decimal_to_hex(42423))
self.assertEqual(42423, NumberConverter.hex_to_decimal('a5b7')) | class NumberConverter:
@staticmethod
def decimal_to_binary(decimal_num):
binary_num = bin(decimal_num)[2:]
return binary_num
@staticmethod
def binary_to_decimal(binary_num):
decimal_num = int(binary_num, 2)
return decimal_num
@staticmethod
def decimal_to_octal(decimal_num):
octal_num = oct(decimal_num)[2:]
return octal_num
@staticmethod
def octal_to_decimal(octal_num):
decimal_num = int(octal_num, 8)
return decimal_num
@staticmethod
def decimal_to_hex(decimal_num):
hex_num = hex(decimal_num)[2:]
return hex_num
@staticmethod
def hex_to_decimal(hex_num):
decimal_num = int(hex_num, 16)
return decimal_num | [] | """
The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily
"""
| [
{
"method_name": "decimal_to_binary",
"method_description": "def decimal_to_binary(decimal_num):\n \"\"\"\n Convert a number from decimal format to binary format.\n :param decimal_num: int, decimal number\n :return: str, the binary representation of an integer.\n >>> NumberConverter.decimal_to_binary(42423)\n '1010010110110111'\n \"\"\"",
"test_class": "NumberConverterTestDecimalToBinary",
"test_code": "class NumberConverterTestDecimalToBinary(unittest.TestCase):\n def test_decimal_to_binary(self):\n self.assertEqual('1010010110110111', NumberConverter.decimal_to_binary(42423))\n\n def test_decimal_to_binary_2(self):\n self.assertEqual('101001100010111', NumberConverter.decimal_to_binary(21271))\n\n def test_decimal_to_binary_3(self):\n self.assertEqual('1010010111010111', NumberConverter.decimal_to_binary(42455))\n\n def test_decimal_to_binary_4(self):\n self.assertEqual('10100101110101011', NumberConverter.decimal_to_binary(84907))\n\n def test_decimal_to_binary_5(self):\n self.assertEqual('101001011101010111', NumberConverter.decimal_to_binary(169815))",
"solution_code": "def decimal_to_binary(decimal_num):\n binary_num = bin(decimal_num)[2:]\n return binary_num",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "binary_to_decimal",
"method_description": "@staticmethod\n def binary_to_decimal(binary_num):\n \"\"\"\n Convert a number from binary format to decimal format.\n :param binary_num: str, binary number\n :return: int, the decimal representation of binary number str.\n >>> NumberConverter.binary_to_decimal('1010010110110111')\n 42423\n \"\"\"",
"test_class": "NumberConverterTestBinaryToDecimal",
"test_code": "class NumberConverterTestBinaryToDecimal(unittest.TestCase):\n def test_binary_to_decimal(self):\n self.assertEqual(42423, NumberConverter.binary_to_decimal('1010010110110111'))\n\n def test_binary_to_decimal_2(self):\n self.assertEqual(10615, NumberConverter.binary_to_decimal('10100101110111'))\n\n def test_binary_to_decimal_3(self):\n self.assertEqual(42455, NumberConverter.binary_to_decimal('1010010111010111'))\n\n def test_binary_to_decimal_4(self):\n self.assertEqual(169819, NumberConverter.binary_to_decimal('101001011101011011'))\n\n def test_binary_to_decimal_5(self):\n self.assertEqual(339639, NumberConverter.binary_to_decimal('1010010111010110111'))",
"solution_code": "@staticmethod\n def binary_to_decimal(binary_num):\n decimal_num = int(binary_num, 2)\n return decimal_num",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "decimal_to_octal",
"method_description": "@staticmethod\n def decimal_to_octal(decimal_num):\n \"\"\"\n Convert a number from decimal format to octal format.\n :param decimal_num: int, decimal number\n :return: str, the octal representation of an integer.\n >>> NumberConverter.decimal_to_octal(42423)\n '122667'\n \"\"\"",
"test_class": "NumberConvertTestDecimalToOctal",
"test_code": "class NumberConvertTestDecimalToOctal(unittest.TestCase):\n def test_decimal_to_octal(self):\n self.assertEqual('122667', NumberConverter.decimal_to_octal(42423))\n\n def test_decimal_to_octal_2(self):\n self.assertEqual('51427', NumberConverter.decimal_to_octal(21271))\n\n def test_decimal_to_octal_3(self):\n self.assertEqual('245653', NumberConverter.decimal_to_octal(84907))\n\n def test_decimal_to_octal_4(self):\n self.assertEqual('513527', NumberConverter.decimal_to_octal(169815))\n\n def test_decimal_to_octal_5(self):\n self.assertEqual('1227256', NumberConverter.decimal_to_octal(339630))",
"solution_code": "@staticmethod\n def decimal_to_octal(decimal_num):\n octal_num = oct(decimal_num)[2:]\n return octal_num",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "octal_to_decimal",
"method_description": "@staticmethod\n def octal_to_decimal(octal_num):\n \"\"\"\n Convert a number from octal format to decimal format.\n :param octal_num: str, octal num\n :return: int, the decimal representation of octal number str.\n >>> NumberConverter.octal_to_decimal('122667')\n 42423\n \"\"\"",
"test_class": "NumberConvertTestOctalToDecimal",
"test_code": "class NumberConvertTestOctalToDecimal(unittest.TestCase):\n def test_octal_to_decimal(self):\n self.assertEqual(42423, NumberConverter.octal_to_decimal('122667'))\n\n def test_octal_to_decimal_2(self):\n self.assertEqual(21271, NumberConverter.octal_to_decimal('51427'))\n\n def test_octal_to_decimal_3(self):\n self.assertEqual(84907, NumberConverter.octal_to_decimal('245653'))\n\n def test_octal_to_decimal_4(self):\n self.assertEqual(169815, NumberConverter.octal_to_decimal('513527'))\n\n def test_octal_to_decimal_5(self):\n self.assertEqual(339630, NumberConverter.octal_to_decimal('1227256'))",
"solution_code": "@staticmethod\n def octal_to_decimal(octal_num):\n decimal_num = int(octal_num, 8)\n return decimal_num",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "decimal_to_hex",
"method_description": "@staticmethod\n def decimal_to_hex(decimal_num):\n \"\"\"\n Convert a number from decimal format to hex format.\n :param decimal_num: int, decimal number\n :return hex_num: str, the hex representation of an integer.\n >>> NumberConverter.decimal_to_hex(42423)\n 'a5b7'\n \"\"\"",
"test_class": "NumberConvertTestDecimalToHex",
"test_code": "class NumberConvertTestDecimalToHex(unittest.TestCase):\n def test_decimal_to_hex(self):\n self.assertEqual('a5b7', NumberConverter.decimal_to_hex(42423))\n\n def test_decimal_to_hex_2(self):\n self.assertEqual('5317', NumberConverter.decimal_to_hex(21271))\n\n def test_decimal_to_hex_3(self):\n self.assertEqual('14bab', NumberConverter.decimal_to_hex(84907))\n\n def test_decimal_to_hex_4(self):\n self.assertEqual('29757', NumberConverter.decimal_to_hex(169815))\n\n def test_decimal_to_hex_5(self):\n self.assertEqual('52eb7', NumberConverter.decimal_to_hex(339639))",
"solution_code": "@staticmethod\n def decimal_to_hex(decimal_num):\n hex_num = hex(decimal_num)[2:]\n return hex_num",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "hex_to_decimal",
"method_description": "@staticmethod\n def hex_to_decimal(hex_num):\n \"\"\"\n Convert a number from hex format to decimal format.\n :param hex_num: str, hex num\n :return: int, the decimal representation of hex number str.\n >>> NumberConverter.hex_to_decimal('a5b7')\n 42423\n \"\"\"",
"test_class": "NumberConvertTestHexToDecimal",
"test_code": "class NumberConvertTestHexToDecimal(unittest.TestCase):\n def test_hex_to_decimal(self):\n self.assertEqual(42423, NumberConverter.hex_to_decimal('a5b7'))\n\n def test_hex_to_decimal_2(self):\n self.assertEqual(21207, NumberConverter.hex_to_decimal('52d7'))\n\n def test_hex_to_decimal_3(self):\n self.assertEqual(84627, NumberConverter.hex_to_decimal('14a93'))\n\n def test_hex_to_decimal_4(self):\n self.assertEqual(170615, NumberConverter.hex_to_decimal('29a77'))\n\n def test_hex_to_decimal_5(self):\n self.assertEqual(342647, NumberConverter.hex_to_decimal('53a77'))",
"solution_code": "@staticmethod\n def hex_to_decimal(hex_num):\n decimal_num = int(hex_num, 16)\n return decimal_num",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | NumberConverter | [
"NumberConverterTestDecimalToBinary",
"NumberConverterTestBinaryToDecimal",
"NumberConvertTestDecimalToOctal",
"NumberConvertTestOctalToDecimal",
"NumberConvertTestDecimalToHex",
"NumberConvertTestHexToDecimal",
"NumberConvertTestMain"
] | class NumberConverter:
| [] |
ClassEval_65 | class NumberWordFormatter:
"""
This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units.
"""
def __init__(self):
"""
Initialize NumberWordFormatter object.
"""
self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"]
self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN",
"EIGHTEEN",
"NINETEEN"]
self.NUMBER_TEN = ["TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"]
self.NUMBER_MORE = ["", "THOUSAND", "MILLION", "BILLION"]
self.NUMBER_SUFFIX = ["k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"]
def format(self, x):
"""
Converts a number into words format
:param x: int or float, the number to be converted into words format
:return: str, the number in words format
>>> formatter = NumberWordFormatter()
>>> formatter.format(123456)
"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY"
"""
def format_string(self, x):
"""
Converts a string representation of a number into words format
:param x: str, the string representation of a number
:return: str, the number in words format
>>> formatter = NumberWordFormatter()
>>> formatter.format_string("123456")
"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY"
"""
def trans_two(self, s):
"""
Converts a two-digit number into words format
:param s: str, the two-digit number
:return: str, the number in words format
>>> formatter = NumberWordFormatter()
>>> formatter.trans_two("23")
"TWENTY THREE"
"""
def trans_three(self, s):
"""
Converts a three-digit number into words format
:param s: str, the three-digit number
:return: str, the number in words format
>>> formatter = NumberWordFormatter()
>>> formatter.trans_three("123")
"ONE HUNDRED AND TWENTY THREE"
"""
def parse_more(self, i):
"""
Parses the thousand/million/billion suffix based on the index
:param i: int, the index representing the magnitude (thousand, million, billion)
:return: str, the corresponding suffix for the magnitude
>>> formatter = NumberWordFormatter()
>>> formatter.parse_more(1)
"THOUSAND"
""" | import unittest
class NumberWordFormatterTestFormat(unittest.TestCase):
def test_format_1(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.format(123456),
"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY")
def test_format_2(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.format(1000), "ONE THOUSAND ONLY")
def test_format_3(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.format(1000000), "ONE MILLION ONLY")
def test_format_4(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.format(1.23), "ONE AND CENTS TWENTY THREE ONLY")
def test_format_5(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.format(0), "ZERO ONLY")
def test_format_6(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.format(None), "")
class NumberWordFormatterTestFormatString(unittest.TestCase):
def test_format_string_1(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.format_string('123456'),
"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY")
def test_format_string_2(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.format_string('1000'), "ONE THOUSAND ONLY")
def test_format_string_3(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.format_string('1000000'), "ONE MILLION ONLY")
def test_format_string_4(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.format_string('1.23'), "ONE AND CENTS TWENTY THREE ONLY")
def test_format_string_5(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.format_string('0'), "ZERO ONLY")
def test_format_string_6(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.format_string('10'), "TEN ONLY")
class NumberWordFormatterTestTransTwo(unittest.TestCase):
def test_trans_two_1(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.trans_two("23"), "TWENTY THREE")
def test_trans_two_2(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.trans_two("10"), "TEN")
def test_trans_two_3(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.trans_two("05"), "FIVE")
def test_trans_two_4(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.trans_two("00"), "")
def test_trans_two_5(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.trans_two("01"), "ONE")
def test_trans_two_6(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.trans_two("80"), "EIGHTY")
class NumberWordFormatterTestTransThree(unittest.TestCase):
def test_trans_three_1(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.trans_three("123"), "ONE HUNDRED AND TWENTY THREE")
def test_trans_three_2(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.trans_three("900"), "NINE HUNDRED")
def test_trans_three_3(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.trans_three("007"), "SEVEN")
def test_trans_three_4(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.trans_three("001"), "ONE")
def test_trans_three_5(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.trans_three("006"), "SIX")
class NumberWordFormatterTestParseMore(unittest.TestCase):
def test_parse_more_1(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.parse_more(0), "")
def test_parse_more_2(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.parse_more(1), "THOUSAND")
def test_parse_more_3(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.parse_more(2), "MILLION")
def test_parse_more_4(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.parse_more(3), "BILLION")
class NumberWordFormatterTest(unittest.TestCase):
def test_NumberWordFormatter(self):
formatter = NumberWordFormatter()
self.assertEqual(formatter.format(123456),
"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY")
formatter = NumberWordFormatter()
self.assertEqual(formatter.format_string('123456'),
"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY")
formatter = NumberWordFormatter()
self.assertEqual(formatter.trans_two("23"), "TWENTY THREE")
formatter = NumberWordFormatter()
self.assertEqual(formatter.trans_three("123"), "ONE HUNDRED AND TWENTY THREE")
formatter = NumberWordFormatter()
self.assertEqual(formatter.parse_more(1), "THOUSAND") | class NumberWordFormatter:
def __init__(self):
self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"]
self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN",
"EIGHTEEN",
"NINETEEN"]
self.NUMBER_TEN = ["TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"]
self.NUMBER_MORE = ["", "THOUSAND", "MILLION", "BILLION"]
self.NUMBER_SUFFIX = ["k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"]
def format(self, x):
if x is not None:
return self.format_string(str(x))
else:
return ""
def format_string(self, x):
lstr, rstr = (x.split('.') + [''])[:2]
lstrrev = lstr[::-1]
a = [''] * 5
if len(lstrrev) % 3 == 1:
lstrrev += "00"
elif len(lstrrev) % 3 == 2:
lstrrev += "0"
lm = ""
for i in range(len(lstrrev) // 3):
a[i] = lstrrev[3 * i:3 * i + 3][::-1]
if a[i] != "000":
lm = self.trans_three(a[i]) + " " + self.parse_more(i) + " " + lm
else:
lm += self.trans_three(a[i])
xs = f"AND CENTS {self.trans_two(rstr)} " if rstr else ""
if not lm.strip():
return "ZERO ONLY"
else:
return f"{lm.strip()} {xs}ONLY"
def trans_two(self, s):
s = s.zfill(2)
if s[0] == "0":
return self.NUMBER[int(s[-1])]
elif s[0] == "1":
return self.NUMBER_TEEN[int(s) - 10]
elif s[1] == "0":
return self.NUMBER_TEN[int(s[0]) - 1]
else:
return self.NUMBER_TEN[int(s[0]) - 1] + " " + self.NUMBER[int(s[-1])]
def trans_three(self, s):
if s[0] == "0":
return self.trans_two(s[1:])
elif s[1:] == "00":
return f"{self.NUMBER[int(s[0])]} HUNDRED"
else:
return f"{self.NUMBER[int(s[0])]} HUNDRED AND {self.trans_two(s[1:])}"
def parse_more(self, i):
return self.NUMBER_MORE[i] | [] | """
This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units.
"""
| [
{
"method_name": "format",
"method_description": "def format(self, x):\n \"\"\"\n Converts a number into words format\n :param x: int or float, the number to be converted into words format\n :return: str, the number in words format\n >>> formatter = NumberWordFormatter()\n >>> formatter.format(123456)\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\"\n \"\"\"",
"test_class": "NumberWordFormatterTestFormat",
"test_code": "class NumberWordFormatterTestFormat(unittest.TestCase):\n def test_format_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(123456),\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\")\n\n def test_format_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(1000), \"ONE THOUSAND ONLY\")\n\n def test_format_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(1000000), \"ONE MILLION ONLY\")\n\n def test_format_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(1.23), \"ONE AND CENTS TWENTY THREE ONLY\")\n\n def test_format_5(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(0), \"ZERO ONLY\")\n\n def test_format_6(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(None), \"\")",
"solution_code": "def format(self, x):\n if x is not None:\n return self.format_string(str(x))\n else:\n return \"\"",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"format_string"
]
}
},
{
"method_name": "format_string",
"method_description": "def format_string(self, x):\n \"\"\"\n Converts a string representation of a number into words format\n :param x: str, the string representation of a number\n :return: str, the number in words format\n >>> formatter = NumberWordFormatter()\n >>> formatter.format_string(\"123456\")\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\"\n \"\"\"",
"test_class": "NumberWordFormatterTestFormatString",
"test_code": "class NumberWordFormatterTestFormatString(unittest.TestCase):\n def test_format_string_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('123456'),\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\")\n\n def test_format_string_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('1000'), \"ONE THOUSAND ONLY\")\n\n def test_format_string_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('1000000'), \"ONE MILLION ONLY\")\n\n def test_format_string_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('1.23'), \"ONE AND CENTS TWENTY THREE ONLY\")\n\n def test_format_string_5(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('0'), \"ZERO ONLY\")\n\n def test_format_string_6(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('10'), \"TEN ONLY\")",
"solution_code": "def format_string(self, x):\n lstr, rstr = (x.split('.') + [''])[:2]\n lstrrev = lstr[::-1]\n a = [''] * 5\n\n if len(lstrrev) % 3 == 1:\n lstrrev += \"00\"\n elif len(lstrrev) % 3 == 2:\n lstrrev += \"0\"\n\n lm = \"\"\n for i in range(len(lstrrev) // 3):\n a[i] = lstrrev[3 * i:3 * i + 3][::-1]\n if a[i] != \"000\":\n lm = self.trans_three(a[i]) + \" \" + self.parse_more(i) + \" \" + lm\n else:\n lm += self.trans_three(a[i])\n\n xs = f\"AND CENTS {self.trans_two(rstr)} \" if rstr else \"\"\n if not lm.strip():\n return \"ZERO ONLY\"\n else:\n return f\"{lm.strip()} {xs}ONLY\"",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"trans_two",
"trans_three",
"parse_more"
]
}
},
{
"method_name": "trans_two",
"method_description": "def trans_two(self, s):\n \"\"\"\n Converts a two-digit number into words format\n :param s: str, the two-digit number\n :return: str, the number in words format\n >>> formatter = NumberWordFormatter()\n >>> formatter.trans_two(\"23\")\n \"TWENTY THREE\"\n \"\"\"",
"test_class": "NumberWordFormatterTestTransTwo",
"test_code": "class NumberWordFormatterTestTransTwo(unittest.TestCase):\n def test_trans_two_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"23\"), \"TWENTY THREE\")\n\n def test_trans_two_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"10\"), \"TEN\")\n\n def test_trans_two_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"05\"), \"FIVE\")\n\n def test_trans_two_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"00\"), \"\")\n\n def test_trans_two_5(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"01\"), \"ONE\")\n\n def test_trans_two_6(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"80\"), \"EIGHTY\")",
"solution_code": "def trans_two(self, s):\n s = s.zfill(2)\n if s[0] == \"0\":\n return self.NUMBER[int(s[-1])]\n elif s[0] == \"1\":\n return self.NUMBER_TEEN[int(s) - 10]\n elif s[1] == \"0\":\n return self.NUMBER_TEN[int(s[0]) - 1]\n else:\n return self.NUMBER_TEN[int(s[0]) - 1] + \" \" + self.NUMBER[int(s[-1])]",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.NUMBER",
"self.NUMBER_TEEN",
"self.NUMBER_TEN"
],
"method_dependencies": []
}
},
{
"method_name": "trans_three",
"method_description": "def trans_three(self, s):\n \"\"\"\n Converts a three-digit number into words format\n :param s: str, the three-digit number\n :return: str, the number in words format\n >>> formatter = NumberWordFormatter()\n >>> formatter.trans_three(\"123\")\n \"ONE HUNDRED AND TWENTY THREE\"\n \"\"\"",
"test_class": "NumberWordFormatterTestTransThree",
"test_code": "class NumberWordFormatterTestTransThree(unittest.TestCase):\n def test_trans_three_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"123\"), \"ONE HUNDRED AND TWENTY THREE\")\n\n def test_trans_three_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"900\"), \"NINE HUNDRED\")\n\n def test_trans_three_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"007\"), \"SEVEN\")\n\n def test_trans_three_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"001\"), \"ONE\")\n\n def test_trans_three_5(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"006\"), \"SIX\")",
"solution_code": "def trans_three(self, s):\n if s[0] == \"0\":\n return self.trans_two(s[1:])\n elif s[1:] == \"00\":\n return f\"{self.NUMBER[int(s[0])]} HUNDRED\"\n else:\n return f\"{self.NUMBER[int(s[0])]} HUNDRED AND {self.trans_two(s[1:])}\"",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.NUMBER"
],
"method_dependencies": [
"trans_two"
]
}
},
{
"method_name": "parse_more",
"method_description": "def parse_more(self, i):\n \"\"\"\n Parses the thousand/million/billion suffix based on the index\n :param i: int, the index representing the magnitude (thousand, million, billion)\n :return: str, the corresponding suffix for the magnitude\n >>> formatter = NumberWordFormatter()\n >>> formatter.parse_more(1)\n \"THOUSAND\"\n \"\"\"",
"test_class": "NumberWordFormatterTestParseMore",
"test_code": "class NumberWordFormatterTestParseMore(unittest.TestCase):\n def test_parse_more_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.parse_more(0), \"\")\n\n def test_parse_more_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.parse_more(1), \"THOUSAND\")\n\n def test_parse_more_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.parse_more(2), \"MILLION\")\n\n def test_parse_more_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.parse_more(3), \"BILLION\")",
"solution_code": "def parse_more(self, i):\n return self.NUMBER_MORE[i]",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.NUMBER",
"self.NUMBER_MORE"
],
"method_dependencies": []
}
}
] | NumberWordFormatter | [
"NumberWordFormatterTestFormat",
"NumberWordFormatterTestFormatString",
"NumberWordFormatterTestTransTwo",
"NumberWordFormatterTestTransThree",
"NumberWordFormatterTestParseMore",
"NumberWordFormatterTest"
] | class NumberWordFormatter:
def __init__(self):
"""
Initialize NumberWordFormatter object.
"""
self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"]
self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN",
"EIGHTEEN",
"NINETEEN"]
self.NUMBER_TEN = ["TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"]
self.NUMBER_MORE = ["", "THOUSAND", "MILLION", "BILLION"]
self.NUMBER_SUFFIX = ["k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"]
| [
"self.NUMBER",
"self.NUMBER_MORE",
"self.NUMBER_SUFFIX",
"self.NUMBER_TEEN",
"self.NUMBER_TEN"
] |
ClassEval_66 | class NumericEntityUnescaper:
"""
This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string.
"""
def __init__(self):
pass
def replace(self, string):
"""
Replaces numeric character references (HTML entities) in the input string with their corresponding Unicode characters.
:param string: str, the input string containing numeric character references.
:return: str, the input string with numeric character references replaced with their corresponding Unicode characters.
>>> unescaper = NumericEntityUnescaper()
>>> unescaper.replace("ABC")
'ABC'
"""
@staticmethod
def is_hex_char(char):
"""
Determines whether a given character is a hexadecimal digit.
:param char: str, the character to check.
:return: bool, True if the character is a hexadecimal digit, False otherwise.
>>> NumericEntityUnescaper.is_hex_char('a')
True
""" | import unittest
class NumericEntityUnescaperTestReplace(unittest.TestCase):
def test_replace_1(self):
unescaper = NumericEntityUnescaper()
res = unescaper.replace("ABC")
self.assertEqual(res, "ABC")
def test_replace_2(self):
unescaper = NumericEntityUnescaper()
res = unescaper.replace("AAA")
self.assertEqual(res, "AAA")
def test_replace_3(self):
unescaper = NumericEntityUnescaper()
res = unescaper.replace("BBB")
self.assertEqual(res, "BBB")
def test_replace_4(self):
unescaper = NumericEntityUnescaper()
res = unescaper.replace("CCC")
self.assertEqual(res, "CCC")
def test_replace_5(self):
unescaper = NumericEntityUnescaper()
res = unescaper.replace("")
self.assertEqual(res, "")
def test_replace_6(self):
unescaper = NumericEntityUnescaper()
res = unescaper.replace("&#")
self.assertEqual(res, "")
def test_replace_7(self):
unescaper = NumericEntityUnescaper()
res = unescaper.replace("eBC")
self.assertEqual(res, "eBC")
def test_replace_8(self):
unescaper = NumericEntityUnescaper()
res = unescaper.replace("&#???;BC")
self.assertEqual(res, "&#???;BC")
def test_replace_9(self):
unescaper = NumericEntityUnescaper()
res = unescaper.replace("CCC;")
self.assertEqual(res, "CCC")
def test_replace_10(self):
unescaper = NumericEntityUnescaper()
res = unescaper.replace("&#X")
self.assertEqual(res, "")
def test_replace_11(self):
unescaper = NumericEntityUnescaper()
res = unescaper.replace("&#c1d;BC")
self.assertEqual(res, "")
class NumericEntityUnescaperTestIsHexChar(unittest.TestCase):
def test_is_hex_char_1(self):
unescaper = NumericEntityUnescaper()
res = unescaper.is_hex_char('0')
self.assertEqual(res, True)
def test_is_hex_char_2(self):
unescaper = NumericEntityUnescaper()
res = unescaper.is_hex_char('F')
self.assertEqual(res, True)
def test_is_hex_char_3(self):
unescaper = NumericEntityUnescaper()
res = unescaper.is_hex_char('G')
self.assertEqual(res, False)
def test_is_hex_char_4(self):
unescaper = NumericEntityUnescaper()
res = unescaper.is_hex_char('X')
self.assertEqual(res, False)
def test_is_hex_char_5(self):
unescaper = NumericEntityUnescaper()
res = unescaper.is_hex_char('Z')
self.assertEqual(res, False)
class unescaperTest(unittest.TestCase):
def test_numericentityunescaper(self):
unescaper = NumericEntityUnescaper()
res = unescaper.replace("ABC")
self.assertEqual(res, "ABC")
unescaper = NumericEntityUnescaper()
res = unescaper.is_hex_char('0')
self.assertEqual(res, True) | class NumericEntityUnescaper:
def __init__(self):
pass
def replace(self, string):
out = []
pos = 0
length = len(string)
while pos < length - 2:
if string[pos] == '&' and string[pos + 1] == '#':
start = pos + 2
is_hex = False
first_char = string[start]
if first_char == 'x' or first_char == 'X':
start += 1
is_hex = True
if start == length:
return ''.join(out)
end = start
while end < length and self.is_hex_char(string[end]):
end += 1
if end < length and string[end] == ';':
try:
entity_value = int(string[start:end], 16 if is_hex else 10)
except:
return ''.join(out)
out.append(chr(entity_value))
pos = end + 1
continue
out.append(string[pos])
pos += 1
return ''.join(out)
@staticmethod
def is_hex_char(char):
return char.isdigit() or ('a' <= char.lower() <= 'f') | [] | """
This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string.
"""
| [
{
"method_name": "replace",
"method_description": "def replace(self, string):\n \"\"\"\n Replaces numeric character references (HTML entities) in the input string with their corresponding Unicode characters.\n :param string: str, the input string containing numeric character references.\n :return: str, the input string with numeric character references replaced with their corresponding Unicode characters.\n >>> unescaper = NumericEntityUnescaper()\n >>> unescaper.replace(\"ABC\")\n 'ABC'\n\n \"\"\"",
"test_class": "NumericEntityUnescaperTestReplace",
"test_code": "class NumericEntityUnescaperTestReplace(unittest.TestCase):\n def test_replace_1(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"ABC\")\n self.assertEqual(res, \"ABC\")\n\n def test_replace_2(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"AAA\")\n self.assertEqual(res, \"AAA\")\n\n def test_replace_3(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"BBB\")\n self.assertEqual(res, \"BBB\")\n\n def test_replace_4(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"CCC\")\n self.assertEqual(res, \"CCC\")\n\n def test_replace_5(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"\")\n self.assertEqual(res, \"\")\n\n def test_replace_6(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"&#\")\n self.assertEqual(res, \"\")\n\n def test_replace_7(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"eBC\")\n self.assertEqual(res, \"eBC\")\n\n def test_replace_8(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"&#???;BC\")\n self.assertEqual(res, \"&#???;BC\")\n\n def test_replace_9(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"CCC;\")\n self.assertEqual(res, \"CCC\")\n\n def test_replace_10(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"&#X\")\n self.assertEqual(res, \"\")\n\n def test_replace_11(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"&#c1d;BC\")\n self.assertEqual(res, \"\")",
"solution_code": "def replace(self, string):\n out = []\n pos = 0\n length = len(string)\n\n while pos < length - 2:\n if string[pos] == '&' and string[pos + 1] == '#':\n start = pos + 2\n is_hex = False\n first_char = string[start]\n\n if first_char == 'x' or first_char == 'X':\n start += 1\n is_hex = True\n\n if start == length:\n return ''.join(out)\n\n end = start\n while end < length and self.is_hex_char(string[end]):\n end += 1\n\n if end < length and string[end] == ';':\n try:\n entity_value = int(string[start:end], 16 if is_hex else 10)\n except:\n return ''.join(out)\n\n out.append(chr(entity_value))\n pos = end + 1\n continue\n\n out.append(string[pos])\n pos += 1\n\n return ''.join(out)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"is_hex_char"
]
}
},
{
"method_name": "is_hex_char",
"method_description": "@staticmethod\n def is_hex_char(char):\n \"\"\"\n Determines whether a given character is a hexadecimal digit.\n :param char: str, the character to check.\n :return: bool, True if the character is a hexadecimal digit, False otherwise.\n >>> NumericEntityUnescaper.is_hex_char('a')\n True\n\n \"\"\"",
"test_class": "NumericEntityUnescaperTestIsHexChar",
"test_code": "class NumericEntityUnescaperTestIsHexChar(unittest.TestCase):\n def test_is_hex_char_1(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('0')\n self.assertEqual(res, True)\n\n def test_is_hex_char_2(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('F')\n self.assertEqual(res, True)\n\n def test_is_hex_char_3(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('G')\n self.assertEqual(res, False)\n\n def test_is_hex_char_4(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('X')\n self.assertEqual(res, False)\n\n def test_is_hex_char_5(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('Z')\n self.assertEqual(res, False)",
"solution_code": "@staticmethod\n def is_hex_char(char):\n return char.isdigit() or ('a' <= char.lower() <= 'f')",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | NumericEntityUnescaper | [
"NumericEntityUnescaperTestReplace",
"NumericEntityUnescaperTestIsHexChar",
"unescaperTest"
] | class NumericEntityUnescaper:
def __init__(self):
pass
| [] |
ClassEval_67 | class Order:
"""
The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout.
"""
def __init__(self):
"""
Initialize the order management system
self.menu stores the dishes of resturant inventory
menu = [{"dish": dish name, "price": price, "count": count}, ...]
self.selected_dishes stores the dished selected by customer
selected_dish = {"dish": dish name, "count": count, price: price}
self.sales stores the sales of each dish
sales = {dish name: sales}
"""
self.menu = []
self.selected_dishes = []
self.sales = {}
def add_dish(self, dish):
"""
Check the self.menu and add into self.selected_dish if the dish count is valid.
And if the dish has successfully been added, change the count in self.menu.
:param dish: dict, the information of dish. dish = {"dish": dish name, "count": count, price: price}
:return: True if successfully added, or False otherwise.
>>> order = Order()
>>> order.menu.append({"dish": "dish1", "price": 10, "count": 5})
>>> order.add_dish({"dish": "dish1", "price": 10, "count": 3})
True
"""
def calculate_total(self):
"""
Calculate the total price of dishes that have been ordered. Multiply the count, price and sales.
:return total: float, the final total price.
>>> order = Order()
>>> order.menu.append({"dish": "dish1", "price": 10, "count": 5})
>>> order.sales = {"dish1": 0.8}
>>> order.add_dish({"dish": "dish1", "price": 10, "count": 4})
True
>>> order.calculate_total()
32.0
"""
def checkout(self):
"""
Check out the dished ordered. IF the self.selected_dishes is not empty, invoke the calculate_total
method to check out.
:return Flase if the self.selected_dishes is empty, or total(return value of calculate_total) otherwise.
>>> order = Order()
>>> order.menu.append({"dish": "dish1", "price": 10, "count": 5})
>>> order.sales = {"dish1": 0.8}
>>> order.add_dish({"dish": "dish1", "price": 10, "count": 4})
True
>>> order.checkout()
32.0
""" | import unittest
class OrderTestAddDish(unittest.TestCase):
def setUp(self):
self.order = Order()
self.order.menu.append({"dish": "dish1", "price": 10, "count": 5})
self.order.menu.append({"dish": "dish2", "price": 15, "count": 3})
self.order.menu.append({"dish": "dish3", "price": 20, "count": 7})
self.order.sales = {"dish1": 0.9, "dish2": 1, "dish3": 0.8}
# add dish in menu
def test_add_dish_1(self):
result = self.order.add_dish({"dish": "dish3", "price": 15, "count": 4})
self.assertTrue(result)
# test the status of self.menu and self.selected_dishes
menu = self.order.menu
for menu_dish in menu:
if menu_dish["dish"] == "dish1":
self.assertEqual(menu_dish["count"], 5)
if menu_dish["dish"] == "dish2":
self.assertEqual(menu_dish["count"], 3)
if menu_dish["dish"] == "dish3":
self.assertEqual(menu_dish["count"], 3)
self.assertEqual(self.order.selected_dishes, [{"dish": "dish3", "price": 15, "count": 4}])
# add dish when dish count exceeds the remaining count
def test_add_dish_2(self):
result = self.order.add_dish({"dish": "dish3", "price": 15, "count": 8})
self.assertFalse(result)
menu = self.order.menu
for menu_dish in menu:
if menu_dish["dish"] == "dish1":
self.assertEqual(menu_dish["count"], 5)
if menu_dish["dish"] == "dish2":
self.assertEqual(menu_dish["count"], 3)
if menu_dish["dish"] == "dish3":
self.assertEqual(menu_dish["count"], 7)
self.assertEqual(self.order.selected_dishes, [])
def test_add_dish_3(self):
result = self.order.add_dish({"dish": "dish3", "price": 15, "count": 7})
self.assertTrue(result)
# test the status of self.menu and self.selected_dishes
menu = self.order.menu
for menu_dish in menu:
if menu_dish["dish"] == "dish1":
self.assertEqual(menu_dish["count"], 5)
if menu_dish["dish"] == "dish2":
self.assertEqual(menu_dish["count"], 3)
if menu_dish["dish"] == "dish3":
self.assertEqual(menu_dish["count"], 0)
self.assertEqual(self.order.selected_dishes, [{"dish": "dish3", "price": 15, "count": 7}])
def test_add_dish_4(self):
result = self.order.add_dish({"dish": "dish3", "price": 15, "count": 6})
self.assertTrue(result)
# test the status of self.menu and self.selected_dishes
menu = self.order.menu
for menu_dish in menu:
if menu_dish["dish"] == "dish1":
self.assertEqual(menu_dish["count"], 5)
if menu_dish["dish"] == "dish2":
self.assertEqual(menu_dish["count"], 3)
if menu_dish["dish"] == "dish3":
self.assertEqual(menu_dish["count"], 1)
self.assertEqual(self.order.selected_dishes, [{"dish": "dish3", "price": 15, "count": 6}])
def test_add_dish_5(self):
result = self.order.add_dish({"dish": "dish3", "price": 15, "count": 5})
self.assertTrue(result)
# test the status of self.menu and self.selected_dishes
menu = self.order.menu
for menu_dish in menu:
if menu_dish["dish"] == "dish1":
self.assertEqual(menu_dish["count"], 5)
if menu_dish["dish"] == "dish2":
self.assertEqual(menu_dish["count"], 3)
if menu_dish["dish"] == "dish3":
self.assertEqual(menu_dish["count"], 2)
self.assertEqual(self.order.selected_dishes, [{"dish": "dish3", "price": 15, "count": 5}])
def test_add_dish_6(self):
self.order.menu = []
result = self.order.add_dish({})
self.assertTrue(result)
class OrderTestCalculateTotal(unittest.TestCase):
def setUp(self):
self.order = Order()
self.order.menu.append({"dish": "dish1", "price": 10, "count": 5})
self.order.menu.append({"dish": "dish2", "price": 15, "count": 3})
self.order.menu.append({"dish": "dish3", "price": 20, "count": 7})
self.order.sales = {"dish1": 0.9, "dish2": 1, "dish3": 0.8}
def test_calculate_total_1(self):
self.order.add_dish({"dish": "dish1", "price": 10, "count": 2})
self.order.add_dish({"dish": "dish3", "price": 20, "count": 2})
result = self.order.calculate_total()
self.assertEqual(50, result)
def test_calculate_total_2(self):
self.order.add_dish({"dish": "dish1", "price": 10, "count": 2})
self.order.add_dish({"dish": "dish2", "price": 15, "count": 2})
result = self.order.calculate_total()
self.assertEqual(48, result)
def test_calculate_total_3(self):
self.order.add_dish({"dish": "dish1", "price": 10, "count": 1})
self.order.add_dish({"dish": "dish3", "price": 20, "count": 1})
result = self.order.calculate_total()
self.assertEqual(25, result)
def test_calculate_total_4(self):
self.order.add_dish({"dish": "dish1", "price": 10, "count": 3})
self.order.add_dish({"dish": "dish3", "price": 20, "count": 3})
result = self.order.calculate_total()
self.assertEqual(75, result)
def test_calculate_total_5(self):
self.order.add_dish({"dish": "dish1", "price": 10, "count": 4})
self.order.add_dish({"dish": "dish3", "price": 20, "count": 4})
result = self.order.calculate_total()
self.assertEqual(100, result)
class OrderTestCheckout(unittest.TestCase):
def setUp(self):
self.order = Order()
self.order.menu.append({"dish": "dish1", "price": 10, "count": 5})
self.order.menu.append({"dish": "dish2", "price": 15, "count": 3})
self.order.menu.append({"dish": "dish3", "price": 20, "count": 7})
self.order.sales = {"dish1": 0.9, "dish2": 1, "dish3": 0.8}
# as test_main
def test_checkout_1(self):
self.order.add_dish({"dish": "dish1", "price": 10, "count": 2})
self.order.add_dish({"dish": "dish3", "price": 20, "count": 2})
result = self.order.checkout()
self.assertEqual(50, result)
menu = self.order.menu
for menu_dish in menu:
if menu_dish["dish"] == "dish1":
self.assertEqual(menu_dish["count"], 3)
if menu_dish["dish"] == "dish2":
self.assertEqual(menu_dish["count"], 3)
if menu_dish["dish"] == "dish3":
self.assertEqual(menu_dish["count"], 5)
self.assertEqual([], self.order.selected_dishes)
# haven't ordered dishes.
# self.selected_dishes is empty
def test_checkout_2(self):
result = self.order.checkout()
self.assertFalse(result)
def test_checkout_3(self):
self.order.add_dish({"dish": "dish1", "price": 10, "count": 1})
self.order.add_dish({"dish": "dish3", "price": 20, "count": 1})
result = self.order.checkout()
self.assertEqual(25, result)
menu = self.order.menu
for menu_dish in menu:
if menu_dish["dish"] == "dish1":
self.assertEqual(menu_dish["count"], 4)
if menu_dish["dish"] == "dish2":
self.assertEqual(menu_dish["count"], 3)
if menu_dish["dish"] == "dish3":
self.assertEqual(menu_dish["count"], 6)
self.assertEqual([], self.order.selected_dishes)
def test_checkout_4(self):
self.order.add_dish({"dish": "dish1", "price": 10, "count": 3})
self.order.add_dish({"dish": "dish3", "price": 20, "count": 3})
result = self.order.checkout()
self.assertEqual(75, result)
menu = self.order.menu
for menu_dish in menu:
if menu_dish["dish"] == "dish1":
self.assertEqual(menu_dish["count"], 2)
if menu_dish["dish"] == "dish2":
self.assertEqual(menu_dish["count"], 3)
if menu_dish["dish"] == "dish3":
self.assertEqual(menu_dish["count"], 4)
self.assertEqual([], self.order.selected_dishes)
def test_checkout_5(self):
self.order.add_dish({"dish": "dish1", "price": 10, "count": 5})
self.order.add_dish({"dish": "dish3", "price": 20, "count": 5})
result = self.order.checkout()
self.assertEqual(125, result)
menu = self.order.menu
for menu_dish in menu:
if menu_dish["dish"] == "dish1":
self.assertEqual(menu_dish["count"], 0)
if menu_dish["dish"] == "dish2":
self.assertEqual(menu_dish["count"], 3)
if menu_dish["dish"] == "dish3":
self.assertEqual(menu_dish["count"], 2)
self.assertEqual([], self.order.selected_dishes)
class OrderTest(unittest.TestCase):
def setUp(self):
self.order = Order()
self.order.menu.append({"dish": "dish1", "price": 10, "count": 5})
self.order.menu.append({"dish": "dish2", "price": 15, "count": 3})
self.order.menu.append({"dish": "dish3", "price": 20, "count": 7})
self.order.sales = {"dish1": 0.9, "dish2": 1, "dish3": 0.8}
def test_order(self):
self.order.add_dish({"dish": "dish1", "price": 10, "count": 2})
self.order.add_dish({"dish": "dish3", "price": 20, "count": 2})
result = self.order.checkout()
self.assertEqual(50, result)
menu = self.order.menu
for menu_dish in menu:
if menu_dish["dish"] == "dish1":
self.assertEqual(menu_dish["count"], 3)
if menu_dish["dish"] == "dish2":
self.assertEqual(menu_dish["count"], 3)
if menu_dish["dish"] == "dish3":
self.assertEqual(menu_dish["count"], 5)
self.assertEqual([], self.order.selected_dishes) | class Order:
def __init__(self):
self.menu = []
# menu = [{"dish": dish name, "price": price, "count": count}, ...]
self.selected_dishes = []
# selected_dish = {"dish": dish name, "count": count, price: price}
self.sales = {}
#
def add_dish(self, dish):
for menu_dish in self.menu:
if dish["dish"] == menu_dish["dish"]:
if menu_dish["count"] < dish["count"]:
return False
else:
menu_dish["count"] -= dish["count"]
break
self.selected_dishes.append(dish)
return True
def calculate_total(self):
total = 0
for dish in self.selected_dishes:
total += dish["price"] * dish["count"] * self.sales[dish["dish"]]
return total
def checkout(self):
if len(self.selected_dishes) == 0:
return False
total = self.calculate_total()
self.selected_dishes = []
return total | [] | """
The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout.
"""
| [
{
"method_name": "add_dish",
"method_description": "def add_dish(self, dish):\n \"\"\"\n Check the self.menu and add into self.selected_dish if the dish count is valid.\n And if the dish has successfully been added, change the count in self.menu.\n :param dish: dict, the information of dish. dish = {\"dish\": dish name, \"count\": count, price: price}\n :return: True if successfully added, or False otherwise.\n >>> order = Order()\n >>> order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n >>> order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 3})\n True\n \"\"\"",
"test_class": "OrderTestAddDish",
"test_code": "class OrderTestAddDish(unittest.TestCase):\n def setUp(self):\n self.order = Order()\n\n self.order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n self.order.menu.append({\"dish\": \"dish2\", \"price\": 15, \"count\": 3})\n self.order.menu.append({\"dish\": \"dish3\", \"price\": 20, \"count\": 7})\n self.order.sales = {\"dish1\": 0.9, \"dish2\": 1, \"dish3\": 0.8}\n\n # add dish in menu\n def test_add_dish_1(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 4})\n self.assertTrue(result)\n\n # test the status of self.menu and self.selected_dishes\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 3)\n self.assertEqual(self.order.selected_dishes, [{\"dish\": \"dish3\", \"price\": 15, \"count\": 4}])\n\n # add dish when dish count exceeds the remaining count\n def test_add_dish_2(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 8})\n self.assertFalse(result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 7)\n self.assertEqual(self.order.selected_dishes, [])\n\n def test_add_dish_3(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 7})\n self.assertTrue(result)\n\n # test the status of self.menu and self.selected_dishes\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 0)\n self.assertEqual(self.order.selected_dishes, [{\"dish\": \"dish3\", \"price\": 15, \"count\": 7}])\n\n def test_add_dish_4(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 6})\n self.assertTrue(result)\n\n # test the status of self.menu and self.selected_dishes\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 1)\n self.assertEqual(self.order.selected_dishes, [{\"dish\": \"dish3\", \"price\": 15, \"count\": 6}])\n\n def test_add_dish_5(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 5})\n self.assertTrue(result)\n\n # test the status of self.menu and self.selected_dishes\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 2)\n self.assertEqual(self.order.selected_dishes, [{\"dish\": \"dish3\", \"price\": 15, \"count\": 5}])\n\n def test_add_dish_6(self):\n self.order.menu = []\n result = self.order.add_dish({})\n self.assertTrue(result)",
"solution_code": "def add_dish(self, dish):\n for menu_dish in self.menu:\n if dish[\"dish\"] == menu_dish[\"dish\"]:\n if menu_dish[\"count\"] < dish[\"count\"]:\n return False\n else:\n menu_dish[\"count\"] -= dish[\"count\"]\n break\n self.selected_dishes.append(dish)\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.menu",
"self.selected_dishes"
],
"method_dependencies": []
}
},
{
"method_name": "calculate_total",
"method_description": "def calculate_total(self):\n \"\"\"\n Calculate the total price of dishes that have been ordered. Multiply the count, price and sales.\n :return total: float, the final total price.\n >>> order = Order()\n >>> order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n >>> order.sales = {\"dish1\": 0.8}\n >>> order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 4})\n True\n >>> order.calculate_total()\n 32.0\n \"\"\"",
"test_class": "OrderTestCalculateTotal",
"test_code": "class OrderTestCalculateTotal(unittest.TestCase):\n def setUp(self):\n self.order = Order()\n self.order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n self.order.menu.append({\"dish\": \"dish2\", \"price\": 15, \"count\": 3})\n self.order.menu.append({\"dish\": \"dish3\", \"price\": 20, \"count\": 7})\n self.order.sales = {\"dish1\": 0.9, \"dish2\": 1, \"dish3\": 0.8}\n\n def test_calculate_total_1(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 2})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 2})\n result = self.order.calculate_total()\n self.assertEqual(50, result)\n\n def test_calculate_total_2(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 2})\n self.order.add_dish({\"dish\": \"dish2\", \"price\": 15, \"count\": 2})\n result = self.order.calculate_total()\n self.assertEqual(48, result)\n\n def test_calculate_total_3(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 1})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 1})\n result = self.order.calculate_total()\n self.assertEqual(25, result)\n\n def test_calculate_total_4(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 3})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 3})\n result = self.order.calculate_total()\n self.assertEqual(75, result)\n\n def test_calculate_total_5(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 4})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 4})\n result = self.order.calculate_total()\n self.assertEqual(100, result)",
"solution_code": "def calculate_total(self):\n total = 0\n for dish in self.selected_dishes:\n total += dish[\"price\"] * dish[\"count\"] * self.sales[dish[\"dish\"]]\n return total",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.sales",
"self.selected_dishes"
],
"method_dependencies": []
}
},
{
"method_name": "checkout",
"method_description": "def checkout(self):\n \"\"\"\n Check out the dished ordered. IF the self.selected_dishes is not empty, invoke the calculate_total\n method to check out.\n :return Flase if the self.selected_dishes is empty, or total(return value of calculate_total) otherwise.\n >>> order = Order()\n >>> order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n >>> order.sales = {\"dish1\": 0.8}\n >>> order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 4})\n True\n >>> order.checkout()\n 32.0\n \"\"\"",
"test_class": "OrderTestCheckout",
"test_code": "class OrderTestCheckout(unittest.TestCase):\n def setUp(self):\n self.order = Order()\n self.order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n self.order.menu.append({\"dish\": \"dish2\", \"price\": 15, \"count\": 3})\n self.order.menu.append({\"dish\": \"dish3\", \"price\": 20, \"count\": 7})\n self.order.sales = {\"dish1\": 0.9, \"dish2\": 1, \"dish3\": 0.8}\n\n # as test_main\n def test_checkout_1(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 2})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 2})\n result = self.order.checkout()\n self.assertEqual(50, result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 5)\n self.assertEqual([], self.order.selected_dishes)\n\n # haven't ordered dishes.\n # self.selected_dishes is empty\n def test_checkout_2(self):\n result = self.order.checkout()\n self.assertFalse(result)\n\n def test_checkout_3(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 1})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 1})\n result = self.order.checkout()\n self.assertEqual(25, result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 4)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 6)\n self.assertEqual([], self.order.selected_dishes)\n\n def test_checkout_4(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 3})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 3})\n result = self.order.checkout()\n self.assertEqual(75, result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 2)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 4)\n self.assertEqual([], self.order.selected_dishes)\n\n def test_checkout_5(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 5})\n result = self.order.checkout()\n self.assertEqual(125, result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 0)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 2)\n self.assertEqual([], self.order.selected_dishes)",
"solution_code": "def checkout(self):\n if len(self.selected_dishes) == 0:\n return False\n total = self.calculate_total()\n self.selected_dishes = []\n return total",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.selected_dishes"
],
"method_dependencies": [
"calculate_total"
]
}
}
] | Order | [
"OrderTestAddDish",
"OrderTestCalculateTotal",
"OrderTestCheckout",
"OrderTest"
] | class Order:
def __init__(self):
"""
Initialize the order management system
self.menu stores the dishes of resturant inventory
menu = [{"dish": dish name, "price": price, "count": count}, ...]
self.selected_dishes stores the dished selected by customer
selected_dish = {"dish": dish name, "count": count, price: price}
self.sales stores the sales of each dish
sales = {dish name: sales}
"""
self.menu = []
self.selected_dishes = []
self.sales = {}
| [
"self.menu",
"self.sales",
"self.selected_dishes"
] |
ClassEval_68 | class PageUtil:
"""
PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner.
"""
def __init__(self, data, page_size):
"""
Initialize the PageUtil object with the given data and page size.
:param data: list, the data to be paginated
:param page_size: int, the number of items per page
"""
self.data = data
self.page_size = page_size
self.total_items = len(data)
self.total_pages = (self.total_items + page_size - 1) // page_size
def get_page(self, page_number):
"""
Retrieve a specific page of data.
:param page_number: int, the page number to fetch
:return: list, the data on the specified page
>>> page_util = PageUtil([1, 2, 3, 4], 1)
>>> page_util.get_page(1)
[1]
"""
def get_page_info(self, page_number):
"""
Retrieve information about a specific page.
:param page_number: int, the page number to fetch information about
:return: dict, containing page information such as current page number, total pages, etc.
>>> page_util = PageUtil([1, 2, 3, 4], 1)
>>> page_util.get_page_info(1)
>>> {
>>> "current_page": 1,
>>> "per_page": 1,
>>> "total_pages": 4,
>>> "total_items": 4,
>>> "has_previous": False,
>>> "has_next": True,
>>> "data": [1]
>>> }
"""
def search(self, keyword):
"""
Search for items in the data that contain the given keyword.
:param keyword: str, the keyword to search for
:return: dict, containing search information such as total results and matching items
>>> page_util = PageUtil([1, 2, 3, 4], 1)
>>> page_util.search("1")
>>> search_info = {
>>> "keyword": "1",
>>> "total_results": 1,
>>> "total_pages": 1,
>>> "results": [1]
>>> }
""" | import unittest
class PageUtilTestGetPage(unittest.TestCase):
def setUp(self):
self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.page_size = 3
self.page_util = PageUtil(self.data, self.page_size)
def test_get_page_1(self):
page_number = 1
expected_page = [1, 2, 3]
actual_page = self.page_util.get_page(page_number)
self.assertEqual(actual_page, expected_page)
def test_get_page_2(self):
page_number = 2
expected_page = [4, 5, 6]
actual_page = self.page_util.get_page(page_number)
self.assertEqual(actual_page, expected_page)
def test_get_page_3(self):
page_number = 3
expected_page = [7, 8, 9]
actual_page = self.page_util.get_page(page_number)
self.assertEqual(actual_page, expected_page)
def test_get_page_4(self):
page_number = 4
expected_page = [10]
actual_page = self.page_util.get_page(page_number)
self.assertEqual(actual_page, expected_page)
def test_get_page_5(self):
invalid_page_number = 0
empty_page = []
actual_page = self.page_util.get_page(invalid_page_number)
self.assertEqual(actual_page, empty_page)
class PageUtilTestGetPageInfo(unittest.TestCase):
def setUp(self):
self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.page_size = 3
self.page_util = PageUtil(self.data, self.page_size)
def test_get_page_info_1(self):
page_number = 2
expected_info = {
"current_page": 2,
"per_page": 3,
"total_pages": 4,
"total_items": 10,
"has_previous": True,
"has_next": True,
"data": [4, 5, 6]
}
actual_info = self.page_util.get_page_info(page_number)
self.assertEqual(actual_info, expected_info)
def test_get_page_info_2(self):
page_number = 1
expected_info = {
"current_page": 1,
"per_page": 3,
"total_pages": 4,
"total_items": 10,
"has_previous": False,
"has_next": True,
"data": [1, 2, 3]
}
actual_info = self.page_util.get_page_info(page_number)
self.assertEqual(actual_info, expected_info)
def test_get_page_info_3(self):
page_number = 3
expected_info = {
"current_page": 3,
"per_page": 3,
"total_pages": 4,
"total_items": 10,
"has_previous": True,
"has_next": True,
"data": [7, 8, 9]
}
actual_info = self.page_util.get_page_info(page_number)
self.assertEqual(actual_info, expected_info)
def test_get_page_info_4(self):
page_number = 4
expected_info = {
"current_page": 4,
"per_page": 3,
"total_pages": 4,
"total_items": 10,
"has_previous": True,
"has_next": False,
"data": [10]
}
actual_info = self.page_util.get_page_info(page_number)
self.assertEqual(actual_info, expected_info)
def test_get_page_info_5(self):
invalid_page_number = 5
empty_info = {}
actual_info = self.page_util.get_page_info(invalid_page_number)
self.assertEqual(actual_info, empty_info)
class PageUtilTestSearch(unittest.TestCase):
def setUp(self):
self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.page_size = 3
self.page_util = PageUtil(self.data, self.page_size)
def test_search_1(self):
keyword = "1"
expected_results = {
"keyword": "1",
"total_results": 2,
"total_pages": 1,
"results": [1, 10]
}
actual_results = self.page_util.search(keyword)
self.assertEqual(actual_results, expected_results)
def test_search_2(self):
keyword = "2"
expected_results = {
"keyword": "2",
"total_results": 1,
"total_pages": 1,
"results": [2]
}
actual_results = self.page_util.search(keyword)
self.assertEqual(actual_results, expected_results)
def test_search_3(self):
keyword = "3"
expected_results = {
"keyword": "3",
"total_results": 1,
"total_pages": 1,
"results": [3]
}
actual_results = self.page_util.search(keyword)
self.assertEqual(actual_results, expected_results)
def test_search_4(self):
keyword = "4"
expected_results = {
"keyword": "4",
"total_results": 1,
"total_pages": 1,
"results": [4]
}
actual_results = self.page_util.search(keyword)
self.assertEqual(actual_results, expected_results)
def test_search_5(self):
keyword = "11"
expected_results = {
"keyword": "11",
"total_results": 0,
"total_pages": 0,
"results": []
}
actual_results = self.page_util.search(keyword)
self.assertEqual(actual_results, expected_results)
class PageUtilTest(unittest.TestCase):
def setUp(self):
self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.page_size = 3
self.page_util = PageUtil(self.data, self.page_size)
def test_pageutil(self):
page_number = 1
expected_page = [1, 2, 3]
actual_page = self.page_util.get_page(page_number)
self.assertEqual(actual_page, expected_page)
page_number = 2
expected_info = {
"current_page": 2,
"per_page": 3,
"total_pages": 4,
"total_items": 10,
"has_previous": True,
"has_next": True,
"data": [4, 5, 6]
}
actual_info = self.page_util.get_page_info(page_number)
self.assertEqual(actual_info, expected_info)
keyword = "4"
expected_results = {
"keyword": "4",
"total_results": 1,
"total_pages": 1,
"results": [4]
}
actual_results = self.page_util.search(keyword)
self.assertEqual(actual_results, expected_results) | class PageUtil:
def __init__(self, data, page_size):
self.data = data
self.page_size = page_size
self.total_items = len(data)
self.total_pages = (self.total_items + page_size - 1) // page_size
def get_page(self, page_number):
if page_number < 1 or page_number > self.total_pages:
return []
start_index = (page_number - 1) * self.page_size
end_index = start_index + self.page_size
return self.data[start_index:end_index]
def get_page_info(self, page_number):
if page_number < 1 or page_number > self.total_pages:
return {}
start_index = (page_number - 1) * self.page_size
end_index = min(start_index + self.page_size, self.total_items)
page_data = self.data[start_index:end_index]
page_info = {
"current_page": page_number,
"per_page": self.page_size,
"total_pages": self.total_pages,
"total_items": self.total_items,
"has_previous": page_number > 1,
"has_next": page_number < self.total_pages,
"data": page_data
}
return page_info
def search(self, keyword):
results = [item for item in self.data if keyword in str(item)]
num_results = len(results)
num_pages = (num_results + self.page_size - 1) // self.page_size
search_info = {
"keyword": keyword,
"total_results": num_results,
"total_pages": num_pages,
"results": results
}
return search_info | [] | """
PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner.
"""
| [
{
"method_name": "get_page",
"method_description": "def get_page(self, page_number):\n \"\"\"\n Retrieve a specific page of data.\n :param page_number: int, the page number to fetch\n :return: list, the data on the specified page\n >>> page_util = PageUtil([1, 2, 3, 4], 1)\n >>> page_util.get_page(1)\n [1]\n\n \"\"\"",
"test_class": "PageUtilTestGetPage",
"test_code": "class PageUtilTestGetPage(unittest.TestCase):\n def setUp(self):\n self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n self.page_size = 3\n self.page_util = PageUtil(self.data, self.page_size)\n\n def test_get_page_1(self):\n page_number = 1\n expected_page = [1, 2, 3]\n actual_page = self.page_util.get_page(page_number)\n self.assertEqual(actual_page, expected_page)\n\n def test_get_page_2(self):\n page_number = 2\n expected_page = [4, 5, 6]\n actual_page = self.page_util.get_page(page_number)\n self.assertEqual(actual_page, expected_page)\n\n def test_get_page_3(self):\n page_number = 3\n expected_page = [7, 8, 9]\n actual_page = self.page_util.get_page(page_number)\n self.assertEqual(actual_page, expected_page)\n\n def test_get_page_4(self):\n page_number = 4\n expected_page = [10]\n actual_page = self.page_util.get_page(page_number)\n self.assertEqual(actual_page, expected_page)\n\n def test_get_page_5(self):\n invalid_page_number = 0\n empty_page = []\n actual_page = self.page_util.get_page(invalid_page_number)\n self.assertEqual(actual_page, empty_page)",
"solution_code": "def get_page(self, page_number):\n if page_number < 1 or page_number > self.total_pages:\n return []\n\n start_index = (page_number - 1) * self.page_size\n end_index = start_index + self.page_size\n return self.data[start_index:end_index]",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.data",
"self.page_size",
"self.total_pages"
],
"method_dependencies": []
}
},
{
"method_name": "get_page_info",
"method_description": "def get_page_info(self, page_number):\n \"\"\"\n Retrieve information about a specific page.\n :param page_number: int, the page number to fetch information about\n :return: dict, containing page information such as current page number, total pages, etc.\n >>> page_util = PageUtil([1, 2, 3, 4], 1)\n >>> page_util.get_page_info(1)\n >>> {\n >>> \"current_page\": 1,\n >>> \"per_page\": 1,\n >>> \"total_pages\": 4,\n >>> \"total_items\": 4,\n >>> \"has_previous\": False,\n >>> \"has_next\": True,\n >>> \"data\": [1]\n >>> }\n\n \"\"\"",
"test_class": "PageUtilTestGetPageInfo",
"test_code": "class PageUtilTestGetPageInfo(unittest.TestCase):\n def setUp(self):\n self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n self.page_size = 3\n self.page_util = PageUtil(self.data, self.page_size)\n\n def test_get_page_info_1(self):\n page_number = 2\n expected_info = {\n \"current_page\": 2,\n \"per_page\": 3,\n \"total_pages\": 4,\n \"total_items\": 10,\n \"has_previous\": True,\n \"has_next\": True,\n \"data\": [4, 5, 6]\n }\n actual_info = self.page_util.get_page_info(page_number)\n self.assertEqual(actual_info, expected_info)\n\n def test_get_page_info_2(self):\n page_number = 1\n expected_info = {\n \"current_page\": 1,\n \"per_page\": 3,\n \"total_pages\": 4,\n \"total_items\": 10,\n \"has_previous\": False,\n \"has_next\": True,\n \"data\": [1, 2, 3]\n }\n actual_info = self.page_util.get_page_info(page_number)\n self.assertEqual(actual_info, expected_info)\n\n def test_get_page_info_3(self):\n page_number = 3\n expected_info = {\n \"current_page\": 3,\n \"per_page\": 3,\n \"total_pages\": 4,\n \"total_items\": 10,\n \"has_previous\": True,\n \"has_next\": True,\n \"data\": [7, 8, 9]\n }\n actual_info = self.page_util.get_page_info(page_number)\n self.assertEqual(actual_info, expected_info)\n\n def test_get_page_info_4(self):\n page_number = 4\n expected_info = {\n \"current_page\": 4,\n \"per_page\": 3,\n \"total_pages\": 4,\n \"total_items\": 10,\n \"has_previous\": True,\n \"has_next\": False,\n \"data\": [10]\n }\n actual_info = self.page_util.get_page_info(page_number)\n self.assertEqual(actual_info, expected_info)\n\n def test_get_page_info_5(self):\n invalid_page_number = 5\n empty_info = {}\n actual_info = self.page_util.get_page_info(invalid_page_number)\n self.assertEqual(actual_info, empty_info)",
"solution_code": "def get_page_info(self, page_number):\n if page_number < 1 or page_number > self.total_pages:\n return {}\n\n start_index = (page_number - 1) * self.page_size\n end_index = min(start_index + self.page_size, self.total_items)\n page_data = self.data[start_index:end_index]\n\n page_info = {\n \"current_page\": page_number,\n \"per_page\": self.page_size,\n \"total_pages\": self.total_pages,\n \"total_items\": self.total_items,\n \"has_previous\": page_number > 1,\n \"has_next\": page_number < self.total_pages,\n \"data\": page_data\n }\n return page_info",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.data",
"self.page_size",
"self.total_items",
"self.total_pages"
],
"method_dependencies": []
}
},
{
"method_name": "search",
"method_description": "def search(self, keyword):\n \"\"\"\n Search for items in the data that contain the given keyword.\n :param keyword: str, the keyword to search for\n :return: dict, containing search information such as total results and matching items\n >>> page_util = PageUtil([1, 2, 3, 4], 1)\n >>> page_util.search(\"1\")\n >>> search_info = {\n >>> \"keyword\": \"1\",\n >>> \"total_results\": 1,\n >>> \"total_pages\": 1,\n >>> \"results\": [1]\n >>> }\n \"\"\"",
"test_class": "PageUtilTestSearch",
"test_code": "class PageUtilTestSearch(unittest.TestCase):\n def setUp(self):\n self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n self.page_size = 3\n self.page_util = PageUtil(self.data, self.page_size)\n\n def test_search_1(self):\n keyword = \"1\"\n expected_results = {\n \"keyword\": \"1\",\n \"total_results\": 2,\n \"total_pages\": 1,\n \"results\": [1, 10]\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)\n\n def test_search_2(self):\n keyword = \"2\"\n expected_results = {\n \"keyword\": \"2\",\n \"total_results\": 1,\n \"total_pages\": 1,\n \"results\": [2]\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)\n\n def test_search_3(self):\n keyword = \"3\"\n expected_results = {\n \"keyword\": \"3\",\n \"total_results\": 1,\n \"total_pages\": 1,\n \"results\": [3]\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)\n\n def test_search_4(self):\n keyword = \"4\"\n expected_results = {\n \"keyword\": \"4\",\n \"total_results\": 1,\n \"total_pages\": 1,\n \"results\": [4]\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)\n\n def test_search_5(self):\n keyword = \"11\"\n expected_results = {\n \"keyword\": \"11\",\n \"total_results\": 0,\n \"total_pages\": 0,\n \"results\": []\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)",
"solution_code": "def search(self, keyword):\n results = [item for item in self.data if keyword in str(item)]\n num_results = len(results)\n num_pages = (num_results + self.page_size - 1) // self.page_size\n\n search_info = {\n \"keyword\": keyword,\n \"total_results\": num_results,\n \"total_pages\": num_pages,\n \"results\": results\n }\n return search_info",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.data",
"self.page_size"
],
"method_dependencies": []
}
}
] | PageUtil | [
"PageUtilTestGetPage",
"PageUtilTestGetPageInfo",
"PageUtilTestSearch",
"PageUtilTest"
] | class PageUtil:
def __init__(self, data, page_size):
"""
Initialize the PageUtil object with the given data and page size.
:param data: list, the data to be paginated
:param page_size: int, the number of items per page
"""
self.data = data
self.page_size = page_size
self.total_items = len(data)
self.total_pages = (self.total_items + page_size - 1) // page_size
| [
"self.data",
"self.page_size",
"self.total_items",
"self.total_pages"
] |
ClassEval_69 | import PyPDF2
class PDFHandler:
"""
The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library.
"""
def __init__(self, filepaths):
"""
takes a list of file paths filepaths as a parameter.
It creates a list named readers using PyPDF2, where each reader opens a file from the given paths.
"""
self.filepaths = filepaths
self.readers = [PyPDF2.PdfFileReader(fp) for fp in filepaths]
def merge_pdfs(self, output_filepath):
"""
Read files in self.readers which stores handles to multiple PDF files.
Merge them to one pdf and update the page number, then save in disk.
:param output_filepath: str, ouput file path to save to
:return: str, "Merged PDFs saved at {output_filepath}" if successfully merged
>>> handler = PDFHandler(['a.pdf', 'b.pdf'])
>>> handler.merge_pdfs('out.pdf')
Merged PDFs saved at out.pdf
"""
def extract_text_from_pdfs(self):
"""
Extract text from pdf files in self.readers
:return pdf_texts: list of str, each element is the text of one pdf file
>>> handler = PDFHandler(['a.pdf', 'b.pdf'])
>>> handler.extract_text_from_pdfs()
['Test a.pdf', 'Test b.pdf']
""" | import os
import unittest
from PyPDF2 import PdfFileReader
from reportlab.pdfgen import canvas
class TestPDFHandler(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_files = ["test1.pdf", "test2.pdf"]
cls.test_text = ["This is a test1.", "This is a test2."]
for i in range(2):
c = canvas.Canvas(cls.test_files[i])
c.drawString(100, 100, cls.test_text[i])
c.showPage()
c.save()
@classmethod
def tearDownClass(cls):
for filename in cls.test_files:
os.remove(filename)
os.remove("merged.pdf")
class PDFHandlerTestMergePdfs(unittest.TestCase):
def setUp(self) -> None:
TestPDFHandler.setUpClass()
def tearDown(self) -> None:
TestPDFHandler.tearDownClass()
def test_merge_pdfs(self):
TestPDFHandler.setUpClass()
handler = PDFHandler(TestPDFHandler.test_files)
result = handler.merge_pdfs("merged.pdf")
self.assertEqual("Merged PDFs saved at merged.pdf", result)
self.assertTrue(os.path.exists("merged.pdf"))
class PDFHandlerTestExtractTextFromPdfs(unittest.TestCase):
def setUp(self) -> None:
TestPDFHandler.setUpClass()
def test_extract_text_from_pdfs(self):
TestPDFHandler.setUpClass()
handler = PDFHandler(TestPDFHandler.test_files)
result = handler.extract_text_from_pdfs()
self.assertEqual(result, ["This is a test1.\n", "This is a test2.\n"])
class PDFHandlerTestMain(unittest.TestCase):
def setUp(self) -> None:
TestPDFHandler.setUpClass()
def tearDown(self) -> None:
TestPDFHandler.tearDownClass()
def test_main(self):
TestPDFHandler.setUpClass()
handler = PDFHandler(TestPDFHandler.test_files)
result = handler.merge_pdfs("merged.pdf")
self.assertEqual("Merged PDFs saved at merged.pdf", result)
self.assertTrue(os.path.exists("merged.pdf"))
result = handler.extract_text_from_pdfs()
self.assertEqual(result, ["This is a test1.\n", "This is a test2.\n"]) | import PyPDF2
class PDFHandler:
def __init__(self, filepaths):
self.filepaths = filepaths
# PdfFileReader is deprecated and was removed in PyPDF2 3.0.0. Use PdfReader instead.
self.readers = [PyPDF2.PdfReader(fp) for fp in filepaths]
def merge_pdfs(self, output_filepath):
pdf_writer = PyPDF2.PdfWriter()
for reader in self.readers:
# reader.getNumPages is deprecated and was removed in PyPDF2 3.0.0. Use len(reader.pages) instead.
for page_num in range(len(reader.pages)):
# reader.getPage(pageNumber) is deprecated and was removed in PyPDF2 3.0.0. Use reader.pages[page_number] instead.
page = reader.pages[page_num]
# addPage is deprecated and was removed in PyPDF2 3.0.0. Use add_page instead.
pdf_writer.add_page(page)
with open(output_filepath, 'wb') as out:
pdf_writer.write(out)
return f"Merged PDFs saved at {output_filepath}"
def extract_text_from_pdfs(self):
pdf_texts = []
for reader in self.readers:
for page_num in range(len(reader.pages)):
page = reader.pages[page_num]
pdf_texts.append(page.extract_text())
return pdf_texts | [
"import PyPDF2"
] | """
The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library.
"""
| [
{
"method_name": "merge_pdfs",
"method_description": "def merge_pdfs(self, output_filepath):\n \"\"\"\n Read files in self.readers which stores handles to multiple PDF files.\n Merge them to one pdf and update the page number, then save in disk.\n :param output_filepath: str, ouput file path to save to\n :return: str, \"Merged PDFs saved at {output_filepath}\" if successfully merged\n >>> handler = PDFHandler(['a.pdf', 'b.pdf'])\n >>> handler.merge_pdfs('out.pdf')\n Merged PDFs saved at out.pdf\n \"\"\"",
"test_class": "TestPDFHandler",
"test_code": "class TestPDFHandler(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.test_files = [\"test1.pdf\", \"test2.pdf\"]\n cls.test_text = [\"This is a test1.\", \"This is a test2.\"]\n for i in range(2):\n c = canvas.Canvas(cls.test_files[i])\n c.drawString(100, 100, cls.test_text[i])\n c.showPage()\n c.save()\n\n @classmethod\n def tearDownClass(cls):\n for filename in cls.test_files:\n os.remove(filename)\n os.remove(\"merged.pdf\")",
"solution_code": "def merge_pdfs(self, output_filepath):\n pdf_writer = PyPDF2.PdfWriter()\n\n for reader in self.readers:\n # reader.getNumPages is deprecated and was removed in PyPDF2 3.0.0. Use len(reader.pages) instead.\n for page_num in range(len(reader.pages)):\n # reader.getPage(pageNumber) is deprecated and was removed in PyPDF2 3.0.0. Use reader.pages[page_number] instead.\n page = reader.pages[page_num]\n # addPage is deprecated and was removed in PyPDF2 3.0.0. Use add_page instead.\n pdf_writer.add_page(page)\n\n with open(output_filepath, 'wb') as out:\n pdf_writer.write(out)\n return f\"Merged PDFs saved at {output_filepath}\"",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"PyPDF2"
],
"field_dependencies": [
"self.readers"
],
"method_dependencies": []
}
},
{
"method_name": "extract_text_from_pdfs",
"method_description": "def extract_text_from_pdfs(self):\n \"\"\"\n Extract text from pdf files in self.readers\n :return pdf_texts: list of str, each element is the text of one pdf file\n >>> handler = PDFHandler(['a.pdf', 'b.pdf'])\n >>> handler.extract_text_from_pdfs()\n ['Test a.pdf', 'Test b.pdf']\n \"\"\"",
"test_class": "PDFHandlerTestMergePdfs",
"test_code": "class PDFHandlerTestMergePdfs(unittest.TestCase):\n def setUp(self) -> None:\n TestPDFHandler.setUpClass()\n\n def tearDown(self) -> None:\n TestPDFHandler.tearDownClass()\n\n def test_merge_pdfs(self):\n TestPDFHandler.setUpClass()\n handler = PDFHandler(TestPDFHandler.test_files)\n result = handler.merge_pdfs(\"merged.pdf\")\n self.assertEqual(\"Merged PDFs saved at merged.pdf\", result)\n self.assertTrue(os.path.exists(\"merged.pdf\"))",
"solution_code": "def extract_text_from_pdfs(self):\n pdf_texts = []\n for reader in self.readers:\n for page_num in range(len(reader.pages)):\n page = reader.pages[page_num]\n pdf_texts.append(page.extract_text())\n return pdf_texts",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.readers"
],
"method_dependencies": []
}
}
] | PDFHandler | [
"TestPDFHandler",
"PDFHandlerTestMergePdfs",
"PDFHandlerTestExtractTextFromPdfs",
"PDFHandlerTestMain"
] | class PDFHandler:
def __init__(self, filepaths):
"""
takes a list of file paths filepaths as a parameter.
It creates a list named readers using PyPDF2, where each reader opens a file from the given paths.
"""
self.filepaths = filepaths
self.readers = [PyPDF2.PdfFileReader(fp) for fp in filepaths]
| [
"self.filepaths",
"self.readers"
] |
ClassEval_70 | class PersonRequest:
"""
This class validates input personal information data and sets invalid fields to None based to specific rules.
"""
def __init__(self, name: str, sex: str, phoneNumber: str):
"""
Initialize PersonRequest object with the provided information.
:param name: str, the name of the person
:param sex: str, the sex of the person
:param phoneNumber: str, the phone number of the person
"""
self.name = self._validate_name(name)
self.sex = self._validate_sex(sex)
self.phoneNumber = self._validate_phoneNumber(phoneNumber)
def _validate_name(self, name: str) -> str:
"""
Validate the name and return it. If name is empty or exceeds 33 characters in length, set to None.
:param name: str, the name to validate
:return: str, the validated name or None if invalid
"""
def _validate_sex(self, sex: str) -> str:
"""
Validate the sex and return it. If sex is not Man, Woman, or UGM, set to None.
:param sex: str, the sex to validate
:return: str, the validated sex or None if invalid
"""
def _validate_phoneNumber(self, phoneNumber: str) -> str:
"""
Validate the phone number and return it. If phoneNumber is empty or not an 11 digit number, set to None.
:param phoneNumber: str, the phone number to validate
:return: str, the validated phone number or None if invalid
""" | import unittest
class PersonRequestTestValidateName(unittest.TestCase):
def test_validate_name_1(self):
pr = PersonRequest("", "Man", "12345678901")
self.assertIsNone(pr.name)
def test_validate_name_2(self):
pr = PersonRequest("This is a very long name that exceeds the character limit", "Man",
"12345678901")
self.assertIsNone(pr.name)
def test_validate_name_3(self):
pr = PersonRequest("aaa", "Man", "12345678901")
self.assertEqual(pr.name, 'aaa')
def test_validate_name_4(self):
pr = PersonRequest("bbb", "Man", "12345678901")
self.assertEqual(pr.name, 'bbb')
def test_validate_name_5(self):
pr = PersonRequest("ccc", "Man", "12345678901")
self.assertEqual(pr.name, 'ccc')
class PersonRequestTestValidateSex(unittest.TestCase):
def test_validate_sex_1(self):
pr = PersonRequest("John Doe", "Unknown", "12345678901")
self.assertIsNone(pr.sex)
def test_validate_sex_2(self):
pr = PersonRequest("John Doe", "UGM", "12345678901")
self.assertEqual(pr.sex, "UGM")
def test_validate_sex_3(self):
pr = PersonRequest("John Doe", "Man", "12345678901")
self.assertEqual(pr.sex, "Man")
def test_validate_sex_4(self):
pr = PersonRequest("John Doe", "Woman", "12345678901")
self.assertEqual(pr.sex, "Woman")
def test_validate_sex_5(self):
pr = PersonRequest("John Doe", "khsigy", "12345678901")
self.assertIsNone(pr.sex)
class PersonRequestTestValidatePhoneNumber(unittest.TestCase):
def test_validate_phoneNumber_1(self):
pr = PersonRequest("John Doe", "Man", "")
self.assertIsNone(pr.phoneNumber)
def test_validate_phoneNumber_2(self):
pr = PersonRequest("John Doe", "Man", "12345")
self.assertIsNone(pr.phoneNumber)
def test_validate_phoneNumber_3(self):
pr = PersonRequest("John Doe", "Man", "jgdjrj")
self.assertIsNone(pr.phoneNumber)
def test_validate_phoneNumber_4(self):
pr = PersonRequest("John Doe", "Man", "12345678901")
self.assertEqual(pr.phoneNumber, "12345678901")
def test_validate_phoneNumber_5(self):
pr = PersonRequest("John Doe", "Man", "11111111111")
self.assertEqual(pr.phoneNumber, "11111111111")
class PersonRequestTest(unittest.TestCase):
def test_PersonRequest(self):
pr = PersonRequest("", "Man", "12345678901")
self.assertIsNone(pr.name)
pr = PersonRequest("John Doe", "Unknown", "12345678901")
self.assertIsNone(pr.sex)
pr = PersonRequest("John Doe", "Man", "")
self.assertIsNone(pr.phoneNumber) | class PersonRequest:
def __init__(self, name: str, sex: str, phoneNumber: str):
self.name = self._validate_name(name)
self.sex = self._validate_sex(sex)
self.phoneNumber = self._validate_phoneNumber(phoneNumber)
def _validate_name(self, name: str) -> str:
if not name:
return None
if len(name) > 33:
return None
return name
def _validate_sex(self, sex: str) -> str:
if sex not in ["Man", "Woman", "UGM"]:
return None
return sex
def _validate_phoneNumber(self, phoneNumber: str) -> str:
if not phoneNumber:
return None
if len(phoneNumber) != 11 or not phoneNumber.isdigit():
return None
return phoneNumber | [] | """
This class validates input personal information data and sets invalid fields to None based to specific rules.
"""
| [
{
"method_name": "_validate_name",
"method_description": "def _validate_name(self, name: str) -> str:\n \"\"\"\n Validate the name and return it. If name is empty or exceeds 33 characters in length, set to None.\n :param name: str, the name to validate\n :return: str, the validated name or None if invalid\n \"\"\"",
"test_class": "PersonRequestTestValidateName",
"test_code": "class PersonRequestTestValidateName(unittest.TestCase):\n def test_validate_name_1(self):\n pr = PersonRequest(\"\", \"Man\", \"12345678901\")\n self.assertIsNone(pr.name)\n\n def test_validate_name_2(self):\n pr = PersonRequest(\"This is a very long name that exceeds the character limit\", \"Man\",\n \"12345678901\")\n self.assertIsNone(pr.name)\n\n def test_validate_name_3(self):\n pr = PersonRequest(\"aaa\", \"Man\", \"12345678901\")\n self.assertEqual(pr.name, 'aaa')\n\n def test_validate_name_4(self):\n pr = PersonRequest(\"bbb\", \"Man\", \"12345678901\")\n self.assertEqual(pr.name, 'bbb')\n\n def test_validate_name_5(self):\n pr = PersonRequest(\"ccc\", \"Man\", \"12345678901\")\n self.assertEqual(pr.name, 'ccc')",
"solution_code": "def _validate_name(self, name: str) -> str:\n if not name:\n return None\n if len(name) > 33:\n return None\n return name",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "_validate_sex",
"method_description": "def _validate_sex(self, sex: str) -> str:\n \"\"\"\n Validate the sex and return it. If sex is not Man, Woman, or UGM, set to None.\n :param sex: str, the sex to validate\n :return: str, the validated sex or None if invalid\n \"\"\"",
"test_class": "PersonRequestTestValidateSex",
"test_code": "class PersonRequestTestValidateSex(unittest.TestCase):\n def test_validate_sex_1(self):\n pr = PersonRequest(\"John Doe\", \"Unknown\", \"12345678901\")\n self.assertIsNone(pr.sex)\n\n def test_validate_sex_2(self):\n pr = PersonRequest(\"John Doe\", \"UGM\", \"12345678901\")\n self.assertEqual(pr.sex, \"UGM\")\n\n def test_validate_sex_3(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"12345678901\")\n self.assertEqual(pr.sex, \"Man\")\n\n def test_validate_sex_4(self):\n pr = PersonRequest(\"John Doe\", \"Woman\", \"12345678901\")\n self.assertEqual(pr.sex, \"Woman\")\n\n def test_validate_sex_5(self):\n pr = PersonRequest(\"John Doe\", \"khsigy\", \"12345678901\")\n self.assertIsNone(pr.sex)",
"solution_code": "def _validate_sex(self, sex: str) -> str:\n if sex not in [\"Man\", \"Woman\", \"UGM\"]:\n return None\n return sex",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "_validate_phoneNumber",
"method_description": "def _validate_phoneNumber(self, phoneNumber: str) -> str:\n \"\"\"\n Validate the phone number and return it. If phoneNumber is empty or not an 11 digit number, set to None.\n :param phoneNumber: str, the phone number to validate\n :return: str, the validated phone number or None if invalid\n \"\"\"",
"test_class": "PersonRequestTestValidatePhoneNumber",
"test_code": "class PersonRequestTestValidatePhoneNumber(unittest.TestCase):\n def test_validate_phoneNumber_1(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"\")\n self.assertIsNone(pr.phoneNumber)\n\n def test_validate_phoneNumber_2(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"12345\")\n self.assertIsNone(pr.phoneNumber)\n\n def test_validate_phoneNumber_3(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"jgdjrj\")\n self.assertIsNone(pr.phoneNumber)\n\n def test_validate_phoneNumber_4(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"12345678901\")\n self.assertEqual(pr.phoneNumber, \"12345678901\")\n\n def test_validate_phoneNumber_5(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"11111111111\")\n self.assertEqual(pr.phoneNumber, \"11111111111\")",
"solution_code": "def _validate_phoneNumber(self, phoneNumber: str) -> str:\n if not phoneNumber:\n return None\n if len(phoneNumber) != 11 or not phoneNumber.isdigit():\n return None\n return phoneNumber",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | PersonRequest | [
"PersonRequestTestValidateName",
"PersonRequestTestValidateSex",
"PersonRequestTestValidatePhoneNumber",
"PersonRequestTest"
] | class PersonRequest:
def __init__(self, name: str, sex: str, phoneNumber: str):
"""
Initialize PersonRequest object with the provided information.
:param name: str, the name of the person
:param sex: str, the sex of the person
:param phoneNumber: str, the phone number of the person
"""
self.name = self._validate_name(name)
self.sex = self._validate_sex(sex)
self.phoneNumber = self._validate_phoneNumber(phoneNumber)
| [
"self.name",
"self.phoneNumber",
"self.sex"
] |
ClassEval_71 | class PushBoxGame:
"""
This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win.
"""
def __init__(self, map):
"""
Initialize the push box game with the map and various attributes.
:param map: list[str], the map of the push box game, represented as a list of strings.
Each character on the map represents a different element, including the following:
- '#' represents a wall that neither the player nor the box can pass through;
- 'O' represents the initial position of the player;
- 'G' represents the target position;
- 'X' represents the initial position of the box.
>>> map = ["#####", "#O #", "# X #", "# G#", "#####"]
>>> game = PushBoxGame(map)
"""
self.map = map
self.player_row = 0
self.player_col = 0
self.targets = []
self.boxes = []
self.target_count = 0
self.is_game_over = False
self.init_game()
def init_game(self):
"""
Initialize the game by setting the positions of the player, targets, and boxes based on the map.
>>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"])
>>> game.targets
[(3, 3)]
>>> game.boxes
[(2, 2)]
>>> game.player_row
1
>>> game.player_col
1
"""
def check_win(self):
"""
Check if the game is won. The game is won when all the boxes are placed on target positions.
And update the value of self.is_game_over.
:return self.is_game_over: True if all the boxes are placed on target positions, or False otherwise.
>>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"])
>>> game.check_win()
"""
def move(self, direction):
"""
Move the player based on the specified direction and check if the game is won.
:param direction: str, the direction of the player's movement.
It can be 'w', 's', 'a', or 'd' representing up, down, left, or right respectively.
:return: True if the game is won, False otherwise.
>>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"])
>>> game.print_map()
# # # # #
# O #
# X #
# G #
# # # # #
>>> game.move('d')
False
>>> game.move('s')
False
>>> game.move('a')
False
>>> game.move('s')
False
>>> game.move('d')
True
""" | import unittest
class PushBoxGameTestInitGame(unittest.TestCase):
def setUp(self) -> None:
self.game_map = [
"#####",
"#O #",
"# X #",
"# G#",
"#####"
]
self.game = PushBoxGame(self.game_map)
def test_init_game_1(self):
self.assertEqual(self.game.map, self.game_map)
def test_init_game_2(self):
self.assertEqual(self.game.is_game_over, False)
def test_init_game_3(self):
self.assertEqual(self.game.player_col, 1)
def test_init_game_4(self):
self.assertEqual(self.game.player_row, 1)
def test_init_game_5(self):
self.assertEqual(self.game.targets, [(3, 3)])
def test_init_game_6(self):
self.assertEqual(self.game.boxes, [(2, 2)])
def test_init_game_7(self):
self.assertEqual(self.game.target_count, 1)
class PushBoxGameTestCheckWin(unittest.TestCase):
def setUp(self) -> None:
self.game_map = [
"#####",
"#O #",
"# X #",
"# G#",
"#####"
]
self.game = PushBoxGame(self.game_map)
def test_check_win_1(self):
self.assertFalse(self.game.check_win())
def test_check_win_2(self):
moves = ['d', 's', 'a', 's', 'd']
for move in moves:
self.game.move(move)
self.assertTrue(self.game.check_win())
class PushBoxGameTestMove(unittest.TestCase):
def setUp(self) -> None:
self.game_map = [
"#####",
"#O #",
"# X #",
"# G#",
"#####"
]
self.game = PushBoxGame(self.game_map)
def test_move_1(self):
moves = ['d', 's', 'a', 's']
for move in moves:
self.assertFalse(self.game.move(move))
self.assertTrue(self.game.move('d'))
def test_move_2(self):
self.game.move('a')
self.assertEqual(self.game.player_col, 1)
self.assertEqual(self.game.player_row, 1)
self.assertFalse(self.game.is_game_over)
def test_move_3(self):
self.game.move('d')
self.assertEqual(self.game.player_col, 2)
self.assertEqual(self.game.player_row, 1)
self.assertFalse(self.game.is_game_over)
def test_move_4(self):
self.game.move('s')
self.assertEqual(self.game.player_col, 1)
self.assertEqual(self.game.player_row, 2)
self.assertFalse(self.game.is_game_over)
def test_move_5(self):
self.game.move('w')
self.assertEqual(self.game.player_col, 1)
self.assertEqual(self.game.player_row, 1)
self.assertFalse(self.game.is_game_over)
def test_move_6(self):
self.game.move('?')
self.assertFalse(self.game.is_game_over)
def test_move_7(self):
self.game_map = [
"#####",
"# X #",
"# O #",
"# G#",
"#####"
]
self.game = PushBoxGame(self.game_map)
self.game.move('w')
self.assertEqual(self.game.player_col, 2)
self.assertEqual(self.game.player_row, 2)
self.assertFalse(self.game.is_game_over) | class PushBoxGame:
def __init__(self, map):
self.map = map
self.player_row = 0
self.player_col = 0
self.targets = []
self.boxes = []
self.target_count = 0
self.is_game_over = False
self.init_game()
def init_game(self):
for row in range(len(self.map)):
for col in range(len(self.map[row])):
if self.map[row][col] == "O":
self.player_row = row
self.player_col = col
elif self.map[row][col] == "G":
self.targets.append((row, col))
self.target_count += 1
elif self.map[row][col] == "X":
self.boxes.append((row, col))
def check_win(self):
box_on_target_count = 0
for box in self.boxes:
if box in self.targets:
box_on_target_count += 1
if box_on_target_count == self.target_count:
self.is_game_over = True
return self.is_game_over
def move(self, direction):
new_player_row = self.player_row
new_player_col = self.player_col
if direction == "w":
new_player_row -= 1
elif direction == "s":
new_player_row += 1
elif direction == "a":
new_player_col -= 1
elif direction == "d":
new_player_col += 1
if self.map[new_player_row][new_player_col] != "#":
if (new_player_row, new_player_col) in self.boxes:
new_box_row = new_player_row + (new_player_row - self.player_row)
new_box_col = new_player_col + (new_player_col - self.player_col)
if self.map[new_box_row][new_box_col] != "#":
self.boxes.remove((new_player_row, new_player_col))
self.boxes.append((new_box_row, new_box_col))
self.player_row = new_player_row
self.player_col = new_player_col
else:
self.player_row = new_player_row
self.player_col = new_player_col
return self.check_win() | [] | """
This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win.
"""
| [
{
"method_name": "init_game",
"method_description": "def init_game(self):\n \"\"\"\n Initialize the game by setting the positions of the player, targets, and boxes based on the map.\n >>> game = PushBoxGame([\"#####\", \"#O #\", \"# X #\", \"# G#\", \"#####\"]) \n >>> game.targets\n [(3, 3)]\n >>> game.boxes\n [(2, 2)]\n >>> game.player_row\n 1\n >>> game.player_col\n 1\n \"\"\"",
"test_class": "PushBoxGameTestInitGame",
"test_code": "class PushBoxGameTestInitGame(unittest.TestCase):\n def setUp(self) -> None:\n self.game_map = [\n \"#####\",\n \"#O #\",\n \"# X #\",\n \"# G#\",\n \"#####\"\n ]\n self.game = PushBoxGame(self.game_map)\n\n def test_init_game_1(self):\n self.assertEqual(self.game.map, self.game_map)\n\n def test_init_game_2(self):\n self.assertEqual(self.game.is_game_over, False)\n\n def test_init_game_3(self):\n self.assertEqual(self.game.player_col, 1)\n\n def test_init_game_4(self):\n self.assertEqual(self.game.player_row, 1)\n\n def test_init_game_5(self):\n self.assertEqual(self.game.targets, [(3, 3)])\n\n def test_init_game_6(self):\n self.assertEqual(self.game.boxes, [(2, 2)])\n\n def test_init_game_7(self):\n self.assertEqual(self.game.target_count, 1)",
"solution_code": "def init_game(self):\n for row in range(len(self.map)):\n for col in range(len(self.map[row])):\n if self.map[row][col] == \"O\":\n self.player_row = row\n self.player_col = col\n elif self.map[row][col] == \"G\":\n self.targets.append((row, col))\n self.target_count += 1\n elif self.map[row][col] == \"X\":\n self.boxes.append((row, col))",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.boxes",
"self.map",
"self.player_col",
"self.player_row",
"self.target_count",
"self.targets"
],
"method_dependencies": []
}
},
{
"method_name": "check_win",
"method_description": "def check_win(self):\n \"\"\"\n Check if the game is won. The game is won when all the boxes are placed on target positions.\n And update the value of self.is_game_over.\n :return self.is_game_over: True if all the boxes are placed on target positions, or False otherwise.\n >>> game = PushBoxGame([\"#####\", \"#O #\", \"# X #\", \"# G#\", \"#####\"]) \n >>> game.check_win()\n \"\"\"",
"test_class": "PushBoxGameTestCheckWin",
"test_code": "class PushBoxGameTestCheckWin(unittest.TestCase):\n def setUp(self) -> None:\n self.game_map = [\n \"#####\",\n \"#O #\",\n \"# X #\",\n \"# G#\",\n \"#####\"\n ]\n self.game = PushBoxGame(self.game_map)\n\n def test_check_win_1(self):\n self.assertFalse(self.game.check_win())\n\n def test_check_win_2(self):\n moves = ['d', 's', 'a', 's', 'd']\n for move in moves:\n self.game.move(move)\n self.assertTrue(self.game.check_win())",
"solution_code": "def check_win(self):\n box_on_target_count = 0\n for box in self.boxes:\n if box in self.targets:\n box_on_target_count += 1\n if box_on_target_count == self.target_count:\n self.is_game_over = True\n return self.is_game_over",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.boxes",
"self.is_game_over",
"self.target_count",
"self.targets"
],
"method_dependencies": []
}
},
{
"method_name": "move",
"method_description": "def move(self, direction):\n \"\"\"\n Move the player based on the specified direction and check if the game is won.\n :param direction: str, the direction of the player's movement. \n It can be 'w', 's', 'a', or 'd' representing up, down, left, or right respectively.\n\n :return: True if the game is won, False otherwise.\n >>> game = PushBoxGame([\"#####\", \"#O #\", \"# X #\", \"# G#\", \"#####\"]) \n >>> game.print_map()\n # # # # # \n # O #\n # X #\n # G #\n # # # # #\n >>> game.move('d')\n False\n >>> game.move('s') \n False\n >>> game.move('a') \n False\n >>> game.move('s') \n False\n >>> game.move('d') \n True\n \"\"\"",
"test_class": "PushBoxGameTestMove",
"test_code": "class PushBoxGameTestMove(unittest.TestCase):\n def setUp(self) -> None:\n self.game_map = [\n \"#####\",\n \"#O #\",\n \"# X #\",\n \"# G#\",\n \"#####\"\n ]\n self.game = PushBoxGame(self.game_map)\n\n def test_move_1(self):\n moves = ['d', 's', 'a', 's']\n for move in moves:\n self.assertFalse(self.game.move(move))\n self.assertTrue(self.game.move('d'))\n\n def test_move_2(self):\n self.game.move('a')\n self.assertEqual(self.game.player_col, 1)\n self.assertEqual(self.game.player_row, 1)\n self.assertFalse(self.game.is_game_over)\n\n def test_move_3(self):\n self.game.move('d')\n self.assertEqual(self.game.player_col, 2)\n self.assertEqual(self.game.player_row, 1)\n self.assertFalse(self.game.is_game_over)\n\n def test_move_4(self):\n self.game.move('s')\n self.assertEqual(self.game.player_col, 1)\n self.assertEqual(self.game.player_row, 2)\n self.assertFalse(self.game.is_game_over)\n\n def test_move_5(self):\n self.game.move('w')\n self.assertEqual(self.game.player_col, 1)\n self.assertEqual(self.game.player_row, 1)\n self.assertFalse(self.game.is_game_over)\n\n def test_move_6(self):\n self.game.move('?')\n self.assertFalse(self.game.is_game_over)\n\n def test_move_7(self):\n self.game_map = [\n \"#####\",\n \"# X #\",\n \"# O #\",\n \"# G#\",\n \"#####\"\n ]\n self.game = PushBoxGame(self.game_map)\n self.game.move('w')\n self.assertEqual(self.game.player_col, 2)\n self.assertEqual(self.game.player_row, 2)\n self.assertFalse(self.game.is_game_over)",
"solution_code": "def move(self, direction):\n new_player_row = self.player_row\n new_player_col = self.player_col\n\n if direction == \"w\":\n new_player_row -= 1\n elif direction == \"s\":\n new_player_row += 1\n elif direction == \"a\":\n new_player_col -= 1\n elif direction == \"d\":\n new_player_col += 1\n\n if self.map[new_player_row][new_player_col] != \"#\":\n if (new_player_row, new_player_col) in self.boxes:\n new_box_row = new_player_row + (new_player_row - self.player_row)\n new_box_col = new_player_col + (new_player_col - self.player_col)\n\n if self.map[new_box_row][new_box_col] != \"#\":\n self.boxes.remove((new_player_row, new_player_col))\n self.boxes.append((new_box_row, new_box_col))\n self.player_row = new_player_row\n self.player_col = new_player_col\n else:\n self.player_row = new_player_row\n self.player_col = new_player_col\n\n return self.check_win()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.boxes",
"self.map",
"self.player_col",
"self.player_row"
],
"method_dependencies": [
"check_win"
]
}
}
] | PushBoxGame | [
"PushBoxGameTestInitGame",
"PushBoxGameTestCheckWin",
"PushBoxGameTestMove"
] | class PushBoxGame:
def __init__(self, map):
"""
Initialize the push box game with the map and various attributes.
:param map: list[str], the map of the push box game, represented as a list of strings.
Each character on the map represents a different element, including the following:
- '#' represents a wall that neither the player nor the box can pass through;
- 'O' represents the initial position of the player;
- 'G' represents the target position;
- 'X' represents the initial position of the box.
>>> map = ["#####", "#O #", "# X #", "# G#", "#####"]
>>> game = PushBoxGame(map)
"""
self.map = map
self.player_row = 0
self.player_col = 0
self.targets = []
self.boxes = []
self.target_count = 0
self.is_game_over = False
self.init_game()
| [
"self.boxes",
"self.is_game_over",
"self.map",
"self.player_col",
"self.player_row",
"self.target_count",
"self.targets"
] |
ClassEval_72 | import re
class RegexUtils:
"""
The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses.
"""
def match(self, pattern, text):
"""
Check if the text matches the regular expression
:param pattern: string, Regular expression pattern
:param text: string, Text to match
:return: True or False, representing whether the text matches the regular expression or not
>>> ru = RegexUtils()
>>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890")
True
"""
def findall(self, pattern, text):
"""
Find all matching substrings and return a list of all matching substrings
:param pattern: string, Regular expression pattern
:param text: string, Text to match
:return: list of string, List of all matching substrings
>>> ru = RegexUtils()
>>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
['123-456-7890', '876-286-9876', '987-762-9767']
"""
def split(self, pattern, text):
"""
Split text based on regular expression patterns and return a list of substrings
:param pattern: string, Regular expression pattern
:param text: string, Text to be split
:return: list of string, List of substrings after splitting
>>> ru = RegexUtils()
>>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
['', ' abiguygusu ', ' kjgufwycs ', '']
"""
def sub(self, pattern, replacement, text):
"""
Replace the substring matched by a regular expression with the specified string
:param pattern: string, Regular expression pattern
:param replacement: Text to replace with
:param text: string, Text to be replaced
:return: string, Text after replacement
>>> ru = RegexUtils()
>>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
'phone num abiguygusu phone num kjgufwycs phone num'
"""
def generate_email_pattern(self):
"""
Generate regular expression patterns that match email addresses
:return: string, regular expression patterns that match email addresses
>>> ru = RegexUtils()
>>> ru.generate_email_pattern()
'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
"""
def generate_phone_number_pattern(self):
"""
Generate regular expression patterns that match phone numbers
:return: string, regular expression patterns that match phone numbers
>>> ru = RegexUtils()
>>> ru.generate_phone_number_pattern()
'\b\d{3}-\d{3}-\d{4}\b'
"""
def generate_split_sentences_pattern(self):
"""
Generate regular expression patterns that match the middle characters of two sentences
:return: string, regular expression patterns that match the middle characters of two sentences
>>> ru = RegexUtils()
>>> ru.generate_split_sentences_pattern()
'[.!?][\s]{1,2}(?=[A-Z])'
"""
def split_sentences(self, text):
"""
Split the text into a list of sentences without Punctuation except the last sentence
:param text: Text to be split
:return: Split Text List
>>> ru = RegexUtils()
>>> ru.split_sentences("Aaa. Bbbb? Ccc!")
['Aaa', 'Bbbb', 'Ccc!']
"""
def validate_phone_number(self, phone_number):
"""
Verify if the phone number is valid
:param phone_number: Phone number to be verified
:return: True or False, indicating whether the phone number is valid
>>> ru = RegexUtils()
>>> ru.validate_phone_number("123-456-7890")
True
"""
def extract_email(self, text):
"""
Extract all email addresses from the text
:param text: string, input text
:return: list of string, All extracted email addresses
>>> ru = RegexUtils()
>>> ru.extract_email("[email protected] [email protected] [email protected]")
['[email protected]', '[email protected]', '[email protected]']
""" | import unittest
class RegexUtilsTestMatch(unittest.TestCase):
def test_match_1(self):
ru = RegexUtils()
res = ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890")
self.assertEqual(res, True)
def test_match_2(self):
ru = RegexUtils()
res = ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "1234567890")
self.assertEqual(res, False)
def test_match_3(self):
ru = RegexUtils()
res = ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "111-111-1111")
self.assertEqual(res, True)
def test_match_4(self):
ru = RegexUtils()
res = ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-789")
self.assertEqual(res, False)
def test_match_5(self):
ru = RegexUtils()
res = ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-789a")
self.assertEqual(res, False)
class RegexUtilsTestFindall(unittest.TestCase):
def test_findall_1(self):
ru = RegexUtils()
res = ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
self.assertEqual(res, ['123-456-7890', '876-286-9876', '987-762-9767'])
def test_findall_2(self):
ru = RegexUtils()
res = ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "abiguygusu kjgufwycs 987-762-9767")
self.assertEqual(res, ['987-762-9767'])
def test_findall_3(self):
ru = RegexUtils()
res = ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "abiguygusu kjgufwycs ")
self.assertEqual(res, [])
def test_findall_4(self):
ru = RegexUtils()
res = ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "abiguygusu 111-111-1111 kjgufwycs 987-762-9767")
self.assertEqual(res, ['111-111-1111', '987-762-9767'])
def test_findall_5(self):
ru = RegexUtils()
res = ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "abiguygusu 111-111-111a kjgufwycs 987-762-9767")
self.assertEqual(res, ['987-762-9767'])
class RegexUtilsTestSplit(unittest.TestCase):
def test_split_1(self):
ru = RegexUtils()
res = ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
self.assertEqual(res, ['', ' abiguygusu ', ' kjgufwycs ', ''])
def test_split_2(self):
ru = RegexUtils()
res = ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "1234567890 abiguygusu 8762869876 kjgufwycs 9877629767")
self.assertEqual(res, ['1234567890 abiguygusu 8762869876 kjgufwycs 9877629767'])
def test_split_3(self):
ru = RegexUtils()
res = ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "111-111-1111 abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
self.assertEqual(res, ['', ' abiguygusu ', ' kjgufwycs ', ''])
def test_split_4(self):
ru = RegexUtils()
res = ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
self.assertEqual(res, ['123456-7890 abiguygusu ', ' kjgufwycs ', ''])
def test_split_5(self):
ru = RegexUtils()
res = ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-789a abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
self.assertEqual(res, ['123-456-789a abiguygusu ', ' kjgufwycs ', ''])
class RegexUtilsTestSub(unittest.TestCase):
def test_sub_1(self):
ru = RegexUtils()
res = ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num',
"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
self.assertEqual(res, 'phone num abiguygusu phone num kjgufwycs phone num')
def test_sub_2(self):
ru = RegexUtils()
res = ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num',
"1234567890 abiguygusu 8762869876 kjgufwycs 9877629767")
self.assertEqual(res, "1234567890 abiguygusu 8762869876 kjgufwycs 9877629767")
def test_sub_3(self):
ru = RegexUtils()
res = ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num',
"123456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
self.assertEqual(res, '123456-7890 abiguygusu phone num kjgufwycs phone num')
def test_sub_4(self):
ru = RegexUtils()
res = ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num',
"123-456-789a abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
self.assertEqual(res, '123-456-789a abiguygusu phone num kjgufwycs phone num')
def test_sub_5(self):
ru = RegexUtils()
res = ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num',
"123-456-780 abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
self.assertEqual(res, '123-456-780 abiguygusu phone num kjgufwycs phone num')
class RegexUtilsTestGenerateEmailPattern(unittest.TestCase):
def test_generate_email_pattern_1(self):
ru = RegexUtils()
pat = ru.generate_email_pattern()
res = ru.match(pat, '[email protected]')
self.assertEqual(res, True)
def test_generate_email_pattern_2(self):
ru = RegexUtils()
pat = ru.generate_email_pattern()
res = ru.match(pat, 'iustd87t2euhifg.com')
self.assertEqual(res, False)
def test_generate_email_pattern_3(self):
ru = RegexUtils()
pat = ru.generate_email_pattern()
res = ru.match(pat, '[email protected]')
self.assertEqual(res, False)
def test_generate_email_pattern_4(self):
ru = RegexUtils()
pat = ru.generate_email_pattern()
res = ru.match(pat, 'iustd87t2euhifg@.')
self.assertEqual(res, False)
def test_generate_email_pattern_5(self):
ru = RegexUtils()
pat = ru.generate_email_pattern()
res = ru.match(pat, 'iustd87t2euhifg@com.')
self.assertEqual(res, False)
class RegexUtilsTestGeneratePhoneNumberPattern(unittest.TestCase):
def test_generate_phone_number_pattern_1(self):
ru = RegexUtils()
pat = ru.generate_phone_number_pattern()
res = ru.match(pat, '123-456-7890')
self.assertEqual(res, True)
def test_generate_phone_number_pattern_2(self):
ru = RegexUtils()
pat = ru.generate_phone_number_pattern()
res = ru.match(pat, '1234567890')
self.assertEqual(res, False)
def test_generate_phone_number_pattern_3(self):
ru = RegexUtils()
pat = ru.generate_phone_number_pattern()
res = ru.match(pat, '123-456-789')
self.assertEqual(res, False)
def test_generate_phone_number_pattern_4(self):
ru = RegexUtils()
pat = ru.generate_phone_number_pattern()
res = ru.match(pat, 'a23-456-7890')
self.assertEqual(res, False)
def test_generate_phone_number_pattern_5(self):
ru = RegexUtils()
pat = ru.generate_phone_number_pattern()
res = ru.match(pat, '1234-56-7890')
self.assertEqual(res, False)
class RegexUtilsTestGenerateSplitSentencesPattern(unittest.TestCase):
def test_generate_split_sentences_pattern_1(self):
ru = RegexUtils()
pat = ru.generate_split_sentences_pattern()
res = ru.match(pat, '? Y')
self.assertEqual(res, True)
def test_generate_split_sentences_pattern_2(self):
ru = RegexUtils()
pat = ru.generate_split_sentences_pattern()
res = ru.match(pat, '! Y')
self.assertEqual(res, True)
def test_generate_split_sentences_pattern_3(self):
ru = RegexUtils()
pat = ru.generate_split_sentences_pattern()
res = ru.match(pat, '? ')
self.assertEqual(res, False)
def test_generate_split_sentences_pattern_4(self):
ru = RegexUtils()
pat = ru.generate_split_sentences_pattern()
res = ru.match(pat, '?Y')
self.assertEqual(res, False)
def test_generate_split_sentences_pattern_5(self):
ru = RegexUtils()
pat = ru.generate_split_sentences_pattern()
res = ru.match(pat, '.Y')
self.assertEqual(res, False)
class RegexUtilsTestSplitSentences(unittest.TestCase):
def test_split_sentences_1(self):
ru = RegexUtils()
res = ru.split_sentences("Aaa. Bbbb? Ccc!")
self.assertEqual(res, ['Aaa', 'Bbbb', 'Ccc!'])
def test_split_sentences_2(self):
ru = RegexUtils()
res = ru.split_sentences("Aaa.Bbbb? Ccc!")
self.assertEqual(res, ['Aaa.Bbbb', 'Ccc!'])
def test_split_sentences_3(self):
ru = RegexUtils()
res = ru.split_sentences("Aaa. bbbb? Ccc!")
self.assertEqual(res, ['Aaa. bbbb', 'Ccc!'])
def test_split_sentences_4(self):
ru = RegexUtils()
res = ru.split_sentences("Aaa. bbbb, Ccc!")
self.assertEqual(res, ['Aaa. bbbb, Ccc!'])
def test_split_sentences_5(self):
ru = RegexUtils()
res = ru.split_sentences("Aaa, Bbbb? Ccc!")
self.assertEqual(res, ['Aaa, Bbbb', 'Ccc!'])
class RegexUtilsTestValidatePhoneNumber(unittest.TestCase):
def test_validate_phone_number_1(self):
ru = RegexUtils()
res = ru.validate_phone_number("123-456-7890")
self.assertEqual(res, True)
def test_validate_phone_number_2(self):
ru = RegexUtils()
res = ru.validate_phone_number("1234567890")
self.assertEqual(res, False)
def test_validate_phone_number_3(self):
ru = RegexUtils()
res = ru.validate_phone_number("a23-456-7890")
self.assertEqual(res, False)
def test_validate_phone_number_4(self):
ru = RegexUtils()
res = ru.validate_phone_number("123-456-789")
self.assertEqual(res, False)
def test_validate_phone_number_5(self):
ru = RegexUtils()
res = ru.validate_phone_number("1234-56-789")
self.assertEqual(res, False)
class RegexUtilsTestExtractEmail(unittest.TestCase):
def test_extract_email_1(self):
ru = RegexUtils()
res = ru.extract_email("[email protected] [email protected] [email protected]")
self.assertEqual(res, ['[email protected]', '[email protected]', '[email protected]'])
def test_extract_email_2(self):
ru = RegexUtils()
res = ru.extract_email("[email protected] [email protected] [email protected]")
self.assertEqual(res, ['[email protected]', '[email protected]'])
def test_extract_email_3(self):
ru = RegexUtils()
res = ru.extract_email("abcdefgiscom [email protected] [email protected]")
self.assertEqual(res, ['[email protected]', '[email protected]'])
def test_extract_email_4(self):
ru = RegexUtils()
res = ru.extract_email("abcdefgiscom ygusyfysy126.com [email protected]")
self.assertEqual(res, ['[email protected]'])
def test_extract_email_5(self):
ru = RegexUtils()
res = ru.extract_email("abcdefgiscom [email protected] [email protected]")
self.assertEqual(res, ['[email protected]'])
class RegexUtilsTest(unittest.TestCase):
def test_regexutils(self):
ru = RegexUtils()
res = ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890")
self.assertEqual(res, True)
res = ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
self.assertEqual(res, ['123-456-7890', '876-286-9876', '987-762-9767'])
res = ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
self.assertEqual(res, ['', ' abiguygusu ', ' kjgufwycs ', ''])
res = ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num',
"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767")
self.assertEqual(res, 'phone num abiguygusu phone num kjgufwycs phone num')
pat = ru.generate_email_pattern()
res = ru.match(pat, '[email protected]')
self.assertEqual(res, True)
pat = ru.generate_phone_number_pattern()
res = ru.match(pat, '123-456-7890')
self.assertEqual(res, True)
pat = ru.generate_split_sentences_pattern()
res = ru.match(pat, '? Y')
self.assertEqual(res, True)
res = ru.split_sentences("Aaa. Bbbb? Ccc!")
self.assertEqual(res, ['Aaa', 'Bbbb', 'Ccc!'])
res = ru.validate_phone_number("123-456-7890")
self.assertEqual(res, True)
res = ru.extract_email("[email protected] [email protected] [email protected]")
self.assertEqual(res, ['[email protected]', '[email protected]', '[email protected]']) | import re
class RegexUtils:
def match(self, pattern, text):
ans = re.match(pattern, text)
if ans:
return True
else:
return False
def findall(self, pattern, text):
return re.findall(pattern, text)
def split(self, pattern, text):
return re.split(pattern, text)
def sub(self, pattern, replacement, text):
return re.sub(pattern, replacement, text)
def generate_email_pattern(self):
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
return pattern
def generate_phone_number_pattern(self):
pattern = r'\b\d{3}-\d{3}-\d{4}\b'
return pattern
def generate_split_sentences_pattern(self):
pattern = r'[.!?][\s]{1,2}(?=[A-Z])'
return pattern
def split_sentences(self, text):
pattern = self.generate_split_sentences_pattern()
return self.split(pattern, text)
def validate_phone_number(self, phone_number):
pattern = self.generate_phone_number_pattern()
return self.match(pattern, phone_number)
def extract_email(self, text):
pattern = self.generate_email_pattern()
return self.findall(pattern, text) | [
"import re"
] | """
The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses.
"""
| [
{
"method_name": "match",
"method_description": "def match(self, pattern, text):\n \"\"\"\n Check if the text matches the regular expression\n :param pattern: string, Regular expression pattern\n :param text: string, Text to match\n :return: True or False, representing whether the text matches the regular expression or not\n >>> ru = RegexUtils()\n >>> ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890\")\n True\n \"\"\"",
"test_class": "RegexUtilsTestMatch",
"test_code": "class RegexUtilsTestMatch(unittest.TestCase):\n def test_match_1(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890\")\n self.assertEqual(res, True)\n\n def test_match_2(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"1234567890\")\n self.assertEqual(res, False)\n\n def test_match_3(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"111-111-1111\")\n self.assertEqual(res, True)\n\n def test_match_4(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-789\")\n self.assertEqual(res, False)\n\n def test_match_5(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-789a\")\n self.assertEqual(res, False)",
"solution_code": "def match(self, pattern, text):\n ans = re.match(pattern, text)\n if ans:\n return True\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"re"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "findall",
"method_description": "def findall(self, pattern, text):\n \"\"\"\n Find all matching substrings and return a list of all matching substrings\n :param pattern: string, Regular expression pattern\n :param text: string, Text to match\n :return: list of string, List of all matching substrings\n >>> ru = RegexUtils()\n >>> ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n ['123-456-7890', '876-286-9876', '987-762-9767']\n \"\"\"",
"test_class": "RegexUtilsTestFindall",
"test_code": "class RegexUtilsTestFindall(unittest.TestCase):\n def test_findall_1(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['123-456-7890', '876-286-9876', '987-762-9767'])\n\n def test_findall_2(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"abiguygusu kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['987-762-9767'])\n\n def test_findall_3(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"abiguygusu kjgufwycs \")\n self.assertEqual(res, [])\n\n def test_findall_4(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"abiguygusu 111-111-1111 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['111-111-1111', '987-762-9767'])\n\n def test_findall_5(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"abiguygusu 111-111-111a kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['987-762-9767'])",
"solution_code": "def findall(self, pattern, text):\n return re.findall(pattern, text)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"re"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "split",
"method_description": "def split(self, pattern, text):\n \"\"\"\n Split text based on regular expression patterns and return a list of substrings\n :param pattern: string, Regular expression pattern\n :param text: string, Text to be split\n :return: list of string, List of substrings after splitting\n >>> ru = RegexUtils()\n >>> ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n ['', ' abiguygusu ', ' kjgufwycs ', '']\n \"\"\"",
"test_class": "RegexUtilsTestSplit",
"test_code": "class RegexUtilsTestSplit(unittest.TestCase):\n def test_split_1(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['', ' abiguygusu ', ' kjgufwycs ', ''])\n\n def test_split_2(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"1234567890 abiguygusu 8762869876 kjgufwycs 9877629767\")\n self.assertEqual(res, ['1234567890 abiguygusu 8762869876 kjgufwycs 9877629767'])\n\n def test_split_3(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"111-111-1111 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['', ' abiguygusu ', ' kjgufwycs ', ''])\n\n def test_split_4(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['123456-7890 abiguygusu ', ' kjgufwycs ', ''])\n\n def test_split_5(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-789a abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['123-456-789a abiguygusu ', ' kjgufwycs ', ''])",
"solution_code": "def split(self, pattern, text):\n return re.split(pattern, text)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"re"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "sub",
"method_description": "def sub(self, pattern, replacement, text):\n \"\"\"\n Replace the substring matched by a regular expression with the specified string\n :param pattern: string, Regular expression pattern\n :param replacement: Text to replace with\n :param text: string, Text to be replaced\n :return: string, Text after replacement\n >>> ru = RegexUtils()\n >>> ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n 'phone num abiguygusu phone num kjgufwycs phone num'\n \"\"\"",
"test_class": "RegexUtilsTestSub",
"test_code": "class RegexUtilsTestSub(unittest.TestCase):\n def test_sub_1(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, 'phone num abiguygusu phone num kjgufwycs phone num')\n\n def test_sub_2(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"1234567890 abiguygusu 8762869876 kjgufwycs 9877629767\")\n self.assertEqual(res, \"1234567890 abiguygusu 8762869876 kjgufwycs 9877629767\")\n\n def test_sub_3(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"123456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, '123456-7890 abiguygusu phone num kjgufwycs phone num')\n\n def test_sub_4(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"123-456-789a abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, '123-456-789a abiguygusu phone num kjgufwycs phone num')\n\n def test_sub_5(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"123-456-780 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, '123-456-780 abiguygusu phone num kjgufwycs phone num')",
"solution_code": "def sub(self, pattern, replacement, text):\n return re.sub(pattern, replacement, text)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"re"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "generate_email_pattern",
"method_description": "def generate_email_pattern(self):\n \"\"\"\n Generate regular expression patterns that match email addresses\n :return: string, regular expression patterns that match email addresses\n >>> ru = RegexUtils()\n >>> ru.generate_email_pattern()\n '\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'\n \"\"\"",
"test_class": "RegexUtilsTestGenerateEmailPattern",
"test_code": "class RegexUtilsTestGenerateEmailPattern(unittest.TestCase):\n def test_generate_email_pattern_1(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, '[email protected]')\n self.assertEqual(res, True)\n\n def test_generate_email_pattern_2(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euhifg.com')\n self.assertEqual(res, False)\n\n def test_generate_email_pattern_3(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, '[email protected]')\n self.assertEqual(res, False)\n\n def test_generate_email_pattern_4(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euhifg@.')\n self.assertEqual(res, False)\n\n def test_generate_email_pattern_5(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euhifg@com.')\n self.assertEqual(res, False)",
"solution_code": "def generate_email_pattern(self):\n pattern = r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'\n return pattern",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "generate_phone_number_pattern",
"method_description": "def generate_phone_number_pattern(self):\n \"\"\"\n Generate regular expression patterns that match phone numbers\n :return: string, regular expression patterns that match phone numbers\n >>> ru = RegexUtils()\n >>> ru.generate_phone_number_pattern()\n '\\b\\d{3}-\\d{3}-\\d{4}\\b'\n \"\"\"",
"test_class": "RegexUtilsTestGeneratePhoneNumberPattern",
"test_code": "class RegexUtilsTestGeneratePhoneNumberPattern(unittest.TestCase):\n def test_generate_phone_number_pattern_1(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, '123-456-7890')\n self.assertEqual(res, True)\n\n def test_generate_phone_number_pattern_2(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, '1234567890')\n self.assertEqual(res, False)\n\n def test_generate_phone_number_pattern_3(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, '123-456-789')\n self.assertEqual(res, False)\n\n def test_generate_phone_number_pattern_4(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, 'a23-456-7890')\n self.assertEqual(res, False)\n\n def test_generate_phone_number_pattern_5(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, '1234-56-7890')\n self.assertEqual(res, False)",
"solution_code": "def generate_phone_number_pattern(self):\n pattern = r'\\b\\d{3}-\\d{3}-\\d{4}\\b'\n return pattern",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "generate_split_sentences_pattern",
"method_description": "def generate_split_sentences_pattern(self):\n \"\"\"\n Generate regular expression patterns that match the middle characters of two sentences\n :return: string, regular expression patterns that match the middle characters of two sentences\n >>> ru = RegexUtils()\n >>> ru.generate_split_sentences_pattern()\n '[.!?][\\s]{1,2}(?=[A-Z])'\n \"\"\"",
"test_class": "RegexUtilsTestGenerateSplitSentencesPattern",
"test_code": "class RegexUtilsTestGenerateSplitSentencesPattern(unittest.TestCase):\n def test_generate_split_sentences_pattern_1(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '? Y')\n self.assertEqual(res, True)\n\n def test_generate_split_sentences_pattern_2(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '! Y')\n self.assertEqual(res, True)\n\n def test_generate_split_sentences_pattern_3(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '? ')\n self.assertEqual(res, False)\n\n def test_generate_split_sentences_pattern_4(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '?Y')\n self.assertEqual(res, False)\n\n def test_generate_split_sentences_pattern_5(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '.Y')\n self.assertEqual(res, False)",
"solution_code": "def generate_split_sentences_pattern(self):\n pattern = r'[.!?][\\s]{1,2}(?=[A-Z])'\n return pattern",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "split_sentences",
"method_description": "def split_sentences(self, text):\n \"\"\"\n Split the text into a list of sentences without Punctuation except the last sentence\n :param text: Text to be split\n :return: Split Text List\n >>> ru = RegexUtils()\n >>> ru.split_sentences(\"Aaa. Bbbb? Ccc!\")\n ['Aaa', 'Bbbb', 'Ccc!']\n \"\"\"",
"test_class": "RegexUtilsTestSplitSentences",
"test_code": "class RegexUtilsTestSplitSentences(unittest.TestCase):\n def test_split_sentences_1(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa. Bbbb? Ccc!\")\n self.assertEqual(res, ['Aaa', 'Bbbb', 'Ccc!'])\n\n def test_split_sentences_2(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa.Bbbb? Ccc!\")\n self.assertEqual(res, ['Aaa.Bbbb', 'Ccc!'])\n\n def test_split_sentences_3(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa. bbbb? Ccc!\")\n self.assertEqual(res, ['Aaa. bbbb', 'Ccc!'])\n\n def test_split_sentences_4(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa. bbbb, Ccc!\")\n self.assertEqual(res, ['Aaa. bbbb, Ccc!'])\n\n def test_split_sentences_5(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa, Bbbb? Ccc!\")\n self.assertEqual(res, ['Aaa, Bbbb', 'Ccc!'])",
"solution_code": "def split_sentences(self, text):\n pattern = self.generate_split_sentences_pattern()\n return self.split(pattern, text)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"split",
"generate_split_sentences_pattern"
]
}
},
{
"method_name": "validate_phone_number",
"method_description": "def validate_phone_number(self, phone_number):\n \"\"\"\n Verify if the phone number is valid\n :param phone_number: Phone number to be verified\n :return: True or False, indicating whether the phone number is valid\n >>> ru = RegexUtils()\n >>> ru.validate_phone_number(\"123-456-7890\")\n True\n \"\"\"",
"test_class": "RegexUtilsTestValidatePhoneNumber",
"test_code": "class RegexUtilsTestValidatePhoneNumber(unittest.TestCase):\n def test_validate_phone_number_1(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"123-456-7890\")\n self.assertEqual(res, True)\n\n def test_validate_phone_number_2(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"1234567890\")\n self.assertEqual(res, False)\n\n def test_validate_phone_number_3(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"a23-456-7890\")\n self.assertEqual(res, False)\n\n def test_validate_phone_number_4(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"123-456-789\")\n self.assertEqual(res, False)\n\n def test_validate_phone_number_5(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"1234-56-789\")\n self.assertEqual(res, False)",
"solution_code": "def validate_phone_number(self, phone_number):\n pattern = self.generate_phone_number_pattern()\n return self.match(pattern, phone_number)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"match",
"generate_phone_number_pattern"
]
}
},
{
"method_name": "extract_email",
"method_description": "def extract_email(self, text):\n \"\"\"\n Extract all email addresses from the text\n :param text: string, input text\n :return: list of string, All extracted email addresses\n >>> ru = RegexUtils()\n >>> ru.extract_email(\"[email protected] [email protected] [email protected]\")\n ['[email protected]', '[email protected]', '[email protected]']\n \"\"\"",
"test_class": "RegexUtilsTestExtractEmail",
"test_code": "class RegexUtilsTestExtractEmail(unittest.TestCase):\n def test_extract_email_1(self):\n ru = RegexUtils()\n res = ru.extract_email(\"[email protected] [email protected] [email protected]\")\n self.assertEqual(res, ['[email protected]', '[email protected]', '[email protected]'])\n\n def test_extract_email_2(self):\n ru = RegexUtils()\n res = ru.extract_email(\"[email protected] [email protected] [email protected]\")\n self.assertEqual(res, ['[email protected]', '[email protected]'])\n\n def test_extract_email_3(self):\n ru = RegexUtils()\n res = ru.extract_email(\"abcdefgiscom [email protected] [email protected]\")\n self.assertEqual(res, ['[email protected]', '[email protected]'])\n\n def test_extract_email_4(self):\n ru = RegexUtils()\n res = ru.extract_email(\"abcdefgiscom ygusyfysy126.com [email protected]\")\n self.assertEqual(res, ['[email protected]'])\n\n def test_extract_email_5(self):\n ru = RegexUtils()\n res = ru.extract_email(\"abcdefgiscom [email protected] [email protected]\")\n self.assertEqual(res, ['[email protected]'])",
"solution_code": "def extract_email(self, text):\n pattern = self.generate_email_pattern()\n return self.findall(pattern, text)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"findall",
"generate_email_pattern"
]
}
}
] | RegexUtils | [
"RegexUtilsTestMatch",
"RegexUtilsTestFindall",
"RegexUtilsTestSplit",
"RegexUtilsTestSub",
"RegexUtilsTestGenerateEmailPattern",
"RegexUtilsTestGeneratePhoneNumberPattern",
"RegexUtilsTestGenerateSplitSentencesPattern",
"RegexUtilsTestSplitSentences",
"RegexUtilsTestValidatePhoneNumber",
"RegexUtilsTestExtractEmail",
"RegexUtilsTest"
] | class RegexUtils:
| [] |
ClassEval_73 | class RPGCharacter:
"""
The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive.
"""
def __init__(self, name, hp, attack_power, defense, level=1):
"""
Initialize an RPG character object.
:param name: strm, the name of the character.
:param hp: int, The health points of the character.
:param attack_power: int, the attack power of the character.
:param defense: int, the defense points of the character.
:param level: int, the level of the character. Default is 1.
"""
self.name = name
self.hp = hp
self.attack_power = attack_power
self.defense = defense
self.level = level
self.exp = 0
def attack(self, other_character):
"""
Attack another character. The damage caused needs to offset the defense value.
:param other_character: str, The character being attacked.
>>> player_1 = RPGCharacter('player 1', 100, 10, 3)
>>> player_2 = RPGCharacter('player 2', 100, 7, 2)
>>> player_1.attack(player_2)
>>> player_2.hp
92
"""
def heal(self):
"""
Heal the character with 10 hp and the max hp is 100.
:return: int, the current health points after healing.
>>> player_1 = RPGCharacter('player 1', 93, 10, 3)
>>> player_1.heal()
100
"""
def gain_exp(self, amount):
"""
Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level
The experience that overflows should be used to calculate the next leve up untill exhausts
:param amount: int, the amount of experience points to gain.
>>> player_1 = RPGCharacter('player 1', 100, 10, 3)
>>> player_1.gain_exp(1100)
>>> player_1.exp
100
>>> player_1.level
5
"""
def level_up(self):
"""
Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points.
max level is 100
:return: tuple[int, int, int, int], the new level, health points, attack power, and defense points after leveling up.
>>> player_1 = RPGCharacter('player 1', 100, 10, 3)
>>> player_1.level_up()
(2, 120, 15, 8)
"""
def is_alive(self):
"""
Check if player is alive.
:return: True if the hp is larger than 0, or False otherwise.
>>> player_1 = RPGCharacter('player 1', 100, 10, 3)
>>> player_1.is_alive()
True
""" | import unittest
class RPGCharacterTestAttack(unittest.TestCase):
def test_attack(self):
character1 = RPGCharacter("John", 100, 20, 10)
character2 = RPGCharacter("Enemy", 100, 15, 5)
character1.attack(character2)
self.assertEqual(character2.hp, 85)
def test_attack_2(self):
character1 = RPGCharacter("John", 100, 20, 10)
character2 = RPGCharacter("Enemy", 100, 15, 5)
character2.attack(character1)
self.assertEqual(character1.hp, 95)
def test_attack_3(self):
character1 = RPGCharacter("John", 100, 20, 10)
character2 = RPGCharacter("Enemy", 100, 15, 5)
character1.attack(character2)
character2.attack(character1)
self.assertEqual(character1.hp, 95)
self.assertEqual(character2.hp, 85)
def test_attack_4(self):
character1 = RPGCharacter("John", 100, 20, 10)
character2 = RPGCharacter("Enemy", 100, 15, 5)
character1.attack(character2)
character1.attack(character2)
self.assertEqual(character2.hp, 70)
def test_attack_5(self):
character1 = RPGCharacter("John", 100, 20, 10)
character2 = RPGCharacter("Enemy", 100, 15, 5)
character1.attack(character2)
character1.attack(character2)
character1.attack(character2)
self.assertEqual(character2.hp, 55)
class RPGCharacterTestHeal(unittest.TestCase):
def test_heal_1(self):
character = RPGCharacter("John", 90, 20, 10)
character.heal()
self.assertEqual(character.hp, 100)
# overflow healing
def test_heal_2(self):
character = RPGCharacter("John", 97, 20, 10)
character.heal()
self.assertEqual(character.hp, 100)
def test_heal_3(self):
character = RPGCharacter("John", 100, 20, 10)
character.heal()
self.assertEqual(character.hp, 100)
def test_heal_4(self):
character = RPGCharacter("John", 100, 20, 10)
character.hp = 50
character.heal()
self.assertEqual(character.hp, 60)
def test_heal_5(self):
character = RPGCharacter("John", 100, 20, 10)
character.hp = 10
character.heal()
self.assertEqual(character.hp, 20)
class RPGCharacterTestGainExp(unittest.TestCase):
# exp not overflow
def test_gain_exp_1(self):
character = RPGCharacter("John", 100, 20, 10)
character.gain_exp(100)
self.assertEqual(character.level, 2)
self.assertEqual(character.exp, 0)
# exp overflow
def test_gain_exp_2(self):
character = RPGCharacter("John", 100, 20, 10)
character.gain_exp(1100)
self.assertEqual(character.level, 5)
self.assertEqual(character.exp, 100)
def test_gain_exp_3(self):
character = RPGCharacter("John", 100, 20, 10)
character.gain_exp(200)
self.assertEqual(character.level, 2)
self.assertEqual(character.exp, 100)
def test_gain_exp_4(self):
character = RPGCharacter("John", 100, 20, 10)
character.gain_exp(300)
self.assertEqual(character.level, 3)
self.assertEqual(character.exp, 0)
def test_gain_exp_5(self):
character = RPGCharacter("John", 100, 20, 10)
character.gain_exp(400)
self.assertEqual(character.level, 3)
self.assertEqual(character.exp, 100)
class RPGCharacterTestLevelUp(unittest.TestCase):
def test_level_up_1(self):
character = RPGCharacter("John", 100, 20, 10)
character.level_up()
self.assertEqual(character.level, 2)
self.assertEqual(character.exp, 0)
self.assertEqual(character.hp, 120)
self.assertEqual(character.attack_power, 25)
self.assertEqual(character.defense, 15)
# full level
def test_level_up_2(self):
character = RPGCharacter("John", 100, 20, 10, 100)
character.level_up()
self.assertEqual(character.level, 100)
self.assertEqual(character.exp, 0)
self.assertEqual(character.hp, 100)
self.assertEqual(character.attack_power, 20)
self.assertEqual(character.defense, 10)
def test_level_up_3(self):
character = RPGCharacter("John", 100, 20, 10, 2)
character.level_up()
self.assertEqual(character.level, 3)
self.assertEqual(character.exp, 0)
self.assertEqual(character.hp, 120)
self.assertEqual(character.attack_power, 25)
self.assertEqual(character.defense, 15)
def test_level_up_4(self):
character = RPGCharacter("John", 100, 20, 10, 3)
character.level_up()
self.assertEqual(character.level, 4)
self.assertEqual(character.exp, 0)
self.assertEqual(character.hp, 120)
self.assertEqual(character.attack_power, 25)
self.assertEqual(character.defense, 15)
def test_level_up_5(self):
character = RPGCharacter("John", 100, 20, 10, 4)
character.level_up()
self.assertEqual(character.level, 5)
self.assertEqual(character.exp, 0)
self.assertEqual(character.hp, 120)
self.assertEqual(character.attack_power, 25)
self.assertEqual(character.defense, 15)
class RPGCharacterTestIsAlive(unittest.TestCase):
def test_is_alive_1(self):
character = RPGCharacter("John", 100, 20, 10)
self.assertTrue(character.is_alive())
def test_is_alive_2(self):
character = RPGCharacter("John", 0, 20, 10)
self.assertFalse(character.is_alive())
def test_is_alive_3(self):
character = RPGCharacter("John", -10, 20, 10)
self.assertFalse(character.is_alive())
def test_is_alive_4(self):
character = RPGCharacter("John", 1, 20, 10)
self.assertTrue(character.is_alive())
def test_is_alive_5(self):
character = RPGCharacter("John", 10, 20, 10)
self.assertTrue(character.is_alive())
class RPGCharacterTestMain(unittest.TestCase):
def test_main(self):
character1 = RPGCharacter("John", 100, 20, 10)
character2 = RPGCharacter("Enemy", 100, 15, 5)
character1.attack(character2)
self.assertEqual(character2.hp, 85)
character2.heal()
self.assertEqual(character2.hp, 95)
character1.gain_exp(200)
self.assertEqual(character1.exp, 100)
self.assertEqual(character1.hp, 120)
self.assertEqual(character1.attack_power, 25)
self.assertEqual(character1.defense, 15)
self.assertTrue(character1.is_alive()) | class RPGCharacter:
def __init__(self, name, hp, attack_power, defense, level=1):
self.name = name
self.hp = hp
self.attack_power = attack_power
self.defense = defense
self.level = level
self.exp = 0
def attack(self, other_character):
damage = max(self.attack_power - other_character.defense, 1)
other_character.hp -= damage
def heal(self):
self.hp += 10
if self.hp > 100:
self.hp = 100
return self.hp
def gain_exp(self, amount):
while amount != 0:
if self.exp + amount >= self.level * 100:
amount -= (self.level * 100 - self.exp)
self.level_up()
else:
self.exp += amount
amount = 0
def level_up(self):
if self.level < 100:
self.level += 1
self.exp = 0
self.hp += 20
self.attack_power += 5
self.defense += 5
return self.level, self.hp, self.attack_power, self.defense
def is_alive(self):
return self.hp > 0 | [] | """
The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive.
"""
| [
{
"method_name": "attack",
"method_description": "def attack(self, other_character):\n \"\"\"\n Attack another character. The damage caused needs to offset the defense value.\n :param other_character: str, The character being attacked.\n >>> player_1 = RPGCharacter('player 1', 100, 10, 3)\n >>> player_2 = RPGCharacter('player 2', 100, 7, 2)\n >>> player_1.attack(player_2)\n >>> player_2.hp\n 92\n \"\"\"",
"test_class": "RPGCharacterTestAttack",
"test_code": "class RPGCharacterTestAttack(unittest.TestCase):\n def test_attack(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character1.attack(character2)\n self.assertEqual(character2.hp, 85)\n\n def test_attack_2(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character2.attack(character1)\n self.assertEqual(character1.hp, 95)\n\n def test_attack_3(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character1.attack(character2)\n character2.attack(character1)\n self.assertEqual(character1.hp, 95)\n self.assertEqual(character2.hp, 85)\n\n def test_attack_4(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character1.attack(character2)\n character1.attack(character2)\n self.assertEqual(character2.hp, 70)\n\n def test_attack_5(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character1.attack(character2)\n character1.attack(character2)\n character1.attack(character2)\n self.assertEqual(character2.hp, 55)",
"solution_code": "def attack(self, other_character):\n damage = max(self.attack_power - other_character.defense, 1)\n other_character.hp -= damage",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.attack_power"
],
"method_dependencies": []
}
},
{
"method_name": "heal",
"method_description": "def heal(self):\n \"\"\"\n Heal the character with 10 hp and the max hp is 100.\n :return: int, the current health points after healing.\n >>> player_1 = RPGCharacter('player 1', 93, 10, 3)\n >>> player_1.heal()\n 100\n \"\"\"",
"test_class": "RPGCharacterTestHeal",
"test_code": "class RPGCharacterTestHeal(unittest.TestCase):\n def test_heal_1(self):\n character = RPGCharacter(\"John\", 90, 20, 10)\n character.heal()\n self.assertEqual(character.hp, 100)\n\n # overflow healing \n def test_heal_2(self):\n character = RPGCharacter(\"John\", 97, 20, 10)\n character.heal()\n self.assertEqual(character.hp, 100)\n\n def test_heal_3(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.heal()\n self.assertEqual(character.hp, 100)\n\n def test_heal_4(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.hp = 50\n character.heal()\n self.assertEqual(character.hp, 60)\n\n def test_heal_5(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.hp = 10\n character.heal()\n self.assertEqual(character.hp, 20)",
"solution_code": "def heal(self):\n self.hp += 10\n if self.hp > 100:\n self.hp = 100\n return self.hp",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.hp"
],
"method_dependencies": []
}
},
{
"method_name": "gain_exp",
"method_description": "def gain_exp(self, amount):\n \"\"\"\n Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level\n The experience that overflows should be used to calculate the next leve up untill exhausts\n :param amount: int, the amount of experience points to gain.\n >>> player_1 = RPGCharacter('player 1', 100, 10, 3)\n >>> player_1.gain_exp(1100)\n >>> player_1.exp\n 100\n >>> player_1.level\n 5\n \"\"\"",
"test_class": "RPGCharacterTestGainExp",
"test_code": "class RPGCharacterTestGainExp(unittest.TestCase):\n\n # exp not overflow\n def test_gain_exp_1(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(100)\n self.assertEqual(character.level, 2)\n self.assertEqual(character.exp, 0)\n\n # exp overflow\n def test_gain_exp_2(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(1100)\n self.assertEqual(character.level, 5)\n self.assertEqual(character.exp, 100)\n\n def test_gain_exp_3(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(200)\n self.assertEqual(character.level, 2)\n self.assertEqual(character.exp, 100)\n\n def test_gain_exp_4(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(300)\n self.assertEqual(character.level, 3)\n self.assertEqual(character.exp, 0)\n\n def test_gain_exp_5(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(400)\n self.assertEqual(character.level, 3)\n self.assertEqual(character.exp, 100)",
"solution_code": "def gain_exp(self, amount):\n while amount != 0:\n if self.exp + amount >= self.level * 100:\n amount -= (self.level * 100 - self.exp)\n self.level_up()\n else:\n self.exp += amount\n amount = 0",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.exp",
"self.level"
],
"method_dependencies": [
"level_up"
]
}
},
{
"method_name": "level_up",
"method_description": "def level_up(self):\n \"\"\"\n Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points.\n max level is 100\n :return: tuple[int, int, int, int], the new level, health points, attack power, and defense points after leveling up.\n >>> player_1 = RPGCharacter('player 1', 100, 10, 3)\n >>> player_1.level_up()\n (2, 120, 15, 8)\n \"\"\"",
"test_class": "RPGCharacterTestLevelUp",
"test_code": "class RPGCharacterTestLevelUp(unittest.TestCase):\n def test_level_up_1(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.level_up()\n self.assertEqual(character.level, 2)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 120)\n self.assertEqual(character.attack_power, 25)\n self.assertEqual(character.defense, 15)\n\n # full level\n def test_level_up_2(self):\n character = RPGCharacter(\"John\", 100, 20, 10, 100)\n character.level_up()\n self.assertEqual(character.level, 100)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 100)\n self.assertEqual(character.attack_power, 20)\n self.assertEqual(character.defense, 10)\n\n def test_level_up_3(self):\n character = RPGCharacter(\"John\", 100, 20, 10, 2)\n character.level_up()\n self.assertEqual(character.level, 3)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 120)\n self.assertEqual(character.attack_power, 25)\n self.assertEqual(character.defense, 15)\n\n def test_level_up_4(self):\n character = RPGCharacter(\"John\", 100, 20, 10, 3)\n character.level_up()\n self.assertEqual(character.level, 4)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 120)\n self.assertEqual(character.attack_power, 25)\n self.assertEqual(character.defense, 15)\n\n def test_level_up_5(self):\n character = RPGCharacter(\"John\", 100, 20, 10, 4)\n character.level_up()\n self.assertEqual(character.level, 5)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 120)\n self.assertEqual(character.attack_power, 25)\n self.assertEqual(character.defense, 15)",
"solution_code": "def level_up(self):\n if self.level < 100:\n self.level += 1\n self.exp = 0\n self.hp += 20\n self.attack_power += 5\n self.defense += 5\n return self.level, self.hp, self.attack_power, self.defense",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.attack_power",
"self.defense",
"self.exp",
"self.hp",
"self.level"
],
"method_dependencies": [
"attack"
]
}
},
{
"method_name": "is_alive",
"method_description": "def is_alive(self):\n \"\"\"\n Check if player is alive.\n :return: True if the hp is larger than 0, or False otherwise.\n >>> player_1 = RPGCharacter('player 1', 100, 10, 3)\n >>> player_1.is_alive()\n True\n \"\"\"",
"test_class": "RPGCharacterTestIsAlive",
"test_code": "class RPGCharacterTestIsAlive(unittest.TestCase):\n def test_is_alive_1(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n self.assertTrue(character.is_alive())\n\n def test_is_alive_2(self):\n character = RPGCharacter(\"John\", 0, 20, 10)\n self.assertFalse(character.is_alive())\n\n def test_is_alive_3(self):\n character = RPGCharacter(\"John\", -10, 20, 10)\n self.assertFalse(character.is_alive())\n\n def test_is_alive_4(self):\n character = RPGCharacter(\"John\", 1, 20, 10)\n self.assertTrue(character.is_alive())\n\n def test_is_alive_5(self):\n character = RPGCharacter(\"John\", 10, 20, 10)\n self.assertTrue(character.is_alive())",
"solution_code": "def is_alive(self):\n return self.hp > 0",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.hp"
],
"method_dependencies": []
}
}
] | RPGCharacter | [
"RPGCharacterTestAttack",
"RPGCharacterTestHeal",
"RPGCharacterTestGainExp",
"RPGCharacterTestLevelUp",
"RPGCharacterTestIsAlive",
"RPGCharacterTestMain"
] | class RPGCharacter:
def __init__(self, name, hp, attack_power, defense, level=1):
"""
Initialize an RPG character object.
:param name: strm, the name of the character.
:param hp: int, The health points of the character.
:param attack_power: int, the attack power of the character.
:param defense: int, the defense points of the character.
:param level: int, the level of the character. Default is 1.
"""
self.name = name
self.hp = hp
self.attack_power = attack_power
self.defense = defense
self.level = level
self.exp = 0
| [
"self.attack_power",
"self.defense",
"self.exp",
"self.hp",
"self.level",
"self.name"
] |
ClassEval_74 | class Server:
"""
This is a class as a server, which handles a white list, message sending and receiving, and information display.
"""
def __init__(self):
"""
Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary
"""
self.white_list = []
self.send_struct = {}
self.receive_struct = {}
def add_white_list(self, addr):
"""
Add an address to the whitelist and do nothing if it already exists
:param addr: int, address to be added
:return: new whitelist, return False if the address already exists
>>> server = Server()
>>> server.add_white_list(88)
[88]
"""
def del_white_list(self, addr):
"""
Remove an address from the whitelist and do nothing if it does not exist
:param addr: int, address to be deleted
:return: new whitelist, return False if the address does not exist
>>> server.add_white_list(88)
>>> server.del_white_list(88)
[]
"""
def recv(self, info):
"""
Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it
:param info: dict, information dictionary containing address and content
:return: if successfully received, return the content of the infomation; otherwise, return False
>>> server.recv({"addr":88,"content":"abc"})
abc
"""
def send(self, info):
"""
Send information containing address and content
:param info: dict, information dictionary containing address and content
:return: if successfully sent, return nothing; otherwise, return a string indicating an error message
>>> server.send({"addr":66,"content":"ABC"})
self.send_struct = {"addr":66,"content":"ABC"}
"""
def show(self, type):
"""
Returns struct of the specified type
:param type: string, the type of struct to be returned, which can be 'send' or 'receive'
:return: if type is equal to 'send' or 'receive', return the corresponding struct; otherwise, return False
>>> server.recv({"addr":88,"content":"abc"})
>>> server.send({"addr":66,"content":"ABC"})
>>> server.show("send")
{"addr":66,"content":"ABC"}
""" | import unittest
class ServerTestAddWhiteList(unittest.TestCase):
def test_add_white_list_1(self):
server = Server()
server.add_white_list(88)
self.assertEqual(server.white_list, [88])
def test_add_white_list_2(self):
server = Server()
server.add_white_list(88)
self.assertEqual(server.add_white_list(88), False)
def test_add_white_list_3(self):
server = Server()
server.add_white_list(88)
server.add_white_list(11)
self.assertEqual(server.add_white_list(11), False)
def test_add_white_list_4(self):
server = Server()
server.add_white_list(11)
self.assertEqual(server.white_list, [11])
def test_add_white_list_5(self):
server = Server()
server.add_white_list(88)
server.add_white_list(11)
server.add_white_list(22)
self.assertEqual(server.add_white_list(22), False)
class ServerTestDelWhiteList(unittest.TestCase):
def test_del_white_list_1(self):
server = Server()
server.add_white_list(88)
server.del_white_list(88)
self.assertEqual(server.white_list, [])
def test_del_white_list_2(self):
server = Server()
self.assertEqual(server.del_white_list(88), False)
def test_del_white_list_3(self):
server = Server()
self.assertEqual(server.del_white_list(11), False)
def test_del_white_list_4(self):
server = Server()
self.assertEqual(server.del_white_list(22), False)
def test_del_white_list_5(self):
server = Server()
server.add_white_list(11)
self.assertEqual(server.del_white_list(22), False)
class ServerTestRecv(unittest.TestCase):
def test_recv_1(self):
server = Server()
server.add_white_list(88)
server.recv({"addr": 88, "content": "abc"})
self.assertEqual(server.receive_struct, {"addr": 88, "content": "abc"})
def test_recv_2(self):
server = Server()
server.add_white_list(88)
flag = server.recv({"addr": 66, "content": "abc"})
self.assertEqual(server.receive_struct, {})
self.assertEqual(flag, False)
def test_recv_3(self):
server = Server()
flag = server.recv([88])
self.assertEqual(server.receive_struct, {})
self.assertEqual(flag, -1)
def test_recv_4(self):
server = Server()
flag = server.recv({"addr": 88})
self.assertEqual(server.receive_struct, {})
self.assertEqual(flag, -1)
def test_recv_5(self):
server = Server()
flag = server.recv({"content": "abc"})
self.assertEqual(server.receive_struct, {})
self.assertEqual(flag, -1)
class ServerTestSend(unittest.TestCase):
def test_send_1(self):
server = Server()
server.send({"addr": 88, "content": "abc"})
self.assertEqual(server.send_struct, {"addr": 88, "content": "abc"})
def test_send_2(self):
server = Server()
flag = server.send({"addr": 88})
self.assertEqual(flag, "info structure is not correct")
def test_send_3(self):
server = Server()
flag = server.send({"content": "abc"})
self.assertEqual(flag, "info structure is not correct")
def test_send_4(self):
server = Server()
flag = server.send([])
self.assertEqual(flag, "info structure is not correct")
def test_send_5(self):
server = Server()
server.send({"addr": 66, "content": "abc"})
self.assertEqual(server.send_struct, {"addr": 66, "content": "abc"})
class ServerTestShow(unittest.TestCase):
def test_show_1(self):
server = Server()
server.add_white_list(66)
server.send({"addr": 88, "content": "abc"})
server.recv({"addr": 66, "content": "ABC"})
self.assertEqual(server.show("send"), {"addr": 88, "content": "abc"})
def test_show_2(self):
server = Server()
server.add_white_list(66)
server.send({"addr": 88, "content": "abc"})
server.recv({"addr": 66, "content": "ABC"})
self.assertEqual(server.show("receive"), {"addr": 66, "content": "ABC"})
def test_show_3(self):
server = Server()
server.add_white_list(66)
server.send({"addr": 88, "content": "abc"})
server.recv({"addr": 66, "content": "ABC"})
self.assertEqual(server.show("abcdefg"), False)
def test_show_4(self):
server = Server()
server.add_white_list(66)
server.send({"addr": 11, "content": "abc"})
server.recv({"addr": 66, "content": "ABC"})
self.assertEqual(server.show("send"), {"addr": 11, "content": "abc"})
def test_show_5(self):
server = Server()
server.add_white_list(66)
server.send({"addr": 22, "content": "abc"})
server.recv({"addr": 66, "content": "ABC"})
self.assertEqual(server.show("send"), {"addr": 22, "content": "abc"})
class ServerTest(unittest.TestCase):
def test_server(self):
server = Server()
server.add_white_list(88)
self.assertEqual(server.white_list, [88])
server.del_white_list(88)
self.assertEqual(server.white_list, [])
server.add_white_list(88)
server.recv({"addr": 88, "content": "abc"})
self.assertEqual(server.receive_struct, {"addr": 88, "content": "abc"})
server.send({"addr": 66, "content": "ABC"})
self.assertEqual(server.send_struct, {"addr": 66, "content": "ABC"})
server.recv({"addr": 88, "content": "abc"})
self.assertEqual(server.show("receive"), {"addr": 88, "content": "abc"}) | class Server:
def __init__(self):
self.white_list = []
self.send_struct = {}
self.receive_struct = {}
def add_white_list(self, addr):
if addr in self.white_list:
return False
else:
self.white_list.append(addr)
return self.white_list
def del_white_list(self, addr):
if addr not in self.white_list:
return False
else:
self.white_list.remove(addr)
return self.white_list
def recv(self, info):
if not isinstance(info, dict) or "addr" not in info or "content" not in info:
return -1
addr = info["addr"]
content = info["content"]
if addr not in self.white_list:
return False
else:
self.receive_struct = {"addr": addr, "content": content}
return self.receive_struct["content"]
def send(self, info):
if not isinstance(info, dict) or "addr" not in info or "content" not in info:
return "info structure is not correct"
self.send_struct = {"addr": info["addr"], "content": info["content"]}
def show(self, type):
if type == "send":
return self.send_struct
elif type == "receive":
return self.receive_struct
else:
return False | [] | """
This is a class as a server, which handles a white list, message sending and receiving, and information display.
"""
| [
{
"method_name": "add_white_list",
"method_description": "def add_white_list(self, addr):\n \"\"\"\n Add an address to the whitelist and do nothing if it already exists\n :param addr: int, address to be added\n :return: new whitelist, return False if the address already exists\n >>> server = Server()\n >>> server.add_white_list(88)\n [88]\n \"\"\"",
"test_class": "ServerTestAddWhiteList",
"test_code": "class ServerTestAddWhiteList(unittest.TestCase):\n def test_add_white_list_1(self):\n server = Server()\n server.add_white_list(88)\n self.assertEqual(server.white_list, [88])\n\n def test_add_white_list_2(self):\n server = Server()\n server.add_white_list(88)\n self.assertEqual(server.add_white_list(88), False)\n\n def test_add_white_list_3(self):\n server = Server()\n server.add_white_list(88)\n server.add_white_list(11)\n self.assertEqual(server.add_white_list(11), False)\n\n def test_add_white_list_4(self):\n server = Server()\n server.add_white_list(11)\n self.assertEqual(server.white_list, [11])\n\n def test_add_white_list_5(self):\n server = Server()\n server.add_white_list(88)\n server.add_white_list(11)\n server.add_white_list(22)\n self.assertEqual(server.add_white_list(22), False)",
"solution_code": "def add_white_list(self, addr):\n if addr in self.white_list:\n return False\n else:\n self.white_list.append(addr)\n return self.white_list",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.white_list"
],
"method_dependencies": []
}
},
{
"method_name": "del_white_list",
"method_description": "def del_white_list(self, addr):\n \"\"\"\n Remove an address from the whitelist and do nothing if it does not exist\n :param addr: int, address to be deleted\n :return: new whitelist, return False if the address does not exist\n >>> server.add_white_list(88)\n >>> server.del_white_list(88)\n []\n \"\"\"",
"test_class": "ServerTestDelWhiteList",
"test_code": "class ServerTestDelWhiteList(unittest.TestCase):\n def test_del_white_list_1(self):\n server = Server()\n server.add_white_list(88)\n server.del_white_list(88)\n self.assertEqual(server.white_list, [])\n\n def test_del_white_list_2(self):\n server = Server()\n self.assertEqual(server.del_white_list(88), False)\n\n def test_del_white_list_3(self):\n server = Server()\n self.assertEqual(server.del_white_list(11), False)\n\n def test_del_white_list_4(self):\n server = Server()\n self.assertEqual(server.del_white_list(22), False)\n\n def test_del_white_list_5(self):\n server = Server()\n server.add_white_list(11)\n self.assertEqual(server.del_white_list(22), False)",
"solution_code": "def del_white_list(self, addr):\n if addr not in self.white_list:\n return False\n else:\n self.white_list.remove(addr)\n return self.white_list",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.white_list"
],
"method_dependencies": []
}
},
{
"method_name": "recv",
"method_description": "def recv(self, info):\n \"\"\"\n Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it\n :param info: dict, information dictionary containing address and content\n :return: if successfully received, return the content of the infomation; otherwise, return False\n >>> server.recv({\"addr\":88,\"content\":\"abc\"})\n abc\n \"\"\"",
"test_class": "ServerTestRecv",
"test_code": "class ServerTestRecv(unittest.TestCase):\n def test_recv_1(self):\n server = Server()\n server.add_white_list(88)\n server.recv({\"addr\": 88, \"content\": \"abc\"})\n self.assertEqual(server.receive_struct, {\"addr\": 88, \"content\": \"abc\"})\n\n def test_recv_2(self):\n server = Server()\n server.add_white_list(88)\n flag = server.recv({\"addr\": 66, \"content\": \"abc\"})\n self.assertEqual(server.receive_struct, {})\n self.assertEqual(flag, False)\n\n def test_recv_3(self):\n server = Server()\n flag = server.recv([88])\n self.assertEqual(server.receive_struct, {})\n self.assertEqual(flag, -1)\n\n def test_recv_4(self):\n server = Server()\n flag = server.recv({\"addr\": 88})\n self.assertEqual(server.receive_struct, {})\n self.assertEqual(flag, -1)\n\n def test_recv_5(self):\n server = Server()\n flag = server.recv({\"content\": \"abc\"})\n self.assertEqual(server.receive_struct, {})\n self.assertEqual(flag, -1)",
"solution_code": "def recv(self, info):\n if not isinstance(info, dict) or \"addr\" not in info or \"content\" not in info:\n return -1\n addr = info[\"addr\"]\n content = info[\"content\"]\n if addr not in self.white_list:\n return False\n else:\n self.receive_struct = {\"addr\": addr, \"content\": content}\n return self.receive_struct[\"content\"]",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.receive_struct",
"self.white_list"
],
"method_dependencies": []
}
},
{
"method_name": "send",
"method_description": "def send(self, info):\n \"\"\"\n Send information containing address and content\n :param info: dict, information dictionary containing address and content\n :return: if successfully sent, return nothing; otherwise, return a string indicating an error message\n >>> server.send({\"addr\":66,\"content\":\"ABC\"})\n self.send_struct = {\"addr\":66,\"content\":\"ABC\"}\n \"\"\"",
"test_class": "ServerTestSend",
"test_code": "class ServerTestSend(unittest.TestCase):\n def test_send_1(self):\n server = Server()\n server.send({\"addr\": 88, \"content\": \"abc\"})\n self.assertEqual(server.send_struct, {\"addr\": 88, \"content\": \"abc\"})\n\n def test_send_2(self):\n server = Server()\n flag = server.send({\"addr\": 88})\n self.assertEqual(flag, \"info structure is not correct\")\n\n def test_send_3(self):\n server = Server()\n flag = server.send({\"content\": \"abc\"})\n self.assertEqual(flag, \"info structure is not correct\")\n\n def test_send_4(self):\n server = Server()\n flag = server.send([])\n self.assertEqual(flag, \"info structure is not correct\")\n\n def test_send_5(self):\n server = Server()\n server.send({\"addr\": 66, \"content\": \"abc\"})\n self.assertEqual(server.send_struct, {\"addr\": 66, \"content\": \"abc\"})",
"solution_code": "def send(self, info):\n if not isinstance(info, dict) or \"addr\" not in info or \"content\" not in info:\n return \"info structure is not correct\"\n self.send_struct = {\"addr\": info[\"addr\"], \"content\": info[\"content\"]}",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.send_struct"
],
"method_dependencies": []
}
},
{
"method_name": "show",
"method_description": "def show(self, type):\n \"\"\"\n Returns struct of the specified type\n :param type: string, the type of struct to be returned, which can be 'send' or 'receive'\n :return: if type is equal to 'send' or 'receive', return the corresponding struct; otherwise, return False\n >>> server.recv({\"addr\":88,\"content\":\"abc\"})\n >>> server.send({\"addr\":66,\"content\":\"ABC\"})\n >>> server.show(\"send\")\n {\"addr\":66,\"content\":\"ABC\"}\n \"\"\"",
"test_class": "ServerTestShow",
"test_code": "class ServerTestShow(unittest.TestCase):\n def test_show_1(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 88, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"send\"), {\"addr\": 88, \"content\": \"abc\"})\n\n def test_show_2(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 88, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"receive\"), {\"addr\": 66, \"content\": \"ABC\"})\n\n def test_show_3(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 88, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"abcdefg\"), False)\n\n def test_show_4(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 11, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"send\"), {\"addr\": 11, \"content\": \"abc\"})\n\n def test_show_5(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 22, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"send\"), {\"addr\": 22, \"content\": \"abc\"})",
"solution_code": "def show(self, type):\n if type == \"send\":\n return self.send_struct\n elif type == \"receive\":\n return self.receive_struct\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.receive_struct",
"self.send_struct"
],
"method_dependencies": [
"send"
]
}
}
] | Server | [
"ServerTestAddWhiteList",
"ServerTestDelWhiteList",
"ServerTestRecv",
"ServerTestSend",
"ServerTestShow",
"ServerTest"
] | class Server:
def __init__(self):
"""
Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary
"""
self.white_list = []
self.send_struct = {}
self.receive_struct = {}
| [
"self.receive_struct",
"self.send_struct",
"self.white_list"
] |
ClassEval_75 | class ShoppingCart:
"""
The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price.
"""
def __init__(self):
"""
Initialize the items representing the shopping list as an empty dictionary
"""
self.items = {}
def add_item(self, item, price, quantity=1):
"""
Add item information to the shopping list items, including price and quantity. The default quantity is 1
:param item: string, Item to be added
:param price: float, The price of the item
:param quantity:int, The number of items, defaults to 1
:return:None
>>> shoppingcart = ShoppingCart()
>>> shoppingcart.add_item("apple", 1, 5)
self.items = {"apple":{"price":1, "quantity":5}}
"""
def remove_item(self, item, quantity=1):
"""
Subtract the specified quantity of item from the shopping list items
:param item:string, Item to be subtracted in quantity
:param quantity:int, Quantity to be subtracted
:return:None
>>> shoppingcart.add_item("apple", 1, 5)
>>> shoppingcart.remove_item("apple", 3)
self.items = {"apple":{"price":1, "quantity":2}}
"""
def view_items(self) -> dict:
"""
Return the current shopping list items
:return:dict, the current shopping list items
>>> shoppingcart.add_item("apple", 1, 5)
>>> shoppingcart.remove_item("apple", 3)
>>> shoppingcart.view_items()
{"apple":{"price":1, "quantity":2}}
"""
def total_price(self) -> float:
"""
Calculate the total price of all items in the shopping list, which is the quantity of each item multiplied by the price
:return:float, the total price of all items in the shopping list
>>> shoppingcart = ShoppingCart()
>>> shoppingcart.add_item("apple", 1, 5)
>>> shoppingcart.add_item("banana", 2, 3)
>>> shoppingcart.total_price()
11.0
""" | import unittest
class ShoppingCartTestAddItem(unittest.TestCase):
def test_add_item_1(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 5)
self.assertEqual(shoppingcart.items, {"apple": {"price": 1, "quantity": 5}})
def test_add_item_2(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1)
self.assertEqual(shoppingcart.items, {"apple": {"price": 1, "quantity": 1}})
def test_add_item_3(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("aaa", 1)
self.assertEqual(shoppingcart.items, {"aaa": {"price": 1, "quantity": 1}})
def test_add_item_4(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("bbb", 1)
self.assertEqual(shoppingcart.items, {"bbb": {"price": 1, "quantity": 1}})
def test_add_item_5(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("ccc", 1)
self.assertEqual(shoppingcart.items, {"ccc": {"price": 1, "quantity": 1}})
def test_add_item_6(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 5)
shoppingcart.add_item("apple", 1, 5)
self.assertEqual(shoppingcart.items, {"apple": {"price": 1, "quantity": 5}})
class ShoppingCartTestRemoveItem(unittest.TestCase):
def test_remove_item_1(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 5)
shoppingcart.remove_item("apple", 3)
self.assertEqual(shoppingcart.items, {"apple": {"price": 1, "quantity": 2}})
def test_remove_item_2(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 5)
shoppingcart.remove_item("apple")
self.assertEqual(shoppingcart.items, {"apple": {"price": 1, "quantity": 4}})
def test_remove_item_3(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 5)
shoppingcart.remove_item("apple", 1)
self.assertEqual(shoppingcart.items, {"apple": {"price": 1, "quantity": 4}})
def test_remove_item_4(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 5)
shoppingcart.remove_item("apple", 2)
self.assertEqual(shoppingcart.items, {"apple": {"price": 1, "quantity": 3}})
def test_remove_item_5(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 5)
shoppingcart.remove_item("apple", 4)
self.assertEqual(shoppingcart.items, {"apple": {"price": 1, "quantity": 1}})
def test_remove_item_6(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 5)
shoppingcart.remove_item("banana", 4)
self.assertEqual(shoppingcart.items, {"apple": {"price": 1, "quantity": 5}})
class ShoppingCartTestViewItems(unittest.TestCase):
def test_view_items_1(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 5)
self.assertEqual(shoppingcart.view_items(), {"apple": {"price": 1, "quantity": 5}})
def test_view_items_2(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 4)
self.assertEqual(shoppingcart.view_items(), {"apple": {"price": 1, "quantity": 4}})
def test_view_items_3(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 3)
self.assertEqual(shoppingcart.view_items(), {"apple": {"price": 1, "quantity": 3}})
def test_view_items_4(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 2)
self.assertEqual(shoppingcart.view_items(), {"apple": {"price": 1, "quantity": 2}})
def test_view_items_5(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 1)
self.assertEqual(shoppingcart.view_items(), {"apple": {"price": 1, "quantity": 1}})
class ShoppingCartTestTotalPrice(unittest.TestCase):
def test_total_price_1(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 5)
shoppingcart.add_item("banana", 2, 3)
self.assertEqual(shoppingcart.total_price(), 11.0)
def test_total_price_2(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 5)
shoppingcart.add_item("banana", 2, 3)
shoppingcart.remove_item("apple", 3)
self.assertEqual(shoppingcart.total_price(), 8.0)
def test_total_price_3(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 1)
shoppingcart.add_item("banana", 2, 1)
self.assertEqual(shoppingcart.total_price(), 3.0)
def test_total_price_4(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 2)
shoppingcart.add_item("banana", 2, 1)
self.assertEqual(shoppingcart.total_price(), 4.0)
def test_total_price_5(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 3)
shoppingcart.add_item("banana", 2, 1)
self.assertEqual(shoppingcart.total_price(), 5.0)
class ShoppingCartTest(unittest.TestCase):
def test_shoppingcart(self):
shoppingcart = ShoppingCart()
shoppingcart.add_item("apple", 1, 5)
self.assertEqual(shoppingcart.items, {"apple": {"price": 1, "quantity": 5}})
self.assertEqual(shoppingcart.view_items(), {"apple": {"price": 1, "quantity": 5}})
shoppingcart.remove_item("apple", 3)
self.assertEqual(shoppingcart.items, {"apple": {"price": 1, "quantity": 2}})
shoppingcart.add_item("banana", 2, 3)
self.assertEqual(shoppingcart.total_price(), 8.0) | class ShoppingCart:
def __init__(self):
self.items = {}
def add_item(self, item, price, quantity=1):
if item in self.items:
self.items[item] = {'price': price, 'quantity': quantity}
else:
self.items[item] = {'price': price, 'quantity': quantity}
def remove_item(self, item, quantity=1):
if item in self.items:
self.items[item]['quantity'] -= quantity
else:
pass
def view_items(self) -> dict:
return self.items
def total_price(self) -> float:
return sum([item['quantity'] * item['price'] for item in self.items.values()]) | [] | """
The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price.
"""
| [
{
"method_name": "add_item",
"method_description": "def add_item(self, item, price, quantity=1):\n \"\"\"\n Add item information to the shopping list items, including price and quantity. The default quantity is 1\n :param item: string, Item to be added\n :param price: float, The price of the item\n :param quantity:int, The number of items, defaults to 1\n :return:None\n >>> shoppingcart = ShoppingCart()\n >>> shoppingcart.add_item(\"apple\", 1, 5)\n self.items = {\"apple\":{\"price\":1, \"quantity\":5}}\n \"\"\"",
"test_class": "ShoppingCartTestAddItem",
"test_code": "class ShoppingCartTestAddItem(unittest.TestCase):\n def test_add_item_1(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 5}})\n\n def test_add_item_2(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 1}})\n\n def test_add_item_3(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"aaa\", 1)\n self.assertEqual(shoppingcart.items, {\"aaa\": {\"price\": 1, \"quantity\": 1}})\n\n def test_add_item_4(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"bbb\", 1)\n self.assertEqual(shoppingcart.items, {\"bbb\": {\"price\": 1, \"quantity\": 1}})\n\n def test_add_item_5(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"ccc\", 1)\n self.assertEqual(shoppingcart.items, {\"ccc\": {\"price\": 1, \"quantity\": 1}})\n\n def test_add_item_6(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.add_item(\"apple\", 1, 5)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 5}})",
"solution_code": "def add_item(self, item, price, quantity=1):\n if item in self.items:\n self.items[item] = {'price': price, 'quantity': quantity}\n else:\n self.items[item] = {'price': price, 'quantity': quantity}",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.items"
],
"method_dependencies": []
}
},
{
"method_name": "remove_item",
"method_description": "def remove_item(self, item, quantity=1):\n \"\"\"\n Subtract the specified quantity of item from the shopping list items\n :param item:string, Item to be subtracted in quantity\n :param quantity:int, Quantity to be subtracted\n :return:None\n >>> shoppingcart.add_item(\"apple\", 1, 5)\n >>> shoppingcart.remove_item(\"apple\", 3)\n self.items = {\"apple\":{\"price\":1, \"quantity\":2}}\n \"\"\"",
"test_class": "ShoppingCartTestRemoveItem",
"test_code": "class ShoppingCartTestRemoveItem(unittest.TestCase):\n def test_remove_item_1(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\", 3)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 2}})\n\n def test_remove_item_2(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\")\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 4}})\n\n def test_remove_item_3(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\", 1)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 4}})\n\n def test_remove_item_4(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\", 2)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 3}})\n\n def test_remove_item_5(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\", 4)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 1}})\n\n def test_remove_item_6(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"banana\", 4)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 5}})",
"solution_code": "def remove_item(self, item, quantity=1):\n if item in self.items:\n self.items[item]['quantity'] -= quantity\n else:\n pass",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.items"
],
"method_dependencies": []
}
},
{
"method_name": "view_items",
"method_description": "def view_items(self) -> dict:\n \"\"\"\n Return the current shopping list items\n :return:dict, the current shopping list items\n >>> shoppingcart.add_item(\"apple\", 1, 5)\n >>> shoppingcart.remove_item(\"apple\", 3)\n >>> shoppingcart.view_items()\n {\"apple\":{\"price\":1, \"quantity\":2}}\n \"\"\"",
"test_class": "ShoppingCartTestViewItems",
"test_code": "class ShoppingCartTestViewItems(unittest.TestCase):\n def test_view_items_1(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 5}})\n\n def test_view_items_2(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 4)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 4}})\n\n def test_view_items_3(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 3)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 3}})\n\n def test_view_items_4(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 2)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 2}})\n\n def test_view_items_5(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 1)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 1}})",
"solution_code": "def view_items(self) -> dict:\n return self.items",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.items"
],
"method_dependencies": []
}
},
{
"method_name": "total_price",
"method_description": "def total_price(self) -> float:\n \"\"\"\n Calculate the total price of all items in the shopping list, which is the quantity of each item multiplied by the price\n :return:float, the total price of all items in the shopping list\n >>> shoppingcart = ShoppingCart()\n >>> shoppingcart.add_item(\"apple\", 1, 5)\n >>> shoppingcart.add_item(\"banana\", 2, 3)\n >>> shoppingcart.total_price()\n 11.0\n \"\"\"",
"test_class": "ShoppingCartTestTotalPrice",
"test_code": "class ShoppingCartTestTotalPrice(unittest.TestCase):\n def test_total_price_1(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.add_item(\"banana\", 2, 3)\n self.assertEqual(shoppingcart.total_price(), 11.0)\n\n def test_total_price_2(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.add_item(\"banana\", 2, 3)\n shoppingcart.remove_item(\"apple\", 3)\n self.assertEqual(shoppingcart.total_price(), 8.0)\n\n def test_total_price_3(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 1)\n shoppingcart.add_item(\"banana\", 2, 1)\n self.assertEqual(shoppingcart.total_price(), 3.0)\n\n def test_total_price_4(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 2)\n shoppingcart.add_item(\"banana\", 2, 1)\n self.assertEqual(shoppingcart.total_price(), 4.0)\n\n def test_total_price_5(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 3)\n shoppingcart.add_item(\"banana\", 2, 1)\n self.assertEqual(shoppingcart.total_price(), 5.0)",
"solution_code": "def total_price(self) -> float:\n return sum([item['quantity'] * item['price'] for item in self.items.values()])",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.items"
],
"method_dependencies": []
}
}
] | ShoppingCart | [
"ShoppingCartTestAddItem",
"ShoppingCartTestRemoveItem",
"ShoppingCartTestViewItems",
"ShoppingCartTestTotalPrice",
"ShoppingCartTest"
] | class ShoppingCart:
def __init__(self):
"""
Initialize the items representing the shopping list as an empty dictionary
"""
self.items = {}
| [
"self.items"
] |
ClassEval_76 | class SignInSystem:
"""
This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users.
"""
def __init__(self):
"""
Initialize the sign-in system.
"""
self.users = {}
def add_user(self, username):
"""
Add a user to the sign-in system if the user wasn't in the self.users.
And the initial state is False.
:param username: str, the username to be added.
:return: bool, True if the user is added successfully, False if the user already exists.
>>> signInSystem.add_user("mike")
True
>>> signInSystem.add_user("mike")
False
"""
def sign_in(self, username):
"""
Sign in a user if the user was in the self.users and change the state to True.
:param username: str, the username to be signed in.
:return: bool, True if the user is signed in successfully, False if the user does not exist.
>>> signInSystem.sign_in("mike")
True
>>> signInSystem.sign_in("mik")
False
"""
def check_sign_in(self, username):
"""
Check if a user is signed in.
:param username: str, the username to be checked.
:return: bool, True if the user is signed in, False if the user does not exist or is not signed in.
>>> signInSystem.check_sign_in("jack")
False
>>> signInSystem.add_user("jack")
>>> signInSystem.check_sign_in("jack")
>>> signInSystem.sign_in("jack")
>>> signInSystem.check_sign_in("jack")
True
"""
def all_signed_in(self):
"""
Check if all users are signed in.
:return: bool, True if all users are signed in, False otherwise.
>>> signInSystem.add_user("jack")
True
>>> signInSystem.sign_in("jack")
>>> signInSystem.all_signed_in()
True
"""
def all_not_signed_in(self):
"""
Get a list of usernames that are not signed in.
:return: list[str], a list of usernames that are not signed in.
>>> signInSystem = SignInSystem()
>>> signInSystem.add_user("a")
True
>>> signInSystem.add_user("b")
True
>>> signInSystem.all_not_signed_in()
['a', 'b']
""" | import unittest
class SignInSystemTestAddUser(unittest.TestCase):
def test_add_user_1(self):
signin_system = SignInSystem()
result = signin_system.add_user("user1")
self.assertTrue(result)
def test_add_user_2(self):
signin_system = SignInSystem()
signin_system.add_user("user1")
result = signin_system.add_user("user1")
self.assertFalse(result)
def test_add_user_3(self):
signin_system = SignInSystem()
result = signin_system.add_user("aaa")
self.assertTrue(result)
def test_add_user_4(self):
signin_system = SignInSystem()
result = signin_system.add_user("bbb")
self.assertTrue(result)
def test_add_user_5(self):
signin_system = SignInSystem()
result = signin_system.add_user("ccc")
self.assertTrue(result)
class SignInSystemTestSignIn(unittest.TestCase):
def test_sign_in_1(self):
signin_system = SignInSystem()
signin_system.add_user("user1")
result = signin_system.sign_in("user1")
self.assertTrue(result)
# user not exist
def test_sign_in_2(self):
signin_system = SignInSystem()
result = signin_system.sign_in("user1")
self.assertFalse(result)
def test_sign_in_3(self):
signin_system = SignInSystem()
signin_system.add_user("aaa")
result = signin_system.sign_in("aaa")
self.assertTrue(result)
def test_sign_in_4(self):
signin_system = SignInSystem()
signin_system.add_user("bbb")
result = signin_system.sign_in("bbb")
self.assertTrue(result)
def test_sign_in_5(self):
signin_system = SignInSystem()
result = signin_system.sign_in("ccc")
self.assertFalse(result)
class SignInSystemTestCheckSignIn(unittest.TestCase):
# has signed in
def test_check_sign_in_1(self):
signin_system = SignInSystem()
signin_system.add_user("user1")
signin_system.sign_in("user1")
result = signin_system.check_sign_in("user1")
self.assertTrue(result)
# hasn't signed in
def test_check_sign_in_2(self):
signin_system = SignInSystem()
signin_system.add_user("user1")
result = signin_system.check_sign_in("user1")
self.assertFalse(result)
# not exist
def test_check_sign_in_3(self):
signin_system = SignInSystem()
result = signin_system.check_sign_in("user1")
self.assertFalse(result)
def test_check_sign_in_4(self):
signin_system = SignInSystem()
signin_system.add_user("aaa")
signin_system.sign_in("aaa")
result = signin_system.check_sign_in("aaa")
self.assertTrue(result)
def test_check_sign_in_5(self):
signin_system = SignInSystem()
signin_system.add_user("bbb")
signin_system.sign_in("bbb")
result = signin_system.check_sign_in("bbb")
self.assertTrue(result)
class SignInSystemTestAllSignedIn(unittest.TestCase):
def test_all_signed_in_1(self):
signin_system = SignInSystem()
signin_system.add_user("user1")
signin_system.sign_in("user1")
result = signin_system.all_signed_in()
self.assertTrue(result)
def test_all_signed_in_2(self):
signin_system = SignInSystem()
signin_system.add_user("user1")
result = signin_system.all_signed_in()
self.assertFalse(result)
def test_all_signed_in_3(self):
signin_system = SignInSystem()
signin_system.add_user("aaa")
signin_system.sign_in("aaa")
result = signin_system.all_signed_in()
self.assertTrue(result)
def test_all_signed_in_4(self):
signin_system = SignInSystem()
signin_system.add_user("bbb")
signin_system.sign_in("bbb")
result = signin_system.all_signed_in()
self.assertTrue(result)
def test_all_signed_in_5(self):
signin_system = SignInSystem()
signin_system.add_user("aaa")
signin_system.add_user("bbb")
signin_system.sign_in("aaa")
result = signin_system.all_signed_in()
self.assertFalse(result)
class SignInSystemTestAllNotSignedIn(unittest.TestCase):
def test_all_not_signed_in_1(self):
signin_system = SignInSystem()
signin_system.add_user("user1")
signin_system.sign_in("user1")
result = signin_system.all_not_signed_in()
self.assertEqual([], result)
def test_all_not_signed_in_2(self):
signin_system = SignInSystem()
signin_system.add_user("user1")
signin_system.add_user("user2")
result = signin_system.all_not_signed_in()
self.assertEqual(["user1", "user2"], result)
def test_all_not_signed_in_3(self):
signin_system = SignInSystem()
signin_system.add_user("aaa")
signin_system.sign_in("aaa")
result = signin_system.all_not_signed_in()
self.assertEqual([], result)
def test_all_not_signed_in_4(self):
signin_system = SignInSystem()
signin_system.add_user("user1")
signin_system.add_user("aaa")
signin_system.sign_in("user1")
result = signin_system.all_not_signed_in()
self.assertEqual(['aaa'], result)
def test_all_not_signed_in_5(self):
signin_system = SignInSystem()
result = signin_system.all_not_signed_in()
self.assertEqual([], result)
class SignInSystemTestMain(unittest.TestCase):
def setUp(self):
self.signin_system = SignInSystem()
def test_main(self):
result = self.signin_system.add_user("user1")
result = self.signin_system.add_user("user2")
self.assertTrue(result)
result = self.signin_system.sign_in("user1")
self.assertTrue(result)
result = self.signin_system.check_sign_in("user1")
self.assertTrue(result)
result = self.signin_system.all_signed_in()
self.assertFalse(result)
result = self.signin_system.all_not_signed_in()
self.assertEqual(["user2"], result) | class SignInSystem:
def __init__(self):
self.users = {}
def add_user(self, username):
if username in self.users:
return False
else:
self.users[username] = False
return True
def sign_in(self, username):
if username not in self.users:
return False
else:
self.users[username] = True
return True
def check_sign_in(self, username):
if username not in self.users:
return False
else:
if self.users[username]:
return True
else:
return False
def all_signed_in(self):
if all(self.users.values()):
return True
else:
return False
def all_not_signed_in(self):
not_signed_in_users = []
for username, signed_in in self.users.items():
if not signed_in:
not_signed_in_users.append(username)
return not_signed_in_users | [] | """
This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users.
"""
| [
{
"method_name": "add_user",
"method_description": "def add_user(self, username):\n \"\"\"\n Add a user to the sign-in system if the user wasn't in the self.users.\n And the initial state is False.\n :param username: str, the username to be added.\n :return: bool, True if the user is added successfully, False if the user already exists.\n >>> signInSystem.add_user(\"mike\")\n True\n >>> signInSystem.add_user(\"mike\")\n False\n \"\"\"",
"test_class": "SignInSystemTestAddUser",
"test_code": "class SignInSystemTestAddUser(unittest.TestCase):\n def test_add_user_1(self):\n signin_system = SignInSystem()\n result = signin_system.add_user(\"user1\")\n self.assertTrue(result)\n\n def test_add_user_2(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n result = signin_system.add_user(\"user1\")\n self.assertFalse(result)\n\n def test_add_user_3(self):\n signin_system = SignInSystem()\n result = signin_system.add_user(\"aaa\")\n self.assertTrue(result)\n\n def test_add_user_4(self):\n signin_system = SignInSystem()\n result = signin_system.add_user(\"bbb\")\n self.assertTrue(result)\n\n def test_add_user_5(self):\n signin_system = SignInSystem()\n result = signin_system.add_user(\"ccc\")\n self.assertTrue(result)",
"solution_code": "def add_user(self, username):\n if username in self.users:\n return False\n else:\n self.users[username] = False\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.users"
],
"method_dependencies": []
}
},
{
"method_name": "sign_in",
"method_description": "def sign_in(self, username):\n \"\"\"\n Sign in a user if the user was in the self.users and change the state to True.\n :param username: str, the username to be signed in.\n :return: bool, True if the user is signed in successfully, False if the user does not exist.\n >>> signInSystem.sign_in(\"mike\")\n True\n >>> signInSystem.sign_in(\"mik\")\n False\n \"\"\"",
"test_class": "SignInSystemTestSignIn",
"test_code": "class SignInSystemTestSignIn(unittest.TestCase):\n def test_sign_in_1(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n result = signin_system.sign_in(\"user1\")\n self.assertTrue(result)\n\n # user not exist\n def test_sign_in_2(self):\n signin_system = SignInSystem()\n result = signin_system.sign_in(\"user1\")\n self.assertFalse(result)\n\n def test_sign_in_3(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n result = signin_system.sign_in(\"aaa\")\n self.assertTrue(result)\n\n def test_sign_in_4(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"bbb\")\n result = signin_system.sign_in(\"bbb\")\n self.assertTrue(result)\n\n def test_sign_in_5(self):\n signin_system = SignInSystem()\n result = signin_system.sign_in(\"ccc\")\n self.assertFalse(result)",
"solution_code": "def sign_in(self, username):\n if username not in self.users:\n return False\n else:\n self.users[username] = True\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.users"
],
"method_dependencies": []
}
},
{
"method_name": "check_sign_in",
"method_description": "def check_sign_in(self, username):\n \"\"\"\n Check if a user is signed in.\n :param username: str, the username to be checked.\n :return: bool, True if the user is signed in, False if the user does not exist or is not signed in.\n >>> signInSystem.check_sign_in(\"jack\")\n False\n >>> signInSystem.add_user(\"jack\")\n >>> signInSystem.check_sign_in(\"jack\")\n >>> signInSystem.sign_in(\"jack\")\n >>> signInSystem.check_sign_in(\"jack\")\n True\n \"\"\"",
"test_class": "SignInSystemTestCheckSignIn",
"test_code": "class SignInSystemTestCheckSignIn(unittest.TestCase):\n # has signed in\n def test_check_sign_in_1(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.sign_in(\"user1\")\n result = signin_system.check_sign_in(\"user1\")\n self.assertTrue(result)\n\n # hasn't signed in \n def test_check_sign_in_2(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n result = signin_system.check_sign_in(\"user1\")\n self.assertFalse(result)\n\n # not exist\n def test_check_sign_in_3(self):\n signin_system = SignInSystem()\n result = signin_system.check_sign_in(\"user1\")\n self.assertFalse(result)\n\n def test_check_sign_in_4(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n signin_system.sign_in(\"aaa\")\n result = signin_system.check_sign_in(\"aaa\")\n self.assertTrue(result)\n\n def test_check_sign_in_5(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"bbb\")\n signin_system.sign_in(\"bbb\")\n result = signin_system.check_sign_in(\"bbb\")\n self.assertTrue(result)",
"solution_code": "def check_sign_in(self, username):\n if username not in self.users:\n return False\n else:\n if self.users[username]:\n return True\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.users"
],
"method_dependencies": []
}
},
{
"method_name": "all_signed_in",
"method_description": "def all_signed_in(self):\n \"\"\"\n Check if all users are signed in.\n :return: bool, True if all users are signed in, False otherwise.\n >>> signInSystem.add_user(\"jack\")\n True\n >>> signInSystem.sign_in(\"jack\")\n >>> signInSystem.all_signed_in()\n True\n \"\"\"",
"test_class": "SignInSystemTestAllSignedIn",
"test_code": "class SignInSystemTestAllSignedIn(unittest.TestCase):\n def test_all_signed_in_1(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.sign_in(\"user1\")\n result = signin_system.all_signed_in()\n self.assertTrue(result)\n\n def test_all_signed_in_2(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n result = signin_system.all_signed_in()\n self.assertFalse(result)\n\n def test_all_signed_in_3(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n signin_system.sign_in(\"aaa\")\n result = signin_system.all_signed_in()\n self.assertTrue(result)\n\n def test_all_signed_in_4(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"bbb\")\n signin_system.sign_in(\"bbb\")\n result = signin_system.all_signed_in()\n self.assertTrue(result)\n\n def test_all_signed_in_5(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n signin_system.add_user(\"bbb\")\n signin_system.sign_in(\"aaa\")\n result = signin_system.all_signed_in()\n self.assertFalse(result)",
"solution_code": "def all_signed_in(self):\n if all(self.users.values()):\n return True\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.users"
],
"method_dependencies": []
}
},
{
"method_name": "all_not_signed_in",
"method_description": "def all_not_signed_in(self):\n \"\"\"\n Get a list of usernames that are not signed in.\n :return: list[str], a list of usernames that are not signed in.\n >>> signInSystem = SignInSystem()\n >>> signInSystem.add_user(\"a\")\n True\n >>> signInSystem.add_user(\"b\")\n True\n >>> signInSystem.all_not_signed_in()\n ['a', 'b']\n \"\"\"",
"test_class": "SignInSystemTestAllNotSignedIn",
"test_code": "class SignInSystemTestAllNotSignedIn(unittest.TestCase):\n def test_all_not_signed_in_1(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.sign_in(\"user1\")\n result = signin_system.all_not_signed_in()\n self.assertEqual([], result)\n\n def test_all_not_signed_in_2(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.add_user(\"user2\")\n result = signin_system.all_not_signed_in()\n self.assertEqual([\"user1\", \"user2\"], result)\n\n def test_all_not_signed_in_3(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n signin_system.sign_in(\"aaa\")\n result = signin_system.all_not_signed_in()\n self.assertEqual([], result)\n\n def test_all_not_signed_in_4(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.add_user(\"aaa\")\n signin_system.sign_in(\"user1\")\n result = signin_system.all_not_signed_in()\n self.assertEqual(['aaa'], result)\n\n def test_all_not_signed_in_5(self):\n signin_system = SignInSystem()\n result = signin_system.all_not_signed_in()\n self.assertEqual([], result)",
"solution_code": "def all_not_signed_in(self):\n not_signed_in_users = []\n for username, signed_in in self.users.items():\n if not signed_in:\n not_signed_in_users.append(username)\n return not_signed_in_users",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.users"
],
"method_dependencies": []
}
}
] | SignInSystem | [
"SignInSystemTestAddUser",
"SignInSystemTestSignIn",
"SignInSystemTestCheckSignIn",
"SignInSystemTestAllSignedIn",
"SignInSystemTestAllNotSignedIn",
"SignInSystemTestMain"
] | class SignInSystem:
def __init__(self):
"""
Initialize the sign-in system.
"""
self.users = {}
| [
"self.users"
] |
ClassEval_77 | import random
class Snake:
"""
The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position.
"""
def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position):
"""
Initialize the length of the snake, screen width, screen height, block size, snake head position, score, and food position.
:param SCREEN_WIDTH: int
:param SCREEN_HEIGHT: int
:param BLOCK_SIZE: int, Size of moving units
:param food_position: tuple, representing the position(x, y) of food.
"""
self.length = 1
self.SCREEN_WIDTH = SCREEN_WIDTH
self.SCREEN_HEIGHT = SCREEN_HEIGHT
self.BLOCK_SIZE = BLOCK_SIZE
self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))]
self.score = 0
self.food_position = food_position
def move(self, direction):
"""
Move the snake in the specified direction. If the new position of the snake's head is equal to the position of the food, then eat the food; If the position of the snake's head is equal to the position of its body, then start over, otherwise its own length plus one.
:param direction: tuple, representing the direction of movement (x, y).
:return: None
>>> snake.move((1,1))
self.length = 1
self.positions = [(51, 51), (50, 50)]
self.score = 10
"""
def random_food_position(self):
"""
Randomly generate a new food position, but don't place it on the snake.
:return: None, Change the food position
"""
def reset(self):
"""
Reset the snake to its initial state. Set the length to 1, the snake head position to ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2)), the score to 0, and randomly generate new food position.
:return: None
>>> snake = Snake(100, 100, 1, (51, 51))
>>> snake.reset()
self.length = 1
self.positions = [(50, 50)]
self.score = 0
self.random_food_position()
"""
def eat_food(self):
"""
Increase the length of the snake by 1 and increase the score by 100. Randomly generate a new food position, but
don't place it on the snake.
:return: None
>>> snake = Snake(100, 100, 1, (51, 51))
>>> snake.move((1,1))
>>> snake.eat_food()
self.length = 2
self.score = 10
""" | import unittest
class SnakeTestMove(unittest.TestCase):
def test_move_1(self):
snake = Snake(100, 100, 1, (51, 51))
snake.move((1, 1))
self.assertEqual(snake.length, 2)
self.assertEqual(snake.positions[0], (51, 51))
self.assertEqual(snake.positions[1], (50, 50))
self.assertEqual(snake.score, 100)
def test_move_2(self):
snake = Snake(100, 100, 1, (80, 80))
snake.move((1, 1))
self.assertEqual(snake.length, 1)
self.assertEqual(snake.positions[0], (51, 51))
self.assertEqual(snake.score, 0)
def test_move_3(self):
snake = Snake(100, 100, 1, (51, 51))
snake.move((1, 0))
self.assertEqual(snake.length, 1)
self.assertEqual(snake.positions[0], (51, 50))
self.assertEqual(snake.score, 0)
def test_move_4(self):
snake = Snake(100, 100, 1, (51, 51))
snake.move((0, 0))
self.assertEqual(snake.length, 1)
self.assertEqual(snake.positions[0], (50, 50))
self.assertEqual(snake.score, 0)
def test_move_5(self):
snake = Snake(100, 100, 1, (99, 99))
snake.move((1, 0))
self.assertEqual(snake.length, 1)
self.assertEqual(snake.positions[0], (51, 50))
self.assertEqual(snake.score, 0)
class SnakeTestRandomFoodPosition(unittest.TestCase):
def test_random_food_position_1(self):
snake = Snake(100, 100, 1, (51, 51))
self.assertEqual(snake.food_position, (51, 51))
snake.random_food_position()
self.assertNotIn(snake.food_position, snake.positions)
self.assertGreaterEqual(snake.food_position[0], 0)
self.assertGreaterEqual(snake.food_position[1], 0)
self.assertLessEqual(snake.food_position[0], 100)
self.assertLessEqual(snake.food_position[1], 100)
def test_random_food_position_2(self):
snake = Snake(100, 100, 1, (99, 99))
self.assertEqual(snake.food_position, (99, 99))
snake.random_food_position()
self.assertNotIn(snake.food_position, snake.positions)
self.assertGreaterEqual(snake.food_position[0], 0)
self.assertGreaterEqual(snake.food_position[1], 0)
self.assertLessEqual(snake.food_position[0], 100)
self.assertLessEqual(snake.food_position[1], 100)
def test_random_food_position_3(self):
snake = Snake(100, 100, 1, (0, 0))
self.assertEqual(snake.food_position, (0, 0))
snake.random_food_position()
self.assertNotIn(snake.food_position, snake.positions)
self.assertGreaterEqual(snake.food_position[0], 0)
self.assertGreaterEqual(snake.food_position[1], 0)
self.assertLessEqual(snake.food_position[0], 100)
self.assertLessEqual(snake.food_position[1], 100)
def test_random_food_position_4(self):
snake = Snake(100, 100, 1, (40, 40))
self.assertEqual(snake.food_position, (40, 40))
snake.random_food_position()
self.assertNotIn(snake.food_position, snake.positions)
self.assertGreaterEqual(snake.food_position[0], 0)
self.assertGreaterEqual(snake.food_position[1], 0)
self.assertLessEqual(snake.food_position[0], 100)
self.assertLessEqual(snake.food_position[1], 100)
def test_random_food_position_5(self):
snake = Snake(100, 100, 1, (60, 60))
self.assertEqual(snake.food_position, (60, 60))
snake.random_food_position()
self.assertNotIn(snake.food_position, snake.positions)
self.assertGreaterEqual(snake.food_position[0], 0)
self.assertGreaterEqual(snake.food_position[1], 0)
self.assertLessEqual(snake.food_position[0], 100)
self.assertLessEqual(snake.food_position[1], 100)
class SnakeTestReset(unittest.TestCase):
def test_reset_1(self):
snake = Snake(100, 100, 1, (51, 51))
snake.move((1, 1))
snake.reset()
self.assertEqual(snake.length, 1)
self.assertEqual(snake.positions[0], (50, 50))
self.assertEqual(snake.score, 0)
def test_reset_2(self):
snake = Snake(100, 100, 1, (51, 51))
snake.move((0, 1))
snake.reset()
self.assertEqual(snake.length, 1)
self.assertEqual(snake.positions[0], (50, 50))
self.assertEqual(snake.score, 0)
def test_reset_3(self):
snake = Snake(100, 100, 1, (51, 51))
snake.move((0, -1))
snake.reset()
self.assertEqual(snake.length, 1)
self.assertEqual(snake.positions[0], (50, 50))
self.assertEqual(snake.score, 0)
def test_reset_4(self):
snake = Snake(100, 100, 1, (51, 51))
snake.move((-1, 0))
snake.reset()
self.assertEqual(snake.length, 1)
self.assertEqual(snake.positions[0], (50, 50))
self.assertEqual(snake.score, 0)
def test_reset_5(self):
snake = Snake(100, 100, 1, (51, 51))
snake.move((1, 0))
snake.reset()
self.assertEqual(snake.length, 1)
self.assertEqual(snake.positions[0], (50, 50))
self.assertEqual(snake.score, 0)
class SnakeTestEatFood(unittest.TestCase):
def test_eat_food_1(self):
snake = Snake(100, 100, 1, (51, 51))
self.assertEqual(snake.length, 1)
self.assertEqual(snake.score, 0)
snake.eat_food()
self.assertEqual(snake.length, 2)
self.assertEqual(snake.score, 100)
def test_eat_food_2(self):
snake = Snake(100, 100, 1, (51, 51))
self.assertEqual(snake.length, 1)
self.assertEqual(snake.score, 0)
snake.eat_food()
snake.eat_food()
self.assertEqual(snake.length, 3)
self.assertEqual(snake.score, 200)
def test_eat_food_3(self):
snake = Snake(100, 100, 1, (51, 51))
self.assertEqual(snake.length, 1)
self.assertEqual(snake.score, 0)
snake.eat_food()
snake.eat_food()
snake.eat_food()
self.assertEqual(snake.length, 4)
self.assertEqual(snake.score, 300)
def test_eat_food_4(self):
snake = Snake(100, 100, 1, (51, 51))
self.assertEqual(snake.length, 1)
self.assertEqual(snake.score, 0)
snake.eat_food()
snake.eat_food()
snake.eat_food()
snake.eat_food()
self.assertEqual(snake.length, 5)
self.assertEqual(snake.score, 400)
def test_eat_food_5(self):
snake = Snake(100, 100, 1, (51, 51))
self.assertEqual(snake.length, 1)
self.assertEqual(snake.score, 0)
snake.eat_food()
snake.eat_food()
snake.eat_food()
snake.eat_food()
snake.eat_food()
self.assertEqual(snake.length, 6)
self.assertEqual(snake.score, 500)
class SnakeTest(unittest.TestCase):
def test_snake(self):
snake = Snake(100, 100, 1, (51, 51))
self.assertEqual(snake.length, 1)
self.assertEqual(snake.SCREEN_WIDTH, 100)
self.assertEqual(snake.SCREEN_HEIGHT, 100)
self.assertEqual(snake.BLOCK_SIZE, 1)
self.assertEqual(snake.positions[0], (50, 50))
self.assertEqual(snake.score, 0)
self.assertEqual(snake.food_position, (51, 51))
snake.move((1, 1))
self.assertEqual(snake.length, 2)
self.assertEqual(snake.positions[0], (51, 51))
self.assertEqual(snake.score, 100)
snake.random_food_position()
self.assertNotIn(snake.food_position, snake.positions)
snake.reset()
self.assertEqual(snake.length, 1)
self.assertEqual(snake.positions[0], (50, 50))
self.assertEqual(snake.score, 0) | import random
class Snake:
def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position):
self.length = 1
self.SCREEN_WIDTH = SCREEN_WIDTH
self.SCREEN_HEIGHT = SCREEN_HEIGHT
self.BLOCK_SIZE = BLOCK_SIZE
self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))]
self.score = 0
self.food_position = food_position
def move(self, direction):
cur = self.positions[0]
x, y = direction
new = (
((cur[0] + (x * self.BLOCK_SIZE)) % self.SCREEN_WIDTH),
(cur[1] + (y * self.BLOCK_SIZE)) % self.SCREEN_HEIGHT,
)
if new == self.food_position:
self.eat_food()
if len(self.positions) > 2 and new in self.positions[2:]:
self.reset()
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
def random_food_position(self):
while self.food_position in self.positions:
self.food_position = (random.randint(0, self.SCREEN_WIDTH // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE,
random.randint(0, self.SCREEN_HEIGHT // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE)
def reset(self):
self.length = 1
self.positions = [((self.SCREEN_WIDTH / 2), (self.SCREEN_HEIGHT / 2))]
self.score = 0
self.random_food_position()
def eat_food(self):
self.length += 1
self.score += 100
self.random_food_position() | [
"import random"
] | """
The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position.
"""
| [
{
"method_name": "move",
"method_description": "def move(self, direction):\n \"\"\"\n Move the snake in the specified direction. If the new position of the snake's head is equal to the position of the food, then eat the food; If the position of the snake's head is equal to the position of its body, then start over, otherwise its own length plus one.\n :param direction: tuple, representing the direction of movement (x, y).\n :return: None\n >>> snake.move((1,1))\n self.length = 1\n self.positions = [(51, 51), (50, 50)]\n self.score = 10\n \"\"\"",
"test_class": "SnakeTestMove",
"test_code": "class SnakeTestMove(unittest.TestCase):\n def test_move_1(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((1, 1))\n self.assertEqual(snake.length, 2)\n self.assertEqual(snake.positions[0], (51, 51))\n self.assertEqual(snake.positions[1], (50, 50))\n self.assertEqual(snake.score, 100)\n\n def test_move_2(self):\n snake = Snake(100, 100, 1, (80, 80))\n snake.move((1, 1))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (51, 51))\n self.assertEqual(snake.score, 0)\n\n def test_move_3(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((1, 0))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (51, 50))\n self.assertEqual(snake.score, 0)\n\n def test_move_4(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((0, 0))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_move_5(self):\n snake = Snake(100, 100, 1, (99, 99))\n snake.move((1, 0))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (51, 50))\n self.assertEqual(snake.score, 0)",
"solution_code": "def move(self, direction):\n cur = self.positions[0]\n x, y = direction\n\n new = (\n ((cur[0] + (x * self.BLOCK_SIZE)) % self.SCREEN_WIDTH),\n (cur[1] + (y * self.BLOCK_SIZE)) % self.SCREEN_HEIGHT,\n )\n\n if new == self.food_position:\n self.eat_food()\n\n if len(self.positions) > 2 and new in self.positions[2:]:\n self.reset()\n else:\n self.positions.insert(0, new)\n if len(self.positions) > self.length:\n self.positions.pop()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.BLOCK_SIZE",
"self.SCREEN_HEIGHT",
"self.SCREEN_WIDTH",
"self.food_position",
"self.length",
"self.positions"
],
"method_dependencies": [
"reset",
"eat_food"
]
}
},
{
"method_name": "random_food_position",
"method_description": "def random_food_position(self):\n \"\"\"\n Randomly generate a new food position, but don't place it on the snake.\n :return: None, Change the food position\n \"\"\"",
"test_class": "SnakeTestRandomFoodPosition",
"test_code": "class SnakeTestRandomFoodPosition(unittest.TestCase):\n def test_random_food_position_1(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.food_position, (51, 51))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)\n\n def test_random_food_position_2(self):\n snake = Snake(100, 100, 1, (99, 99))\n self.assertEqual(snake.food_position, (99, 99))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)\n\n def test_random_food_position_3(self):\n snake = Snake(100, 100, 1, (0, 0))\n self.assertEqual(snake.food_position, (0, 0))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)\n\n def test_random_food_position_4(self):\n snake = Snake(100, 100, 1, (40, 40))\n self.assertEqual(snake.food_position, (40, 40))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)\n\n def test_random_food_position_5(self):\n snake = Snake(100, 100, 1, (60, 60))\n self.assertEqual(snake.food_position, (60, 60))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)",
"solution_code": "def random_food_position(self):\n while self.food_position in self.positions:\n self.food_position = (random.randint(0, self.SCREEN_WIDTH // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE,\n random.randint(0, self.SCREEN_HEIGHT // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"random"
],
"field_dependencies": [
"self.BLOCK_SIZE",
"self.SCREEN_HEIGHT",
"self.SCREEN_WIDTH",
"self.food_position",
"self.positions"
],
"method_dependencies": []
}
},
{
"method_name": "reset",
"method_description": "def reset(self):\n \"\"\"\n Reset the snake to its initial state. Set the length to 1, the snake head position to ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2)), the score to 0, and randomly generate new food position.\n :return: None\n >>> snake = Snake(100, 100, 1, (51, 51))\n >>> snake.reset()\n self.length = 1\n self.positions = [(50, 50)]\n self.score = 0\n self.random_food_position()\n \"\"\"",
"test_class": "SnakeTestReset",
"test_code": "class SnakeTestReset(unittest.TestCase):\n def test_reset_1(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((1, 1))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_reset_2(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((0, 1))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_reset_3(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((0, -1))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_reset_4(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((-1, 0))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_reset_5(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((1, 0))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)",
"solution_code": "def reset(self):\n self.length = 1\n self.positions = [((self.SCREEN_WIDTH / 2), (self.SCREEN_HEIGHT / 2))]\n self.score = 0\n self.random_food_position()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.SCREEN_HEIGHT",
"self.SCREEN_WIDTH",
"self.length",
"self.positions",
"self.score"
],
"method_dependencies": [
"random_food_position"
]
}
},
{
"method_name": "eat_food",
"method_description": "def eat_food(self):\n \"\"\"\n Increase the length of the snake by 1 and increase the score by 100. Randomly generate a new food position, but\n don't place it on the snake.\n :return: None\n >>> snake = Snake(100, 100, 1, (51, 51))\n >>> snake.move((1,1))\n >>> snake.eat_food()\n self.length = 2\n self.score = 10\n \"\"\"",
"test_class": "SnakeTestEatFood",
"test_code": "class SnakeTestEatFood(unittest.TestCase):\n def test_eat_food_1(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n self.assertEqual(snake.length, 2)\n self.assertEqual(snake.score, 100)\n\n def test_eat_food_2(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n snake.eat_food()\n self.assertEqual(snake.length, 3)\n self.assertEqual(snake.score, 200)\n\n def test_eat_food_3(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n self.assertEqual(snake.length, 4)\n self.assertEqual(snake.score, 300)\n\n def test_eat_food_4(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n self.assertEqual(snake.length, 5)\n self.assertEqual(snake.score, 400)\n\n def test_eat_food_5(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n self.assertEqual(snake.length, 6)\n self.assertEqual(snake.score, 500)",
"solution_code": "def eat_food(self):\n self.length += 1\n self.score += 100\n self.random_food_position()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.length",
"self.score"
],
"method_dependencies": [
"random_food_position"
]
}
}
] | Snake | [
"SnakeTestMove",
"SnakeTestRandomFoodPosition",
"SnakeTestReset",
"SnakeTestEatFood",
"SnakeTest"
] | class Snake:
def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position):
"""
Initialize the length of the snake, screen width, screen height, block size, snake head position, score, and food position.
:param SCREEN_WIDTH: int
:param SCREEN_HEIGHT: int
:param BLOCK_SIZE: int, Size of moving units
:param food_position: tuple, representing the position(x, y) of food.
"""
self.length = 1
self.SCREEN_WIDTH = SCREEN_WIDTH
self.SCREEN_HEIGHT = SCREEN_HEIGHT
self.BLOCK_SIZE = BLOCK_SIZE
self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))]
self.score = 0
self.food_position = food_position
| [
"self.BLOCK_SIZE",
"self.SCREEN_HEIGHT",
"self.SCREEN_WIDTH",
"self.food_position",
"self.length",
"self.positions",
"self.score"
] |
ClassEval_78 | import re
class SplitSentence:
"""
The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count.
"""
def split_sentences(self, sentences_string):
"""
Split a string into a list of sentences. Sentences end with . or ? and with a space after that. Please note that Mr. also end with . but are not sentences.
:param sentences_string: string, string to split
:return:list, split sentence list
>>> ss = SplitSentence()
>>> ss.split_sentences("aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?")
['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?']
"""
def count_words(self, sentence):
"""
Count the number of words in a sentence. Note that words are separated by spaces and that punctuation marks and numbers are not counted as words.
:param sentence:string, sentence to be counted, where words are separated by spaces
:return:int, number of words in the sentence
>>> ss.count_words("abc def")
2
"""
def process_text_file(self, sentences_string):
"""
Given a text, return the number of words in the longest sentence
:param sentences_string: string, undivided long sentence
:return:int, the number of words in the longest sentence
>>> ss.process_text_file("aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?")
4
""" | import unittest
class SplitSentenceTestSplitSentences(unittest.TestCase):
def test_split_sentences_1(self):
ss = SplitSentence()
lst = ss.split_sentences("aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?")
self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?'])
def test_split_sentences_2(self):
ss = SplitSentence()
lst = ss.split_sentences("Who is Mr. Smith? He is a teacher.")
self.assertEqual(lst, ['Who is Mr. Smith?', 'He is a teacher.'])
def test_split_sentences_3(self):
ss = SplitSentence()
lst = ss.split_sentences("Who is A.B.C.? He is a teacher.")
self.assertEqual(lst, ['Who is A.B.C.?', 'He is a teacher.'])
def test_split_sentences_4(self):
ss = SplitSentence()
lst = ss.split_sentences("aaa aaaa. bb bbbb bbb? cccc cccc.")
self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.'])
def test_split_sentences_5(self):
ss = SplitSentence()
lst = ss.split_sentences("aaa aaaa. bb bbbb bbb?")
self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?'])
class SplitSentenceTestCountWords(unittest.TestCase):
def test_count_words_1(self):
ss = SplitSentence()
cnt = ss.count_words("abc def")
self.assertEqual(cnt, 2)
def test_count_words_2(self):
ss = SplitSentence()
cnt = ss.count_words("abc def 1")
self.assertEqual(cnt, 2)
def test_count_words_3(self):
ss = SplitSentence()
cnt = ss.count_words("abc 1")
self.assertEqual(cnt, 1)
def test_count_words_4(self):
ss = SplitSentence()
cnt = ss.count_words("abc def bbb1")
self.assertEqual(cnt, 3)
def test_count_words_5(self):
ss = SplitSentence()
cnt = ss.count_words("abc def 111")
self.assertEqual(cnt, 2)
class SplitSentenceTestProcessTextFile(unittest.TestCase):
def test_process_text_file_1(self):
ss = SplitSentence()
cnt = ss.process_text_file("aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?")
self.assertEqual(cnt, 4)
def test_process_text_file_2(self):
ss = SplitSentence()
cnt = ss.process_text_file("Mr. Smith is a teacher. Yes.")
self.assertEqual(cnt, 5)
def test_process_text_file_3(self):
ss = SplitSentence()
cnt = ss.process_text_file("Mr. Smith is a teacher. Yes 1 2 3 4 5 6.")
self.assertEqual(cnt, 5)
def test_process_text_file_4(self):
ss = SplitSentence()
cnt = ss.process_text_file("aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc.")
self.assertEqual(cnt, 4)
def test_process_text_file_5(self):
ss = SplitSentence()
cnt = ss.process_text_file("aaa aaaa. bb bbbb bbb?")
self.assertEqual(cnt, 3)
class SplitSentenceTest(unittest.TestCase):
def test_SplitSentence(self):
ss = SplitSentence()
lst = ss.split_sentences("aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?")
self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?'])
cnt = ss.count_words("abc def")
self.assertEqual(cnt, 2)
cnt = ss.process_text_file("aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?")
self.assertEqual(cnt, 4) | import re
class SplitSentence:
def split_sentences(self, sentences_string):
sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', sentences_string)
return sentences
def count_words(self, sentence):
sentence = re.sub(r'[^a-zA-Z\s]', '', sentence)
words = sentence.split()
return len(words)
def process_text_file(self, sentences_string):
sentences = self.split_sentences(sentences_string)
max_count = 0
for sentence in sentences:
count = self.count_words(sentence)
if count > max_count:
max_count = count
return max_count | [
"import re"
] | """
The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count.
"""
| [
{
"method_name": "split_sentences",
"method_description": "def split_sentences(self, sentences_string):\n \"\"\"\n Split a string into a list of sentences. Sentences end with . or ? and with a space after that. Please note that Mr. also end with . but are not sentences.\n :param sentences_string: string, string to split\n :return:list, split sentence list\n >>> ss = SplitSentence()\n >>> ss.split_sentences(\"aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?\")\n ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?']\n \"\"\"",
"test_class": "SplitSentenceTestSplitSentences",
"test_code": "class SplitSentenceTestSplitSentences(unittest.TestCase):\n def test_split_sentences_1(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?\")\n self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?'])\n\n def test_split_sentences_2(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"Who is Mr. Smith? He is a teacher.\")\n self.assertEqual(lst, ['Who is Mr. Smith?', 'He is a teacher.'])\n\n def test_split_sentences_3(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"Who is A.B.C.? He is a teacher.\")\n self.assertEqual(lst, ['Who is A.B.C.?', 'He is a teacher.'])\n\n def test_split_sentences_4(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"aaa aaaa. bb bbbb bbb? cccc cccc.\")\n self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.'])\n\n def test_split_sentences_5(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"aaa aaaa. bb bbbb bbb?\")\n self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?'])",
"solution_code": "def split_sentences(self, sentences_string):\n sentences = re.split(r'(?<!\\w\\.\\w.)(?<![A-Z][a-z]\\.)(?<=\\.|\\?)\\s', sentences_string)\n return sentences",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"re"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "count_words",
"method_description": "def count_words(self, sentence):\n \"\"\"\n Count the number of words in a sentence. Note that words are separated by spaces and that punctuation marks and numbers are not counted as words.\n :param sentence:string, sentence to be counted, where words are separated by spaces\n :return:int, number of words in the sentence\n >>> ss.count_words(\"abc def\")\n 2\n \"\"\"",
"test_class": "SplitSentenceTestCountWords",
"test_code": "class SplitSentenceTestCountWords(unittest.TestCase):\n def test_count_words_1(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc def\")\n self.assertEqual(cnt, 2)\n\n def test_count_words_2(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc def 1\")\n self.assertEqual(cnt, 2)\n\n def test_count_words_3(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc 1\")\n self.assertEqual(cnt, 1)\n\n def test_count_words_4(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc def bbb1\")\n self.assertEqual(cnt, 3)\n\n def test_count_words_5(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc def 111\")\n self.assertEqual(cnt, 2)",
"solution_code": "def count_words(self, sentence):\n sentence = re.sub(r'[^a-zA-Z\\s]', '', sentence)\n words = sentence.split()\n return len(words)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"re"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "process_text_file",
"method_description": "def process_text_file(self, sentences_string):\n \"\"\"\n Given a text, return the number of words in the longest sentence\n :param sentences_string: string, undivided long sentence\n :return:int, the number of words in the longest sentence\n >>> ss.process_text_file(\"aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?\")\n 4\n \"\"\"",
"test_class": "SplitSentenceTestProcessTextFile",
"test_code": "class SplitSentenceTestProcessTextFile(unittest.TestCase):\n def test_process_text_file_1(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?\")\n self.assertEqual(cnt, 4)\n\n def test_process_text_file_2(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"Mr. Smith is a teacher. Yes.\")\n self.assertEqual(cnt, 5)\n\n def test_process_text_file_3(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"Mr. Smith is a teacher. Yes 1 2 3 4 5 6.\")\n self.assertEqual(cnt, 5)\n\n def test_process_text_file_4(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc.\")\n self.assertEqual(cnt, 4)\n\n def test_process_text_file_5(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"aaa aaaa. bb bbbb bbb?\")\n self.assertEqual(cnt, 3)",
"solution_code": "def process_text_file(self, sentences_string):\n sentences = self.split_sentences(sentences_string)\n max_count = 0\n for sentence in sentences:\n count = self.count_words(sentence)\n if count > max_count:\n max_count = count\n\n return max_count",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"split_sentences",
"count_words"
]
}
}
] | SplitSentence | [
"SplitSentenceTestSplitSentences",
"SplitSentenceTestCountWords",
"SplitSentenceTestProcessTextFile",
"SplitSentenceTest"
] | class SplitSentence:
| [] |
ClassEval_79 | class SQLGenerator:
"""
This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE.
"""
def __init__(self, table_name):
"""
Initialize the table name.
:param table_name: str
"""
self.table_name = table_name
def select(self, fields=None, condition=None):
"""
Generates a SELECT SQL statement based on the specified fields and conditions.
:param fields: list, optional. Default is None. The list of fields to be queried.
:param condition: str, optional. Default is None. The condition expression for the query.
:return: str. The generated SQL statement.
>>> sql = SQLGenerator('table1')
>>> sql.select(['field1', 'field2'], 'filed3 = value1')
'SELECT field1, field2 FROM table1 WHERE filed3 = value1;'
"""
def insert(self, data):
"""
Generates an INSERT SQL statement based on the given data.
:param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values.
:return: str. The generated SQL statement.
>>> sql.insert({'key1': 'value1', 'key2': 'value2'})
"INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');"
"""
def update(self, data, condition):
"""
Generates an UPDATE SQL statement based on the given data and condition.
:param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values.
:param condition: str. The condition expression for the update.
:return: str. The generated SQL statement.
>>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, "field3 = value1")
"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;"
"""
def delete(self, condition):
"""
Generates a DELETE SQL statement based on the given condition.
:param condition: str. The condition expression for the delete.
:return: str. The generated SQL statement.
>>> sql.delete("field1 = value1")
'DELETE FROM table1 WHERE field1 = value1;'
"""
def select_female_under_age(self, age):
"""
Generates a SQL statement to select females under a specified age.
:param age: int. The specified age.
:return: str. The generated SQL statement.
>>> sql.select_female_under_age(30)
"SELECT * FROM table1 WHERE age < 30 AND gender = 'female';"
"""
def select_by_age_range(self, min_age, max_age):
"""
Generates a SQL statement to select records within a specified age range.
:param min_age: int. The minimum age.
:param max_age: int. The maximum age.
:return: str. The generated SQL statement.
>>> sql.select_by_age_range(20, 30)
'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;'
""" | import unittest
class SQLGeneratorTestSelect(unittest.TestCase):
def test_select_1(self):
sql = SQLGenerator('table1')
result = sql.select(['field1'], "field2 = value1")
self.assertEqual(result, "SELECT field1 FROM table1 WHERE field2 = value1;")
def test_select_2(self):
sql = SQLGenerator('table1')
result = sql.select(['field1', 'field2'], "field3 = value1")
self.assertEqual(result, "SELECT field1, field2 FROM table1 WHERE field3 = value1;")
def test_select_3(self):
sql = SQLGenerator('table1')
result = sql.select(['field1, field2'], "field3 = value1")
self.assertEqual(result, "SELECT field1, field2 FROM table1 WHERE field3 = value1;")
def test_select_4(self):
sql = SQLGenerator('table1')
result = sql.select(['field1, field2'], "field3 = value1, field4 = value2")
self.assertEqual(result, "SELECT field1, field2 FROM table1 WHERE field3 = value1, field4 = value2;")
def test_select_5(self):
sql = SQLGenerator('table1')
result = sql.select(['field1'], "field2 = value1, field3 = value2")
self.assertEqual(result, "SELECT field1 FROM table1 WHERE field2 = value1, field3 = value2;")
def test_select_6(self):
sql = SQLGenerator('table1')
result = sql.select(['field1'])
self.assertEqual(result, "SELECT field1 FROM table1;")
class SQLGeneratorTestInsert(unittest.TestCase):
def test_insert(self):
sql = SQLGenerator('table1')
result = sql.insert({'field1': 'value1', 'field2': 'value2'})
self.assertEqual(result, "INSERT INTO table1 (field1, field2) VALUES ('value1', 'value2');")
def test_insert_2(self):
sql = SQLGenerator('table1')
result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3'})
self.assertEqual(result, "INSERT INTO table1 (field1, field2, field3) VALUES ('value1', 'value2', 'value3');")
def test_insert_3(self):
sql = SQLGenerator('table1')
result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3', 'field4': 'value4'})
self.assertEqual(result,
"INSERT INTO table1 (field1, field2, field3, field4) VALUES ('value1', 'value2', 'value3', 'value4');")
def test_insert_4(self):
sql = SQLGenerator('table1')
result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3', 'field4': 'value4',
'field5': 'value5'})
self.assertEqual(result,
"INSERT INTO table1 (field1, field2, field3, field4, field5) VALUES ('value1', 'value2', 'value3', 'value4', 'value5');")
def test_insert_5(self):
sql = SQLGenerator('table1')
result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3', 'field4': 'value4',
'field5': 'value5', 'field6': 'value6'})
self.assertEqual(result,
"INSERT INTO table1 (field1, field2, field3, field4, field5, field6) VALUES ('value1', 'value2', 'value3', 'value4', 'value5', 'value6');")
class SQLGeneratorTestUpdate(unittest.TestCase):
def test_update(self):
sql = SQLGenerator('table1')
result = sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, "field3 = value1")
self.assertEqual(result,
"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;")
def test_update_2(self):
sql = SQLGenerator('table1')
result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3'},
"field4 = value1")
self.assertEqual(result,
"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3' WHERE field4 = value1;")
def test_update_3(self):
sql = SQLGenerator('table1')
result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3',
'field4': 'new_value4'}, "field5 = value1")
self.assertEqual(result,
"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3', field4 = 'new_value4' WHERE field5 = value1;")
def test_update_4(self):
sql = SQLGenerator('table1')
result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3',
'field4': 'new_value4', 'field5': 'new_value5'}, "field6 = value1")
self.assertEqual(result,
"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3', field4 = 'new_value4', field5 = 'new_value5' WHERE field6 = value1;")
def test_update_5(self):
sql = SQLGenerator('table1')
result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3',
'field4': 'new_value4', 'field5': 'new_value5', 'field6': 'new_value6'},
"field7 = value1")
self.assertEqual(result,
"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3', field4 = 'new_value4', field5 = 'new_value5', field6 = 'new_value6' WHERE field7 = value1;")
class SQLGeneratorTestDelete(unittest.TestCase):
def test_delete(self):
sql = SQLGenerator('table1')
result = sql.delete("field1 = value1")
self.assertEqual(result, "DELETE FROM table1 WHERE field1 = value1;")
def test_delete_2(self):
sql = SQLGenerator('table1')
result = sql.delete("field1 = value1 AND field2 = value2")
self.assertEqual(result, "DELETE FROM table1 WHERE field1 = value1 AND field2 = value2;")
def test_delete_3(self):
sql = SQLGenerator('table1')
result = sql.delete("field1 = value1 AND field2 = value2 AND field3 = value3")
self.assertEqual(result, "DELETE FROM table1 WHERE field1 = value1 AND field2 = value2 AND field3 = value3;")
def test_delete_4(self):
sql = SQLGenerator('table1')
result = sql.delete("field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4")
self.assertEqual(result,
"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4;")
def test_delete_5(self):
sql = SQLGenerator('table1')
result = sql.delete("field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4 AND field5 = value5")
self.assertEqual(result,
"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4 AND field5 = value5;")
class SQLGeneratorTestSelectFemaleUnderAge(unittest.TestCase):
def test_select_female_under_age(self):
sql = SQLGenerator('table1')
result = sql.select_female_under_age(30)
self.assertEqual(result, "SELECT * FROM table1 WHERE age < 30 AND gender = 'female';")
def test_select_female_under_age_2(self):
sql = SQLGenerator('table1')
result = sql.select_female_under_age(40)
self.assertEqual(result,"SELECT * FROM table1 WHERE age < 40 AND gender = 'female';")
def test_select_female_under_age_3(self):
sql = SQLGenerator('table1')
result = sql.select_female_under_age(20)
self.assertEqual(result,"SELECT * FROM table1 WHERE age < 20 AND gender = 'female';")
def test_select_female_under_age_4(self):
sql = SQLGenerator('table1')
result = sql.select_female_under_age(10)
self.assertEqual(result,"SELECT * FROM table1 WHERE age < 10 AND gender = 'female';")
def test_select_female_under_age_5(self):
sql = SQLGenerator('table1')
result = sql.select_female_under_age(50)
self.assertEqual(result,"SELECT * FROM table1 WHERE age < 50 AND gender = 'female';")
class SQLGeneratorTestSelectByAgeRange(unittest.TestCase):
def test_select_by_age_range(self):
sql = SQLGenerator('table1')
result = sql.select_by_age_range(20, 30)
self.assertEqual(result, "SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;")
def test_select_by_age_range_2(self):
sql = SQLGenerator('table1')
result = sql.select_by_age_range(10, 20)
self.assertEqual(result, "SELECT * FROM table1 WHERE age BETWEEN 10 AND 20;")
def test_select_by_age_range_3(self):
sql = SQLGenerator('table1')
result = sql.select_by_age_range(30, 40)
self.assertEqual(result, "SELECT * FROM table1 WHERE age BETWEEN 30 AND 40;")
def test_select_by_age_range_4(self):
sql = SQLGenerator('table1')
result = sql.select_by_age_range(40, 50)
self.assertEqual(result, "SELECT * FROM table1 WHERE age BETWEEN 40 AND 50;")
def test_select_by_age_range_5(self):
sql = SQLGenerator('table1')
result = sql.select_by_age_range(50, 60)
self.assertEqual(result, "SELECT * FROM table1 WHERE age BETWEEN 50 AND 60;")
class SQLGeneratorTestMain(unittest.TestCase):
def test_main(self):
sql = SQLGenerator('table1')
self.assertEqual(sql.select(['field1', 'field2'], "field3 = value1"),
"SELECT field1, field2 FROM table1 WHERE field3 = value1;")
self.assertEqual(sql.insert({'field1': 'value1', 'field2': 'value2'}),
"INSERT INTO table1 (field1, field2) VALUES ('value1', 'value2');")
self.assertEqual(sql.update({'field1': 'new_value1', 'field2': 'new_value2'},
"field3 = value1"),
"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;")
self.assertEqual(sql.delete("field1 = value1"),
"DELETE FROM table1 WHERE field1 = value1;")
self.assertEqual(sql.select_female_under_age(30),
"SELECT * FROM table1 WHERE age < 30 AND gender = 'female';")
self.assertEqual(sql.select_by_age_range(20, 30),
"SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;") | class SQLGenerator:
def __init__(self, table_name):
self.table_name = table_name
def select(self, fields=None, condition=None):
if fields is None:
fields = "*"
else:
fields = ", ".join(fields)
sql = f"SELECT {fields} FROM {self.table_name}"
if condition is not None:
sql += f" WHERE {condition}"
return sql + ";"
def insert(self, data):
fields = ", ".join(data.keys())
values = ", ".join([f"'{value}'" for value in data.values()])
sql = f"INSERT INTO {self.table_name} ({fields}) VALUES ({values})"
return sql + ";"
def update(self, data, condition):
set_clause = ", ".join([f"{field} = '{value}'" for field, value in data.items()])
sql = f"UPDATE {self.table_name} SET {set_clause} WHERE {condition}"
return sql + ";"
def delete(self, condition):
sql = f"DELETE FROM {self.table_name} WHERE {condition}"
return sql + ";"
def select_female_under_age(self, age):
condition = f"age < {age} AND gender = 'female'"
return self.select(condition=condition)
def select_by_age_range(self, min_age, max_age):
condition = f"age BETWEEN {min_age} AND {max_age}"
return self.select(condition=condition) | [] | """
This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE.
"""
| [
{
"method_name": "select",
"method_description": "def select(self, fields=None, condition=None):\n \"\"\"\n Generates a SELECT SQL statement based on the specified fields and conditions.\n :param fields: list, optional. Default is None. The list of fields to be queried.\n :param condition: str, optional. Default is None. The condition expression for the query.\n :return: str. The generated SQL statement.\n >>> sql = SQLGenerator('table1')\n >>> sql.select(['field1', 'field2'], 'filed3 = value1')\n 'SELECT field1, field2 FROM table1 WHERE filed3 = value1;'\n \"\"\"",
"test_class": "SQLGeneratorTestSelect",
"test_code": "class SQLGeneratorTestSelect(unittest.TestCase):\n def test_select_1(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1'], \"field2 = value1\")\n self.assertEqual(result, \"SELECT field1 FROM table1 WHERE field2 = value1;\")\n\n def test_select_2(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1', 'field2'], \"field3 = value1\")\n self.assertEqual(result, \"SELECT field1, field2 FROM table1 WHERE field3 = value1;\")\n\n def test_select_3(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1, field2'], \"field3 = value1\")\n self.assertEqual(result, \"SELECT field1, field2 FROM table1 WHERE field3 = value1;\")\n\n def test_select_4(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1, field2'], \"field3 = value1, field4 = value2\")\n self.assertEqual(result, \"SELECT field1, field2 FROM table1 WHERE field3 = value1, field4 = value2;\")\n\n def test_select_5(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1'], \"field2 = value1, field3 = value2\")\n self.assertEqual(result, \"SELECT field1 FROM table1 WHERE field2 = value1, field3 = value2;\")\n\n def test_select_6(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1'])\n self.assertEqual(result, \"SELECT field1 FROM table1;\")",
"solution_code": "def select(self, fields=None, condition=None):\n if fields is None:\n fields = \"*\"\n else:\n fields = \", \".join(fields)\n sql = f\"SELECT {fields} FROM {self.table_name}\"\n if condition is not None:\n sql += f\" WHERE {condition}\"\n return sql + \";\"",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.table_name"
],
"method_dependencies": []
}
},
{
"method_name": "insert",
"method_description": "def insert(self, data):\n \"\"\"\n Generates an INSERT SQL statement based on the given data.\n :param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values.\n :return: str. The generated SQL statement.\n >>> sql.insert({'key1': 'value1', 'key2': 'value2'})\n \"INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');\"\n \"\"\"",
"test_class": "SQLGeneratorTestInsert",
"test_code": "class SQLGeneratorTestInsert(unittest.TestCase):\n def test_insert(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2'})\n self.assertEqual(result, \"INSERT INTO table1 (field1, field2) VALUES ('value1', 'value2');\")\n\n def test_insert_2(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3'})\n self.assertEqual(result, \"INSERT INTO table1 (field1, field2, field3) VALUES ('value1', 'value2', 'value3');\")\n\n def test_insert_3(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3', 'field4': 'value4'})\n self.assertEqual(result,\n \"INSERT INTO table1 (field1, field2, field3, field4) VALUES ('value1', 'value2', 'value3', 'value4');\")\n\n def test_insert_4(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3', 'field4': 'value4',\n 'field5': 'value5'})\n self.assertEqual(result,\n \"INSERT INTO table1 (field1, field2, field3, field4, field5) VALUES ('value1', 'value2', 'value3', 'value4', 'value5');\")\n\n def test_insert_5(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3', 'field4': 'value4',\n 'field5': 'value5', 'field6': 'value6'})\n self.assertEqual(result,\n \"INSERT INTO table1 (field1, field2, field3, field4, field5, field6) VALUES ('value1', 'value2', 'value3', 'value4', 'value5', 'value6');\")",
"solution_code": "def insert(self, data):\n fields = \", \".join(data.keys())\n values = \", \".join([f\"'{value}'\" for value in data.values()])\n sql = f\"INSERT INTO {self.table_name} ({fields}) VALUES ({values})\"\n return sql + \";\"",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.table_name"
],
"method_dependencies": []
}
},
{
"method_name": "update",
"method_description": "def update(self, data, condition):\n \"\"\"\n Generates an UPDATE SQL statement based on the given data and condition.\n :param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values.\n :param condition: str. The condition expression for the update.\n :return: str. The generated SQL statement.\n >>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, \"field3 = value1\")\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;\"\n \"\"\"",
"test_class": "SQLGeneratorTestUpdate",
"test_code": "class SQLGeneratorTestUpdate(unittest.TestCase):\n def test_update(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, \"field3 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;\")\n\n def test_update_2(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3'},\n \"field4 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3' WHERE field4 = value1;\")\n\n def test_update_3(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3',\n 'field4': 'new_value4'}, \"field5 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3', field4 = 'new_value4' WHERE field5 = value1;\")\n\n def test_update_4(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3',\n 'field4': 'new_value4', 'field5': 'new_value5'}, \"field6 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3', field4 = 'new_value4', field5 = 'new_value5' WHERE field6 = value1;\")\n\n def test_update_5(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3',\n 'field4': 'new_value4', 'field5': 'new_value5', 'field6': 'new_value6'},\n \"field7 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3', field4 = 'new_value4', field5 = 'new_value5', field6 = 'new_value6' WHERE field7 = value1;\")",
"solution_code": "def update(self, data, condition):\n set_clause = \", \".join([f\"{field} = '{value}'\" for field, value in data.items()])\n sql = f\"UPDATE {self.table_name} SET {set_clause} WHERE {condition}\"\n return sql + \";\"",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.table_name"
],
"method_dependencies": []
}
},
{
"method_name": "delete",
"method_description": "def delete(self, condition):\n \"\"\"\n Generates a DELETE SQL statement based on the given condition.\n :param condition: str. The condition expression for the delete.\n :return: str. The generated SQL statement.\n >>> sql.delete(\"field1 = value1\")\n 'DELETE FROM table1 WHERE field1 = value1;'\n \"\"\"",
"test_class": "SQLGeneratorTestDelete",
"test_code": "class SQLGeneratorTestDelete(unittest.TestCase):\n def test_delete(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1\")\n self.assertEqual(result, \"DELETE FROM table1 WHERE field1 = value1;\")\n\n def test_delete_2(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1 AND field2 = value2\")\n self.assertEqual(result, \"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2;\")\n\n def test_delete_3(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1 AND field2 = value2 AND field3 = value3\")\n self.assertEqual(result, \"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2 AND field3 = value3;\")\n\n def test_delete_4(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4\")\n self.assertEqual(result,\n \"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4;\")\n\n def test_delete_5(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4 AND field5 = value5\")\n self.assertEqual(result,\n \"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4 AND field5 = value5;\")",
"solution_code": "def delete(self, condition):\n sql = f\"DELETE FROM {self.table_name} WHERE {condition}\"\n return sql + \";\"",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.table_name"
],
"method_dependencies": []
}
},
{
"method_name": "select_female_under_age",
"method_description": "def select_female_under_age(self, age):\n \"\"\"\n Generates a SQL statement to select females under a specified age.\n :param age: int. The specified age.\n :return: str. The generated SQL statement.\n >>> sql.select_female_under_age(30)\n \"SELECT * FROM table1 WHERE age < 30 AND gender = 'female';\"\n \"\"\"",
"test_class": "SQLGeneratorTestSelectFemaleUnderAge",
"test_code": "class SQLGeneratorTestSelectFemaleUnderAge(unittest.TestCase):\n def test_select_female_under_age(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(30)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age < 30 AND gender = 'female';\")\n\n def test_select_female_under_age_2(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(40)\n self.assertEqual(result,\"SELECT * FROM table1 WHERE age < 40 AND gender = 'female';\")\n\n def test_select_female_under_age_3(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(20)\n self.assertEqual(result,\"SELECT * FROM table1 WHERE age < 20 AND gender = 'female';\")\n\n def test_select_female_under_age_4(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(10)\n self.assertEqual(result,\"SELECT * FROM table1 WHERE age < 10 AND gender = 'female';\")\n\n def test_select_female_under_age_5(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(50)\n self.assertEqual(result,\"SELECT * FROM table1 WHERE age < 50 AND gender = 'female';\")",
"solution_code": "def select_female_under_age(self, age):\n condition = f\"age < {age} AND gender = 'female'\"\n return self.select(condition=condition)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"select"
]
}
},
{
"method_name": "select_by_age_range",
"method_description": "def select_by_age_range(self, min_age, max_age):\n \"\"\"\n Generates a SQL statement to select records within a specified age range.\n :param min_age: int. The minimum age.\n :param max_age: int. The maximum age.\n :return: str. The generated SQL statement.\n >>> sql.select_by_age_range(20, 30)\n 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;'\n \"\"\"",
"test_class": "SQLGeneratorTestSelectByAgeRange",
"test_code": "class SQLGeneratorTestSelectByAgeRange(unittest.TestCase):\n def test_select_by_age_range(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(20, 30)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;\")\n\n def test_select_by_age_range_2(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(10, 20)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 10 AND 20;\")\n\n def test_select_by_age_range_3(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(30, 40)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 30 AND 40;\")\n\n def test_select_by_age_range_4(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(40, 50)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 40 AND 50;\")\n\n def test_select_by_age_range_5(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(50, 60)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 50 AND 60;\")",
"solution_code": "def select_by_age_range(self, min_age, max_age):\n condition = f\"age BETWEEN {min_age} AND {max_age}\"\n return self.select(condition=condition)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"select"
]
}
}
] | SQLGenerator | [
"SQLGeneratorTestSelect",
"SQLGeneratorTestInsert",
"SQLGeneratorTestUpdate",
"SQLGeneratorTestDelete",
"SQLGeneratorTestSelectFemaleUnderAge",
"SQLGeneratorTestSelectByAgeRange",
"SQLGeneratorTestMain"
] | class SQLGenerator:
def __init__(self, table_name):
"""
Initialize the table name.
:param table_name: str
"""
self.table_name = table_name
| [
"self.table_name"
] |
ClassEval_80 | class SQLQueryBuilder:
"""
This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements.
"""
@staticmethod
def select(table, columns='*', where=None):
"""
Generate the SELECT SQL statement from the given parameters.
:param table: str, the query table in database.
:param columns: list of str, ['col1', 'col2'].
:param where: dict, {key1: value1, key2: value2 ...}. The query condition.
return query: str, the SQL query statement.
>>> SQLQueryBuilder.select('table1', columns = ["col1","col2"], where = {"age": 15})
"SELECT col1, col2 FROM table1 WHERE age='15'"
"""
@staticmethod
def insert(table, data):
"""
Generate the INSERT SQL statement from the given parameters.
:param table: str, the table to be inserted in database.
:param data: dict, the key and value in SQL insert statement
:return query: str, the SQL insert statement.
>>> SQLQueryBuilder.insert('table1', {'name': 'Test', 'age': 14})
"INSERT INTO table1 (name, age) VALUES ('Test', '14')"
"""
@staticmethod
def delete(table, where=None):
"""
Generate the DELETE SQL statement from the given parameters.
:param table: str, the table that will be excuted with DELETE operation in database
:param where: dict, {key1: value1, key2: value2 ...}. The query condition.
:return query: str, the SQL delete statement.
>>> SQLQueryBuilder.delete('table1', {'name': 'Test', 'age': 14})
"DELETE FROM table1 WHERE name='Test' AND age='14'"
"""
@staticmethod
def update(table, data, where=None):
"""
Generate the UPDATE SQL statement from the given parameters.
:param table: str, the table that will be excuted with UPDATE operation in database
:param data: dict, the key and value in SQL update statement
:param where: dict, {key1: value1, key2: value2 ...}. The query condition.
>>> SQLQueryBuilder.update('table1', {'name': 'Test2', 'age': 15}, where = {'name':'Test'})
"UPDATE table1 SET name='Test2', age='15' WHERE name='Test'"
""" | import unittest
class SQLQueryBuilderTestSelect(unittest.TestCase):
def test_select_1(self):
self.assertEqual(
SQLQueryBuilder.select('users', ["id", "name"], {'age': 30}),
"SELECT id, name FROM users WHERE age='30'"
)
def test_select_2(self):
self.assertEqual(
SQLQueryBuilder.select('students', ["id", "name"], {'age': 18}),
"SELECT id, name FROM students WHERE age='18'"
)
def test_select_3(self):
self.assertEqual(
SQLQueryBuilder.select('items', ["id", "name"], {'price': 1.0}),
"SELECT id, name FROM items WHERE price='1.0'"
)
def test_select_4(self):
self.assertEqual(
SQLQueryBuilder.select('users', ["id"], {'age': 30}),
"SELECT id FROM users WHERE age='30'"
)
def test_select_5(self):
self.assertEqual(
SQLQueryBuilder.select('users', ["name"], {'age': 30}),
"SELECT name FROM users WHERE age='30'"
)
def test_select_6(self):
self.assertEqual(
SQLQueryBuilder.select('users', ["name"]),
"SELECT name FROM users"
)
def test_select_7(self):
self.assertEqual(
SQLQueryBuilder.select('users', "*"),
"SELECT * FROM users"
)
class SQLQueryBuilderTestInsert(unittest.TestCase):
def test_insert_1(self):
self.assertEqual(
SQLQueryBuilder.insert('users', {'name': 'Tom', 'age': 30}),
"INSERT INTO users (name, age) VALUES ('Tom', '30')"
)
def test_insert_2(self):
self.assertEqual(
SQLQueryBuilder.insert('students', {'name': 'Tom', 'age': 18}),
"INSERT INTO students (name, age) VALUES ('Tom', '18')"
)
def test_insert_3(self):
self.assertEqual(
SQLQueryBuilder.insert('items', {'name': 'apple', 'price': 1.0}),
"INSERT INTO items (name, price) VALUES ('apple', '1.0')"
)
def test_insert_4(self):
self.assertEqual(
SQLQueryBuilder.insert('users', {'name': 'Tom'}),
"INSERT INTO users (name) VALUES ('Tom')"
)
def test_insert_5(self):
self.assertEqual(
SQLQueryBuilder.insert('users', {'name': 'Tom', 'age': 30, 'region': 'USA'}),
"INSERT INTO users (name, age, region) VALUES ('Tom', '30', 'USA')"
)
class SQLQueryBuilderTestDetele(unittest.TestCase):
def test_delete_1(self):
self.assertEqual(
SQLQueryBuilder.delete('users', {'name': 'Tom'}),
"DELETE FROM users WHERE name='Tom'"
)
def test_delete_2(self):
self.assertEqual(
SQLQueryBuilder.delete('students', {'name': 'Tom'}),
"DELETE FROM students WHERE name='Tom'"
)
def test_delete_3(self):
self.assertEqual(
SQLQueryBuilder.delete('items', {'name': 'apple'}),
"DELETE FROM items WHERE name='apple'"
)
def test_delete_4(self):
self.assertEqual(
SQLQueryBuilder.delete('items', {'name': 'aaa'}),
"DELETE FROM items WHERE name='aaa'"
)
def test_delete_5(self):
self.assertEqual(
SQLQueryBuilder.delete('items', {'name': 'bbb'}),
"DELETE FROM items WHERE name='bbb'"
)
def test_delete_6(self):
self.assertEqual(
SQLQueryBuilder.delete('items'),
"DELETE FROM items"
)
class SQLQueryBuilderTestUpdate(unittest.TestCase):
def test_update_1(self):
self.assertEqual(
SQLQueryBuilder.update('users', {'age': 35}, {'name': 'Tom'}),
"UPDATE users SET age='35' WHERE name='Tom'"
)
def test_update_2(self):
self.assertEqual(
SQLQueryBuilder.update('students', {'age': 18}, {'name': 'Tom'}),
"UPDATE students SET age='18' WHERE name='Tom'"
)
def test_update_3(self):
self.assertEqual(
SQLQueryBuilder.update('items', {'price': 1.0}, {'name': 'apple'}),
"UPDATE items SET price='1.0' WHERE name='apple'"
)
def test_update_4(self):
self.assertEqual(
SQLQueryBuilder.update('items', {'price': 1.0}, {'name': 'aaa'}),
"UPDATE items SET price='1.0' WHERE name='aaa'"
)
def test_update_5(self):
self.assertEqual(
SQLQueryBuilder.update('items', {'price': 1.0}, {'name': 'bbb'}),
"UPDATE items SET price='1.0' WHERE name='bbb'"
)
def test_update_6(self):
self.assertEqual(
SQLQueryBuilder.update('items', {'price': 1.0}),
"UPDATE items SET price='1.0'"
)
class SQLQueryBuilderTestMain(unittest.TestCase):
def test_main(self):
self.assertEqual(
SQLQueryBuilder.select('users', ["id", "name"], {'age': 30}),
"SELECT id, name FROM users WHERE age='30'"
)
self.assertEqual(
SQLQueryBuilder.insert('users', {'name': 'Tom', 'age': 30}),
"INSERT INTO users (name, age) VALUES ('Tom', '30')"
)
self.assertEqual(
SQLQueryBuilder.delete('users', {'name': 'Tom'}),
"DELETE FROM users WHERE name='Tom'"
)
self.assertEqual(
SQLQueryBuilder.update('users', {'age': 35}, {'name': 'Tom'}),
"UPDATE users SET age='35' WHERE name='Tom'"
) | class SQLQueryBuilder:
@staticmethod
def select(table, columns='*', where=None):
if columns != '*':
columns = ', '.join(columns)
query = f"SELECT {columns} FROM {table}"
if where:
query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items())
return query
@staticmethod
def insert(table, data):
keys = ', '.join(data.keys())
values = ', '.join(f"'{v}'" for v in data.values())
return f"INSERT INTO {table} ({keys}) VALUES ({values})"
@staticmethod
def delete(table, where=None):
query = f"DELETE FROM {table}"
if where:
query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items())
return query
@staticmethod
def update(table, data, where=None):
update_str = ', '.join(f"{k}='{v}'" for k, v in data.items())
query = f"UPDATE {table} SET {update_str}"
if where:
query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items())
return query | [] | """
This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements.
"""
| [
{
"method_name": "select",
"method_description": "def select(table, columns='*', where=None):\n \"\"\"\n Generate the SELECT SQL statement from the given parameters.\n :param table: str, the query table in database.\n :param columns: list of str, ['col1', 'col2'].\n :param where: dict, {key1: value1, key2: value2 ...}. The query condition.\n return query: str, the SQL query statement.\n >>> SQLQueryBuilder.select('table1', columns = [\"col1\",\"col2\"], where = {\"age\": 15})\n \"SELECT col1, col2 FROM table1 WHERE age='15'\"\n \"\"\"",
"test_class": "SQLQueryBuilderTestSelect",
"test_code": "class SQLQueryBuilderTestSelect(unittest.TestCase):\n def test_select_1(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', [\"id\", \"name\"], {'age': 30}),\n \"SELECT id, name FROM users WHERE age='30'\"\n )\n\n def test_select_2(self):\n self.assertEqual(\n SQLQueryBuilder.select('students', [\"id\", \"name\"], {'age': 18}),\n \"SELECT id, name FROM students WHERE age='18'\"\n )\n\n def test_select_3(self):\n self.assertEqual(\n SQLQueryBuilder.select('items', [\"id\", \"name\"], {'price': 1.0}),\n \"SELECT id, name FROM items WHERE price='1.0'\"\n )\n\n def test_select_4(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', [\"id\"], {'age': 30}),\n \"SELECT id FROM users WHERE age='30'\"\n )\n\n def test_select_5(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', [\"name\"], {'age': 30}),\n \"SELECT name FROM users WHERE age='30'\"\n )\n\n def test_select_6(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', [\"name\"]),\n \"SELECT name FROM users\"\n )\n\n def test_select_7(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', \"*\"),\n \"SELECT * FROM users\"\n )",
"solution_code": "def select(table, columns='*', where=None):\n if columns != '*':\n columns = ', '.join(columns)\n query = f\"SELECT {columns} FROM {table}\"\n if where:\n query += \" WHERE \" + ' AND '.join(f\"{k}='{v}'\" for k, v in where.items())\n return query",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "insert",
"method_description": "@staticmethod\n def insert(table, data):\n \"\"\"\n Generate the INSERT SQL statement from the given parameters.\n :param table: str, the table to be inserted in database.\n :param data: dict, the key and value in SQL insert statement\n :return query: str, the SQL insert statement.\n >>> SQLQueryBuilder.insert('table1', {'name': 'Test', 'age': 14})\n \"INSERT INTO table1 (name, age) VALUES ('Test', '14')\"\n \"\"\"",
"test_class": "SQLQueryBuilderTestInsert",
"test_code": "class SQLQueryBuilderTestInsert(unittest.TestCase):\n def test_insert_1(self):\n self.assertEqual(\n SQLQueryBuilder.insert('users', {'name': 'Tom', 'age': 30}),\n \"INSERT INTO users (name, age) VALUES ('Tom', '30')\"\n )\n\n def test_insert_2(self):\n self.assertEqual(\n SQLQueryBuilder.insert('students', {'name': 'Tom', 'age': 18}),\n \"INSERT INTO students (name, age) VALUES ('Tom', '18')\"\n )\n\n def test_insert_3(self):\n self.assertEqual(\n SQLQueryBuilder.insert('items', {'name': 'apple', 'price': 1.0}),\n \"INSERT INTO items (name, price) VALUES ('apple', '1.0')\"\n )\n\n def test_insert_4(self):\n self.assertEqual(\n SQLQueryBuilder.insert('users', {'name': 'Tom'}),\n \"INSERT INTO users (name) VALUES ('Tom')\"\n )\n\n def test_insert_5(self):\n self.assertEqual(\n SQLQueryBuilder.insert('users', {'name': 'Tom', 'age': 30, 'region': 'USA'}),\n \"INSERT INTO users (name, age, region) VALUES ('Tom', '30', 'USA')\"\n )",
"solution_code": "@staticmethod\n def insert(table, data):\n keys = ', '.join(data.keys())\n values = ', '.join(f\"'{v}'\" for v in data.values())\n return f\"INSERT INTO {table} ({keys}) VALUES ({values})\"",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "delete",
"method_description": "@staticmethod\n def delete(table, where=None):\n \"\"\"\n Generate the DELETE SQL statement from the given parameters.\n :param table: str, the table that will be excuted with DELETE operation in database\n :param where: dict, {key1: value1, key2: value2 ...}. The query condition.\n :return query: str, the SQL delete statement.\n >>> SQLQueryBuilder.delete('table1', {'name': 'Test', 'age': 14})\n \"DELETE FROM table1 WHERE name='Test' AND age='14'\"\n \"\"\"",
"test_class": "SQLQueryBuilderTestDetele",
"test_code": "class SQLQueryBuilderTestDetele(unittest.TestCase):\n def test_delete_1(self):\n self.assertEqual(\n SQLQueryBuilder.delete('users', {'name': 'Tom'}),\n \"DELETE FROM users WHERE name='Tom'\"\n )\n\n def test_delete_2(self):\n self.assertEqual(\n SQLQueryBuilder.delete('students', {'name': 'Tom'}),\n \"DELETE FROM students WHERE name='Tom'\"\n )\n\n def test_delete_3(self):\n self.assertEqual(\n SQLQueryBuilder.delete('items', {'name': 'apple'}),\n \"DELETE FROM items WHERE name='apple'\"\n )\n\n def test_delete_4(self):\n self.assertEqual(\n SQLQueryBuilder.delete('items', {'name': 'aaa'}),\n \"DELETE FROM items WHERE name='aaa'\"\n )\n\n def test_delete_5(self):\n self.assertEqual(\n SQLQueryBuilder.delete('items', {'name': 'bbb'}),\n \"DELETE FROM items WHERE name='bbb'\"\n )\n\n def test_delete_6(self):\n self.assertEqual(\n SQLQueryBuilder.delete('items'),\n \"DELETE FROM items\"\n )",
"solution_code": "@staticmethod\n def delete(table, where=None):\n query = f\"DELETE FROM {table}\"\n if where:\n query += \" WHERE \" + ' AND '.join(f\"{k}='{v}'\" for k, v in where.items())\n return query",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "update",
"method_description": "@staticmethod\n def update(table, data, where=None):\n \"\"\"\n Generate the UPDATE SQL statement from the given parameters.\n :param table: str, the table that will be excuted with UPDATE operation in database\n :param data: dict, the key and value in SQL update statement\n :param where: dict, {key1: value1, key2: value2 ...}. The query condition.\n >>> SQLQueryBuilder.update('table1', {'name': 'Test2', 'age': 15}, where = {'name':'Test'})\n \"UPDATE table1 SET name='Test2', age='15' WHERE name='Test'\"\n \"\"\"",
"test_class": "SQLQueryBuilderTestUpdate",
"test_code": "class SQLQueryBuilderTestUpdate(unittest.TestCase):\n def test_update_1(self):\n self.assertEqual(\n SQLQueryBuilder.update('users', {'age': 35}, {'name': 'Tom'}),\n \"UPDATE users SET age='35' WHERE name='Tom'\"\n )\n\n def test_update_2(self):\n self.assertEqual(\n SQLQueryBuilder.update('students', {'age': 18}, {'name': 'Tom'}),\n \"UPDATE students SET age='18' WHERE name='Tom'\"\n )\n\n def test_update_3(self):\n self.assertEqual(\n SQLQueryBuilder.update('items', {'price': 1.0}, {'name': 'apple'}),\n \"UPDATE items SET price='1.0' WHERE name='apple'\"\n )\n\n def test_update_4(self):\n self.assertEqual(\n SQLQueryBuilder.update('items', {'price': 1.0}, {'name': 'aaa'}),\n \"UPDATE items SET price='1.0' WHERE name='aaa'\"\n )\n\n def test_update_5(self):\n self.assertEqual(\n SQLQueryBuilder.update('items', {'price': 1.0}, {'name': 'bbb'}),\n \"UPDATE items SET price='1.0' WHERE name='bbb'\"\n )\n\n def test_update_6(self):\n self.assertEqual(\n SQLQueryBuilder.update('items', {'price': 1.0}),\n \"UPDATE items SET price='1.0'\"\n )",
"solution_code": "@staticmethod\n def update(table, data, where=None):\n update_str = ', '.join(f\"{k}='{v}'\" for k, v in data.items())\n query = f\"UPDATE {table} SET {update_str}\"\n if where:\n query += \" WHERE \" + ' AND '.join(f\"{k}='{v}'\" for k, v in where.items())\n return query",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | SQLQueryBuilder | [
"SQLQueryBuilderTestSelect",
"SQLQueryBuilderTestInsert",
"SQLQueryBuilderTestDetele",
"SQLQueryBuilderTestUpdate",
"SQLQueryBuilderTestMain"
] | class SQLQueryBuilder:
| [] |
ClassEval_81 | import math
class Statistics3:
"""
This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics.
"""
@staticmethod
def median(data):
"""
calculates the median of the given list.
:param data: the given list, list.
:return: the median of the given list, float.
>>> statistics3 = Statistics3()
>>> statistics3.median([1, 2, 3, 4])
2.5
"""
@staticmethod
def mode(data):
"""
calculates the mode of the given list.
:param data: the given list, list.
:return: the mode of the given list, list.
>>> statistics3 = Statistics3()
>>> statistics3.mode([1, 2, 3, 3])
[3]
"""
@staticmethod
def correlation(x, y):
"""
calculates the correlation of the given list.
:param x: the given list, list.
:param y: the given list, list.
:return: the correlation of the given list, float.
>>> statistics3 = Statistics3()
>>> statistics3.correlation([1, 2, 3], [4, 5, 6])
1.0
"""
@staticmethod
def mean(data):
"""
calculates the mean of the given list.
:param data: the given list, list.
:return: the mean of the given list, float.
>>> statistics3 = Statistics3()
>>> statistics3.mean([1, 2, 3])
2.0
"""
@staticmethod
def correlation_matrix(data):
"""
calculates the correlation matrix of the given list.
:param data: the given list, list.
:return: the correlation matrix of the given list, list.
>>> statistics3 = Statistics3()
>>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
"""
@staticmethod
def standard_deviation(data):
"""
calculates the standard deviation of the given list.
:param data: the given list, list.
:return: the standard deviation of the given list, float.
>>> statistics3 = Statistics3()
>>> statistics3.standard_deviation([1, 2, 3])
1.0
"""
@staticmethod
def z_score(data):
"""
calculates the z-score of the given list.
:param data: the given list, list.
:return: the z-score of the given list, list.
>>> statistics3 = Statistics3()
>>> statistics3.z_score([1, 2, 3, 4])
[-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225]
""" | import unittest
class Statistics3TestMedian(unittest.TestCase):
def test_median(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.median([1, 2, 3, 4]), 2.5)
def test_median_2(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.median([1, 2, 3, 4, 5]), 3)
def test_median_3(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.median([1, 2, 3, 4, 5, 6]), 3.5)
def test_median_4(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.median([1, 2, 3, 4, 5, 6, 7]), 4)
def test_median_5(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.median([1, 2, 3, 4, 5, 6, 7, 8]), 4.5)
class Statistics3TestMode(unittest.TestCase):
def test_mode(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.mode([1, 2, 3, 3]), [3])
def test_mode_2(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4]), [3, 4])
def test_mode_3(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4, 5]), [3, 4])
def test_mode_4(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4, 5, 5]), [3, 4, 5])
def test_mode_5(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4, 5, 5, 6]), [3, 4, 5])
class Statistics3TestCorrelation(unittest.TestCase):
def test_correlation(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.correlation([1, 2, 3], [4, 5, 6]), 1.0)
def test_correlation_2(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.correlation([1, 2, 3, 4], [5, 6, 7, 8]), 1.0)
def test_correlation_3(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.correlation([1, 2, 3], [1,2,3]), 1.0)
def test_correlation_4(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.correlation([1, 1,1], [2,2,2]), None)
def test_correlation_5(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.correlation([1, 1,1], [1,1,1]), None)
class Statistics3TestMean(unittest.TestCase):
def test_mean(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.mean([1, 2, 3]), 2.0)
def test_mean_2(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.mean([]), None)
def test_mean_3(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.mean([1, 1, 1]), 1.0)
def test_mean_4(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.mean([1, 1, 1, 1]), 1.0)
def test_mean_5(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.mean([1, 1, 1, 1, 1]), 1.0)
class Statistics3TestCorrelationMatrix(unittest.TestCase):
def test_correlation_matrix(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])
def test_correlation_matrix_2(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])
def test_correlation_matrix_3(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.correlation_matrix([[1, 2, 3]]), [[None, None, None], [None, None, None], [None, None, None]])
def test_correlation_matrix_4(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11,12]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])
def test_correlation_matrix_5(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11,12], [13, 14, 15]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])
class Statistics3TestStandardDeviation(unittest.TestCase):
def test_standard_deviation(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.standard_deviation([1, 2, 3]), 1.0)
def test_standard_deviation_2(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.standard_deviation([1, 1, 1]), 0.0)
def test_standard_deviation_3(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.standard_deviation([1, 1]), 0.0)
def test_standard_deviation_4(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.standard_deviation([1, 1, 1, 1]), 0.0)
def test_standard_deviation_5(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.standard_deviation([1, 1, 2, 1, 4]), 1.3038404810405297)
class Statistics3TestZScore(unittest.TestCase):
def test_z_score(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.z_score([1, 2, 3, 4]), [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225])
def test_z_score_2(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.z_score([1, 1, 1, 1]), None)
def test_z_score_3(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.z_score([1]),None)
def test_z_score_4(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.z_score([1, 1, 2, 3]), [-0.7833494518006403,-0.7833494518006403,0.26111648393354675,1.3055824196677337])
def test_z_score_5(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.z_score([1, 1, 1, 1, 1]), None)
class Statistics3TestMain(unittest.TestCase):
def test_main(self):
statistics3 = Statistics3()
self.assertEqual(statistics3.median([1, 2, 3, 4]), 2.5)
self.assertEqual(statistics3.mode([1, 2, 3, 3]), [3])
self.assertEqual(statistics3.correlation([1, 2, 3], [4, 5, 6]), 1.0)
self.assertEqual(statistics3.mean([1, 2, 3]), 2.0)
self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])
self.assertEqual(statistics3.standard_deviation([1, 2, 3]), 1.0)
self.assertEqual(statistics3.z_score([1, 2, 3, 4]), [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225]) | import math
class Statistics3:
@staticmethod
def median(data):
sorted_data = sorted(data)
n = len(sorted_data)
if n % 2 == 1:
return sorted_data[n // 2]
else:
return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2
@staticmethod
def mode(data):
counts = {}
for value in data:
counts[value] = counts.get(value, 0) + 1
max_count = max(counts.values())
mode_values = [value for value, count in counts.items() if count == max_count]
return mode_values
@staticmethod
def correlation(x, y):
n = len(x)
mean_x = sum(x) / n
mean_y = sum(y) / n
numerator = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))
denominator = math.sqrt(sum((xi - mean_x) ** 2 for xi in x) * sum((yi - mean_y) ** 2 for yi in y))
if denominator == 0:
return None
return numerator / denominator
@staticmethod
def mean(data):
if len(data) == 0:
return None
return sum(data) / len(data)
@staticmethod
def correlation_matrix(data):
matrix = []
for i in range(len(data[0])):
row = []
for j in range(len(data[0])):
column1 = [row[i] for row in data]
column2 = [row[j] for row in data]
correlation = Statistics3.correlation(column1, column2)
row.append(correlation)
matrix.append(row)
return matrix
@staticmethod
def standard_deviation(data):
n = len(data)
if n < 2:
return None
mean_value = Statistics3.mean(data)
variance = sum((x - mean_value) ** 2 for x in data) / (n - 1)
return math.sqrt(variance)
@staticmethod
def z_score(data):
mean = Statistics3.mean(data)
std_deviation = Statistics3.standard_deviation(data)
if std_deviation is None or std_deviation == 0:
return None
return [(x - mean) / std_deviation for x in data] | [
"import math"
] | """
This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics.
"""
| [
{
"method_name": "median",
"method_description": "def median(data):\n \"\"\"\n calculates the median of the given list.\n :param data: the given list, list.\n :return: the median of the given list, float.\n >>> statistics3 = Statistics3()\n >>> statistics3.median([1, 2, 3, 4])\n 2.5\n\n \"\"\"",
"test_class": "Statistics3TestMedian",
"test_code": "class Statistics3TestMedian(unittest.TestCase):\n def test_median(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4]), 2.5)\n\n def test_median_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4, 5]), 3)\n\n def test_median_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4, 5, 6]), 3.5)\n\n def test_median_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4, 5, 6, 7]), 4)\n\n def test_median_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4, 5, 6, 7, 8]), 4.5)",
"solution_code": "def median(data):\n sorted_data = sorted(data)\n n = len(sorted_data)\n if n % 2 == 1:\n return sorted_data[n // 2]\n else:\n return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "mode",
"method_description": "@staticmethod\n def mode(data):\n \"\"\"\n calculates the mode of the given list.\n :param data: the given list, list.\n :return: the mode of the given list, list.\n >>> statistics3 = Statistics3()\n >>> statistics3.mode([1, 2, 3, 3])\n [3]\n\n \"\"\"",
"test_class": "Statistics3TestMode",
"test_code": "class Statistics3TestMode(unittest.TestCase):\n def test_mode(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3]), [3])\n\n def test_mode_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4]), [3, 4])\n\n def test_mode_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4, 5]), [3, 4])\n\n def test_mode_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4, 5, 5]), [3, 4, 5])\n\n def test_mode_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4, 5, 5, 6]), [3, 4, 5])",
"solution_code": "@staticmethod\n def mode(data):\n counts = {}\n for value in data:\n counts[value] = counts.get(value, 0) + 1\n max_count = max(counts.values())\n mode_values = [value for value, count in counts.items() if count == max_count]\n return mode_values",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "correlation",
"method_description": "@staticmethod\n def correlation(x, y):\n \"\"\"\n calculates the correlation of the given list.\n :param x: the given list, list.\n :param y: the given list, list.\n :return: the correlation of the given list, float.\n >>> statistics3 = Statistics3()\n >>> statistics3.correlation([1, 2, 3], [4, 5, 6])\n 1.0\n\n \"\"\"",
"test_class": "Statistics3TestCorrelation",
"test_code": "class Statistics3TestCorrelation(unittest.TestCase):\n def test_correlation(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 2, 3], [4, 5, 6]), 1.0)\n\n def test_correlation_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 2, 3, 4], [5, 6, 7, 8]), 1.0)\n\n def test_correlation_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 2, 3], [1,2,3]), 1.0)\n\n def test_correlation_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 1,1], [2,2,2]), None)\n\n def test_correlation_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 1,1], [1,1,1]), None)",
"solution_code": "@staticmethod\n def correlation(x, y):\n n = len(x)\n mean_x = sum(x) / n\n mean_y = sum(y) / n\n numerator = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))\n denominator = math.sqrt(sum((xi - mean_x) ** 2 for xi in x) * sum((yi - mean_y) ** 2 for yi in y))\n if denominator == 0:\n return None\n return numerator / denominator",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"math"
],
"field_dependencies": [],
"method_dependencies": [
"mean"
]
}
},
{
"method_name": "mean",
"method_description": "@staticmethod\n def mean(data):\n \"\"\"\n calculates the mean of the given list.\n :param data: the given list, list.\n :return: the mean of the given list, float.\n >>> statistics3 = Statistics3()\n >>> statistics3.mean([1, 2, 3])\n 2.0\n\n \"\"\"",
"test_class": "Statistics3TestMean",
"test_code": "class Statistics3TestMean(unittest.TestCase):\n def test_mean(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([1, 2, 3]), 2.0)\n\n def test_mean_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([]), None)\n\n def test_mean_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([1, 1, 1]), 1.0)\n\n def test_mean_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([1, 1, 1, 1]), 1.0)\n\n def test_mean_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([1, 1, 1, 1, 1]), 1.0)",
"solution_code": "@staticmethod\n def mean(data):\n if len(data) == 0:\n return None\n return sum(data) / len(data)",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "correlation_matrix",
"method_description": "@staticmethod\n def correlation_matrix(data):\n \"\"\"\n calculates the correlation matrix of the given list.\n :param data: the given list, list.\n :return: the correlation matrix of the given list, list.\n >>> statistics3 = Statistics3()\n >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]\n\n \"\"\"",
"test_class": "Statistics3TestCorrelationMatrix",
"test_code": "class Statistics3TestCorrelationMatrix(unittest.TestCase):\n def test_correlation_matrix(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])\n\n def test_correlation_matrix_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])\n\n def test_correlation_matrix_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3]]), [[None, None, None], [None, None, None], [None, None, None]])\n\n def test_correlation_matrix_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11,12]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])\n\n def test_correlation_matrix_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11,12], [13, 14, 15]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])",
"solution_code": "@staticmethod\n def correlation_matrix(data):\n matrix = []\n for i in range(len(data[0])):\n row = []\n for j in range(len(data[0])):\n column1 = [row[i] for row in data]\n column2 = [row[j] for row in data]\n correlation = Statistics3.correlation(column1, column2)\n row.append(correlation)\n matrix.append(row)\n return matrix",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"correlation"
]
}
},
{
"method_name": "standard_deviation",
"method_description": "@staticmethod\n def standard_deviation(data):\n \"\"\"\n calculates the standard deviation of the given list.\n :param data: the given list, list.\n :return: the standard deviation of the given list, float.\n >>> statistics3 = Statistics3()\n >>> statistics3.standard_deviation([1, 2, 3])\n 1.0\n\n \"\"\"",
"test_class": "Statistics3TestStandardDeviation",
"test_code": "class Statistics3TestStandardDeviation(unittest.TestCase):\n def test_standard_deviation(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 2, 3]), 1.0)\n\n def test_standard_deviation_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 1, 1]), 0.0)\n\n def test_standard_deviation_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 1]), 0.0)\n\n def test_standard_deviation_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 1, 1, 1]), 0.0)\n\n def test_standard_deviation_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 1, 2, 1, 4]), 1.3038404810405297)",
"solution_code": "@staticmethod\n def standard_deviation(data):\n n = len(data)\n if n < 2:\n return None\n mean_value = Statistics3.mean(data)\n variance = sum((x - mean_value) ** 2 for x in data) / (n - 1)\n return math.sqrt(variance)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"math"
],
"field_dependencies": [],
"method_dependencies": [
"mean"
]
}
},
{
"method_name": "z_score",
"method_description": "@staticmethod\n def z_score(data):\n \"\"\"\n calculates the z-score of the given list.\n :param data: the given list, list.\n :return: the z-score of the given list, list.\n >>> statistics3 = Statistics3()\n >>> statistics3.z_score([1, 2, 3, 4])\n [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225]\n\n \"\"\"",
"test_class": "Statistics3TestZScore",
"test_code": "class Statistics3TestZScore(unittest.TestCase):\n def test_z_score(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1, 2, 3, 4]), [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225])\n\n def test_z_score_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1, 1, 1, 1]), None)\n\n def test_z_score_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1]),None)\n\n def test_z_score_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1, 1, 2, 3]), [-0.7833494518006403,-0.7833494518006403,0.26111648393354675,1.3055824196677337])\n\n def test_z_score_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1, 1, 1, 1, 1]), None)",
"solution_code": "@staticmethod\n def z_score(data):\n mean = Statistics3.mean(data)\n std_deviation = Statistics3.standard_deviation(data)\n if std_deviation is None or std_deviation == 0:\n return None\n return [(x - mean) / std_deviation for x in data]",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"mean",
"standard_deviation"
]
}
}
] | Statistics3 | [
"Statistics3TestMedian",
"Statistics3TestMode",
"Statistics3TestCorrelation",
"Statistics3TestMean",
"Statistics3TestCorrelationMatrix",
"Statistics3TestStandardDeviation",
"Statistics3TestZScore",
"Statistics3TestMain"
] | class Statistics3:
| [] |
ClassEval_82 | class StockPortfolioTracker:
"""
This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio.
"""
def __init__(self, cash_balance):
"""
Initialize the StockPortfolioTracker class with a cash balance and an empty portfolio.
"""
self.portfolio = []
self.cash_balance = cash_balance
def add_stock(self, stock):
"""
Add a stock to the portfolio.
:param stock: a dictionary with keys "name", "price", and "quantity"
>>> tracker = StockPortfolioTracker(10000.0)
>>> tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10})
>>> tracker.portfolio
[{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
"""
def remove_stock(self, stock):
"""
Remove a stock from the portfolio.
:param stock: a dictionary with keys "name", "price", and "quantity"
>>> tracker = StockPortfolioTracker(10000.0)
>>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
>>> tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10})
True
>>> tracker.portfolio
[]
"""
def buy_stock(self, stock):
"""
Buy a stock and add it to the portfolio.
:param stock: a dictionary with keys "name", "price", and "quantity"
:param quantity: the quantity of the stock to buy,int.
:return: True if the stock was bought successfully, False if the cash balance is not enough.
>>> tracker = StockPortfolioTracker(10000.0)
>>> tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10})
True
>>> tracker.portfolio
[{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
"""
def sell_stock(self, stock):
"""
Sell a stock and remove it from the portfolio and add the cash to the cash balance.
:param stock: a dictionary with keys "name", "price", and "quantity"
:param quantity: the quantity of the stock to sell,int.
:return: True if the stock was sold successfully, False if the quantity of the stock is not enough.
>>> tracker = StockPortfolioTracker(10000.0)
>>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
>>> tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10})
True
>>> tracker.portfolio
[]
"""
def calculate_portfolio_value(self):
"""
Calculate the total value of the portfolio.
:return: the total value of the portfolio, float.
>>> tracker = StockPortfolioTracker(10000.0)
>>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
>>> tracker.calculate_portfolio_value()
11500.0
"""
def get_portfolio_summary(self):
"""
Get a summary of the portfolio.
:return: a tuple of the total value of the portfolio and a list of dictionaries with keys "name" and "value"
>>> tracker = StockPortfolioTracker(10000.0)
>>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
>>> tracker.get_portfolio_summary()
(11500.0, [{'name': 'AAPL', 'value': 1500.0}])
"""
def get_stock_value(self, stock):
"""
Get the value of a stock.
:param stock: a dictionary with keys "name", "price", and "quantity"
:return: the value of the stock, float.
>>> tracker = StockPortfolioTracker(10000.0)
>>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10})
1500.0
""" | import unittest
class StockPortfolioTrackerTestAddStock(unittest.TestCase):
def test_add_stock(self):
tracker = StockPortfolioTracker(10000.0)
tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10})
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])
def test_add_stock_2(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10})
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20}])
def test_add_stock_3(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
tracker.add_stock({"name": "MSFT", "price": 150.0, "quantity": 10})
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
def test_add_stock_4(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10})
tracker.add_stock({"name": "MSFT", "price": 150.0, "quantity": 10})
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
def test_add_stock_5(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10})
tracker.add_stock({"name": "MSFT", "price": 150.0, "quantity": 10})
tracker.add_stock({"name": "MSFT", "price": 150.0, "quantity": 10})
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},
{'name': 'MSFT', 'price': 150.0, 'quantity': 20}])
class StockPortfolioTrackerTestRemoveStock(unittest.TestCase):
def test_remove_stock(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.portfolio, [])
def test_remove_stock_2(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
def test_remove_stock_3(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.remove_stock({"name": "MSFT", "price": 150.0, "quantity": 20}), False)
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
def test_remove_stock_4(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.remove_stock({"name": "MSFT", "price": 150.0, "quantity": 10}), False)
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])
def test_remove_stock_5(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.remove_stock({"name": "MSFT", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])
class StockPortfolioTrackerTestBuyStock(unittest.TestCase):
def test_buy_stock(self):
tracker = StockPortfolioTracker(10000.0)
self.assertEqual(tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])
self.assertEqual(tracker.cash_balance, 8500.0)
def test_buy_stock_2(self):
tracker = StockPortfolioTracker(1000.0)
self.assertEqual(tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), False)
self.assertEqual(tracker.portfolio, [])
self.assertEqual(tracker.cash_balance, 1000.0)
def test_buy_stock_3(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20}])
self.assertEqual(tracker.cash_balance, 8500.0)
def test_buy_stock_4(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.buy_stock({"name": "MSFT", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.buy_stock({"name": "MSFT", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},
{'name': 'MSFT', 'price': 150.0, 'quantity': 20}])
self.assertEqual(tracker.cash_balance, 7000.0)
def test_buy_stock_5(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.buy_stock({"name": "MSFT", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
self.assertEqual(tracker.cash_balance, 7000.0)
class StockPortfolioTrackerTestSellStock(unittest.TestCase):
def test_sell_stock(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 9}), True)
self.assertEqual(tracker.portfolio, [{"name": "AAPL", "price": 150.0, "quantity": 1}])
self.assertEqual(tracker.cash_balance, 11350.0)
def test_sell_stock_2(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 20}), False)
self.assertEqual(tracker.portfolio, [{"name": "AAPL", "price": 150.0, "quantity": 10}])
self.assertEqual(tracker.cash_balance, 10000.0)
def test_sell_stock_3(self):
tracker = StockPortfolioTracker(10000.0)
self.assertEqual(tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), False)
self.assertEqual(tracker.portfolio, [])
self.assertEqual(tracker.cash_balance, 10000.0)
def test_sell_stock_4(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 20}]
self.assertEqual(tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 20}), True)
self.assertEqual(tracker.portfolio, [])
self.assertEqual(tracker.cash_balance, 13000.0)
def test_sell_stock_5(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 20}), True)
self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
self.assertEqual(tracker.cash_balance, 13000.0)
class StockPortfolioTrackerTestCalculatePortfolioValue(unittest.TestCase):
def test_calculate_portfolio_value(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.calculate_portfolio_value(), 11500.0)
def test_calculate_portfolio_value_2(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.calculate_portfolio_value(), 13000.0)
def test_calculate_portfolio_value_3(self):
tracker = StockPortfolioTracker(10000.0)
self.assertEqual(tracker.calculate_portfolio_value(), 10000.0)
def test_calculate_portfolio_value_4(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 0}]
self.assertEqual(tracker.calculate_portfolio_value(), 10000.0)
def test_calculate_portfolio_value_5(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 0.0, 'quantity': 10}]
self.assertEqual(tracker.calculate_portfolio_value(), 10000.0)
class StockPortfolioTrackerTestGetPortfolioSummary(unittest.TestCase):
def test_get_portfolio_summary(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.get_portfolio_summary(), (11500.0, [{'name': 'AAPL', 'value': 1500.0}]))
def test_get_portfolio_summary_2(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.get_portfolio_summary(),
(13000.0, [{'name': 'AAPL', 'value': 1500.0}, {'name': 'MSFT', 'value': 1500.0}]))
def test_get_portfolio_summary_3(self):
tracker = StockPortfolioTracker(10000.0)
self.assertEqual(tracker.get_portfolio_summary(), (10000.0, []))
def test_get_portfolio_summary_4(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 0}]
self.assertEqual(tracker.get_portfolio_summary(), (10000.0, [{'name': 'AAPL', 'value': 0.0}]))
def test_get_portfolio_summary_5(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 0.0, 'quantity': 10}]
self.assertEqual(tracker.get_portfolio_summary(), (10000.0, [{'name': 'AAPL', 'value': 0.0}]))
class StockPortfolioTrackerTestGetStockValue(unittest.TestCase):
def test_get_stock_value(self):
tracker = StockPortfolioTracker(10000.0)
self.assertEqual(tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}), 1500.0)
def test_get_stock_value_2(self):
tracker = StockPortfolioTracker(10000.0)
self.assertEqual(tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 0}), 0.0)
def test_get_stock_value_3(self):
tracker = StockPortfolioTracker(10000.0)
self.assertEqual(tracker.get_stock_value({"name": "AAPL", "price": 0.0, "quantity": 10}), 0.0)
def test_get_stock_value_4(self):
tracker = StockPortfolioTracker(10000.0)
self.assertEqual(tracker.get_stock_value({"name": "AAPL", "price": 0.0, "quantity": 0}), 0.0)
def test_get_stock_value_5(self):
tracker = StockPortfolioTracker(10000.0)
self.assertEqual(tracker.get_stock_value({"name": "MSFL", "price": 150.0, "quantity": 2}), 300.0)
class StockPortfolioTrackerTestMain(unittest.TestCase):
def test_main(self):
tracker = StockPortfolioTracker(10000.0)
self.assertEqual(tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), None)
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])
self.assertEqual(tracker.buy_stock({"name": "MSFT", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
self.assertEqual(tracker.cash_balance, 8500.0)
self.assertEqual(tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 9}), True)
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 1},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
self.assertEqual(tracker.cash_balance, 9850.0)
self.assertEqual(tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 1}), True)
self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
self.assertEqual(tracker.calculate_portfolio_value(), 11350.0)
self.assertEqual(tracker.get_portfolio_summary(), (11350.0, [{'name': 'MSFT', 'value': 1500.0}]))
self.assertEqual(tracker.get_stock_value({"name": "MSFT", "price": 150.0, "quantity": 10}), 1500.0)
def test_main_2(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.add_stock({"name": "MSFT", "price": 150.0, "quantity": 10}), None)
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
self.assertEqual(tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
self.assertEqual(tracker.calculate_portfolio_value(), 11500.0)
self.assertEqual(tracker.get_portfolio_summary(), (11500.0, [{'name': 'MSFT', 'value': 1500.0}]))
self.assertEqual(tracker.get_stock_value({"name": "MSFT", "price": 150.0, "quantity": 10}), 1500.0)
self.assertEqual(tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10},
{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])
self.assertEqual(tracker.cash_balance, 8500.0)
def test_main_3(self):
tracker = StockPortfolioTracker(10000.0)
tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}]
self.assertEqual(tracker.get_stock_value({"name": "MSFT", "price": 150.0, "quantity": 10}), 1500.0)
self.assertEqual(tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
self.assertEqual(tracker.cash_balance, 8500.0)
self.assertEqual(tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},
{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
self.assertEqual(tracker.cash_balance, 10000.0)
self.assertEqual(tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), True)
self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])
self.assertEqual(tracker.calculate_portfolio_value(), 11500.0)
self.assertEqual(tracker.get_portfolio_summary(), (11500.0, [{'name': 'MSFT', 'value': 1500.0}]))
self.assertEqual(tracker.get_stock_value({"name": "MSFT", "price": 150.0, "quantity": 10}), 1500.0)
self.assertEqual(tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}), None)
self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10},
{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]) | class StockPortfolioTracker:
def __init__(self, cash_balance):
self.portfolio = []
self.cash_balance = cash_balance
def add_stock(self, stock):
for pf in self.portfolio:
if pf['name'] == stock['name']:
pf['quantity'] += stock['quantity']
return
self.portfolio.append(stock)
def remove_stock(self, stock):
for pf in self.portfolio:
if pf['name'] == stock['name'] and pf['quantity'] >= stock['quantity']:
pf['quantity'] -= stock['quantity']
if pf['quantity'] == 0:
self.portfolio.remove(pf)
return True
return False
def buy_stock(self, stock):
if stock['price'] * stock['quantity'] > self.cash_balance:
return False
else:
self.add_stock(stock)
self.cash_balance -= stock['price'] * stock['quantity']
return True
def sell_stock(self, stock):
if self.remove_stock(stock) == False:
return False
self.cash_balance += stock['price'] * stock['quantity']
return True
def calculate_portfolio_value(self):
total_value = self.cash_balance
for stock in self.portfolio:
total_value += stock['price'] * stock['quantity']
return total_value
def get_portfolio_summary(self):
summary = []
for stock in self.portfolio:
value = self.get_stock_value(stock)
summary.append({"name": stock["name"], "value": value})
portfolio_value = self.calculate_portfolio_value()
return portfolio_value, summary
def get_stock_value(self, stock):
return stock['price'] * stock['quantity'] | [] | """
This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio.
"""
| [
{
"method_name": "add_stock",
"method_description": "def add_stock(self, stock):\n \"\"\"\n Add a stock to the portfolio.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n >>> tracker.portfolio\n [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n\n \"\"\"",
"test_class": "StockPortfolioTrackerTestAddStock",
"test_code": "class StockPortfolioTrackerTestAddStock(unittest.TestCase):\n def test_add_stock(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])\n\n def test_add_stock_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20}])\n\n def test_add_stock_3(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n tracker.add_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n\n def test_add_stock_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n tracker.add_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n\n def test_add_stock_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n tracker.add_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10})\n tracker.add_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 20}])",
"solution_code": "def add_stock(self, stock):\n for pf in self.portfolio:\n if pf['name'] == stock['name']:\n pf['quantity'] += stock['quantity']\n return\n\n self.portfolio.append(stock)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.portfolio"
],
"method_dependencies": []
}
},
{
"method_name": "remove_stock",
"method_description": "def remove_stock(self, stock):\n \"\"\"\n Remove a stock from the portfolio.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n >>> tracker.remove_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n True\n >>> tracker.portfolio\n []\n\n \"\"\"",
"test_class": "StockPortfolioTrackerTestRemoveStock",
"test_code": "class StockPortfolioTrackerTestRemoveStock(unittest.TestCase):\n def test_remove_stock(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [])\n\n def test_remove_stock_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n\n def test_remove_stock_3(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 20}), False)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n\n def test_remove_stock_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), False)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])\n\n def test_remove_stock_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])",
"solution_code": "def remove_stock(self, stock):\n for pf in self.portfolio:\n if pf['name'] == stock['name'] and pf['quantity'] >= stock['quantity']:\n pf['quantity'] -= stock['quantity']\n if pf['quantity'] == 0:\n self.portfolio.remove(pf)\n return True\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.portfolio"
],
"method_dependencies": []
}
},
{
"method_name": "buy_stock",
"method_description": "def buy_stock(self, stock):\n \"\"\"\n Buy a stock and add it to the portfolio.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n :param quantity: the quantity of the stock to buy,int.\n :return: True if the stock was bought successfully, False if the cash balance is not enough.\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n True\n >>> tracker.portfolio\n [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n\n \"\"\"",
"test_class": "StockPortfolioTrackerTestBuyStock",
"test_code": "class StockPortfolioTrackerTestBuyStock(unittest.TestCase):\n def test_buy_stock(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 8500.0)\n\n def test_buy_stock_2(self):\n tracker = StockPortfolioTracker(1000.0)\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), False)\n self.assertEqual(tracker.portfolio, [])\n self.assertEqual(tracker.cash_balance, 1000.0)\n\n def test_buy_stock_3(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20}])\n self.assertEqual(tracker.cash_balance, 8500.0)\n\n def test_buy_stock_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.buy_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.buy_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 20}])\n self.assertEqual(tracker.cash_balance, 7000.0)\n\n def test_buy_stock_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.buy_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 7000.0)",
"solution_code": "def buy_stock(self, stock):\n if stock['price'] * stock['quantity'] > self.cash_balance:\n return False\n else:\n self.add_stock(stock)\n self.cash_balance -= stock['price'] * stock['quantity']\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.cash_balance"
],
"method_dependencies": [
"add_stock"
]
}
},
{
"method_name": "sell_stock",
"method_description": "def sell_stock(self, stock):\n \"\"\"\n Sell a stock and remove it from the portfolio and add the cash to the cash balance.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n :param quantity: the quantity of the stock to sell,int.\n :return: True if the stock was sold successfully, False if the quantity of the stock is not enough.\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n >>> tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n True\n >>> tracker.portfolio\n []\n\n \"\"\"",
"test_class": "StockPortfolioTrackerTestSellStock",
"test_code": "class StockPortfolioTrackerTestSellStock(unittest.TestCase):\n def test_sell_stock(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 9}), True)\n self.assertEqual(tracker.portfolio, [{\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 1}])\n self.assertEqual(tracker.cash_balance, 11350.0)\n\n def test_sell_stock_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 20}), False)\n self.assertEqual(tracker.portfolio, [{\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}])\n self.assertEqual(tracker.cash_balance, 10000.0)\n\n def test_sell_stock_3(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), False)\n self.assertEqual(tracker.portfolio, [])\n self.assertEqual(tracker.cash_balance, 10000.0)\n\n def test_sell_stock_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 20}]\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 20}), True)\n self.assertEqual(tracker.portfolio, [])\n self.assertEqual(tracker.cash_balance, 13000.0)\n\n def test_sell_stock_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 20}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 13000.0)",
"solution_code": "def sell_stock(self, stock):\n if self.remove_stock(stock) == False:\n return False\n self.cash_balance += stock['price'] * stock['quantity']\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.cash_balance"
],
"method_dependencies": [
"remove_stock"
]
}
},
{
"method_name": "calculate_portfolio_value",
"method_description": "def calculate_portfolio_value(self):\n \"\"\"\n Calculate the total value of the portfolio.\n :return: the total value of the portfolio, float.\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n >>> tracker.calculate_portfolio_value()\n 11500.0\n\n \"\"\"",
"test_class": "StockPortfolioTrackerTestCalculatePortfolioValue",
"test_code": "class StockPortfolioTrackerTestCalculatePortfolioValue(unittest.TestCase):\n def test_calculate_portfolio_value(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.calculate_portfolio_value(), 11500.0)\n\n def test_calculate_portfolio_value_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.calculate_portfolio_value(), 13000.0)\n\n def test_calculate_portfolio_value_3(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.calculate_portfolio_value(), 10000.0)\n\n def test_calculate_portfolio_value_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 0}]\n self.assertEqual(tracker.calculate_portfolio_value(), 10000.0)\n\n def test_calculate_portfolio_value_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 0.0, 'quantity': 10}]\n self.assertEqual(tracker.calculate_portfolio_value(), 10000.0)",
"solution_code": "def calculate_portfolio_value(self):\n total_value = self.cash_balance\n for stock in self.portfolio:\n total_value += stock['price'] * stock['quantity']\n return total_value",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.cash_balance",
"self.portfolio"
],
"method_dependencies": []
}
},
{
"method_name": "get_portfolio_summary",
"method_description": "def get_portfolio_summary(self):\n \"\"\"\n Get a summary of the portfolio.\n :return: a tuple of the total value of the portfolio and a list of dictionaries with keys \"name\" and \"value\"\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n >>> tracker.get_portfolio_summary()\n (11500.0, [{'name': 'AAPL', 'value': 1500.0}])\n\n \"\"\"",
"test_class": "StockPortfolioTrackerTestGetPortfolioSummary",
"test_code": "class StockPortfolioTrackerTestGetPortfolioSummary(unittest.TestCase):\n def test_get_portfolio_summary(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.get_portfolio_summary(), (11500.0, [{'name': 'AAPL', 'value': 1500.0}]))\n\n def test_get_portfolio_summary_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.get_portfolio_summary(),\n (13000.0, [{'name': 'AAPL', 'value': 1500.0}, {'name': 'MSFT', 'value': 1500.0}]))\n\n def test_get_portfolio_summary_3(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_portfolio_summary(), (10000.0, []))\n\n def test_get_portfolio_summary_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 0}]\n self.assertEqual(tracker.get_portfolio_summary(), (10000.0, [{'name': 'AAPL', 'value': 0.0}]))\n\n def test_get_portfolio_summary_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 0.0, 'quantity': 10}]\n self.assertEqual(tracker.get_portfolio_summary(), (10000.0, [{'name': 'AAPL', 'value': 0.0}]))",
"solution_code": "def get_portfolio_summary(self):\n summary = []\n for stock in self.portfolio:\n value = self.get_stock_value(stock)\n summary.append({\"name\": stock[\"name\"], \"value\": value})\n portfolio_value = self.calculate_portfolio_value()\n return portfolio_value, summary",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.portfolio"
],
"method_dependencies": [
"calculate_portfolio_value",
"get_stock_value"
]
}
},
{
"method_name": "get_stock_value",
"method_description": "def get_stock_value(self, stock):\n \"\"\"\n Get the value of a stock.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n :return: the value of the stock, float.\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n 1500.0\n\n \"\"\"",
"test_class": "StockPortfolioTrackerTestGetStockValue",
"test_code": "class StockPortfolioTrackerTestGetStockValue(unittest.TestCase):\n def test_get_stock_value(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), 1500.0)\n\n def test_get_stock_value_2(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 0}), 0.0)\n\n def test_get_stock_value_3(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 0.0, \"quantity\": 10}), 0.0)\n\n def test_get_stock_value_4(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 0.0, \"quantity\": 0}), 0.0)\n\n def test_get_stock_value_5(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"MSFL\", \"price\": 150.0, \"quantity\": 2}), 300.0)",
"solution_code": "def get_stock_value(self, stock):\n return stock['price'] * stock['quantity']",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | StockPortfolioTracker | [
"StockPortfolioTrackerTestAddStock",
"StockPortfolioTrackerTestRemoveStock",
"StockPortfolioTrackerTestBuyStock",
"StockPortfolioTrackerTestSellStock",
"StockPortfolioTrackerTestCalculatePortfolioValue",
"StockPortfolioTrackerTestGetPortfolioSummary",
"StockPortfolioTrackerTestGetStockValue",
"StockPortfolioTrackerTestMain"
] | class StockPortfolioTracker:
def __init__(self, cash_balance):
"""
Initialize the StockPortfolioTracker class with a cash balance and an empty portfolio.
"""
self.portfolio = []
self.cash_balance = cash_balance
| [
"self.cash_balance",
"self.portfolio"
] |
ClassEval_83 | import sqlite3
class StudentDatabaseProcessor:
"""
This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name.
"""
def __init__(self, database_name):
"""
Initializes the StudentDatabaseProcessor object with the specified database name.
:param database_name: str, the name of the SQLite database.
"""
self.database_name = database_name
def create_student_table(self):
"""
Creates a "students" table in the database if it does not exist already.Fields include ID of type int, name of type str, age of type int, gender of type str, and grade of type int
:return: None
>>> processor = StudentDatabaseProcessor("students.db")
>>> processor.create_student_table()
"""
def insert_student(self, student_data):
"""
Inserts a new student into the "students" table.
:param student_data: dict, a dictionary containing the student's information (name, age, gender, grade).
:return: None
>>> processor = StudentDatabaseProcessor("students.db")
>>> processor.create_student_table()
>>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9}
>>> processor.insert_student(student_data)
"""
def search_student_by_name(self, name):
"""
Searches for a student in the "students" table by their name.
:param name: str, the name of the student to search for.
:return: list of tuples, the rows from the "students" table that match the search criteria.
>>> processor = StudentDatabaseProcessor("students.db")
>>> processor.create_student_table()
>>> result = processor.search_student_by_name("John")
"""
def delete_student_by_name(self, name):
"""
Deletes a student from the "students" table by their name.
:param name: str, the name of the student to delete.
:return: None
>>> processor = StudentDatabaseProcessor("students.db")
>>> processor.create_student_table()
>>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9}
>>> processor.insert_student(student_data)
>>> processor.delete_student_by_name("John")
""" | import unittest
class StudentDatabaseProcessorTestInsertStudent(unittest.TestCase):
def setUp(self):
self.processor = StudentDatabaseProcessor("test_database.db")
self.processor.create_student_table()
def tearDown(self):
conn = sqlite3.connect("test_database.db")
conn.execute("DROP TABLE IF EXISTS students")
conn.commit()
conn.close()
def test_insert_student_1(self):
student_data = {
'name': 'Alice',
'age': 20,
'gender': 'female',
'grade': 90
}
self.processor.insert_student(student_data)
conn = sqlite3.connect("test_database.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name=?", ('Alice',))
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'Alice')
def test_insert_student_2(self):
student_data = {
'name': 'aaa',
'age': 20,
'gender': 'female',
'grade': 90
}
self.processor.insert_student(student_data)
conn = sqlite3.connect("test_database.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name=?", ('aaa',))
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'aaa')
def test_insert_student_3(self):
student_data = {
'name': 'bbb',
'age': 20,
'gender': 'female',
'grade': 90
}
self.processor.insert_student(student_data)
conn = sqlite3.connect("test_database.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name=?", ('bbb',))
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'bbb')
def test_insert_student_4(self):
student_data = {
'name': 'ccc',
'age': 20,
'gender': 'female',
'grade': 90
}
self.processor.insert_student(student_data)
conn = sqlite3.connect("test_database.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name=?", ('ccc',))
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'ccc')
def test_insert_student_5(self):
student_data = {
'name': 'ddd',
'age': 20,
'gender': 'female',
'grade': 90
}
self.processor.insert_student(student_data)
conn = sqlite3.connect("test_database.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name=?", ('ddd',))
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'ddd')
class StudentDatabaseProcessorTestSearchStudentByName(unittest.TestCase):
def setUp(self):
self.processor = StudentDatabaseProcessor("test_database.db")
self.processor.create_student_table()
def tearDown(self):
conn = sqlite3.connect("test_database.db")
conn.execute("DROP TABLE IF EXISTS students")
conn.commit()
conn.close()
def test_search_student_by_name_1(self):
student_data = {
'name': 'Bob',
'age': 19,
'gender': 'male',
'grade': 85
}
self.processor.insert_student(student_data)
result = self.processor.search_student_by_name('Bob')
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'Bob')
def test_search_student_by_name_2(self):
student_data = {
'name': 'aaa',
'age': 19,
'gender': 'male',
'grade': 85
}
self.processor.insert_student(student_data)
result = self.processor.search_student_by_name('aaa')
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'aaa')
def test_search_student_by_name_3(self):
student_data = {
'name': 'bbb',
'age': 19,
'gender': 'male',
'grade': 85
}
self.processor.insert_student(student_data)
result = self.processor.search_student_by_name('bbb')
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'bbb')
def test_search_student_by_name_4(self):
student_data = {
'name': 'ccc',
'age': 19,
'gender': 'male',
'grade': 85
}
self.processor.insert_student(student_data)
result = self.processor.search_student_by_name('ccc')
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'ccc')
def test_search_student_by_name_5(self):
student_data = {
'name': 'ddd',
'age': 19,
'gender': 'male',
'grade': 85
}
self.processor.insert_student(student_data)
result = self.processor.search_student_by_name('ddd')
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'ddd')
class StudentDatabaseProcessorTestDeleteStudentByName(unittest.TestCase):
def setUp(self):
self.processor = StudentDatabaseProcessor("test_database.db")
self.processor.create_student_table()
def tearDown(self):
conn = sqlite3.connect("test_database.db")
conn.execute("DROP TABLE IF EXISTS students")
conn.commit()
conn.close()
def test_delete_student_by_name_1(self):
student_data = {
'name': 'Charlie',
'age': 18,
'gender': 'male',
'grade': 95
}
self.processor.insert_student(student_data)
self.processor.delete_student_by_name('Charlie')
conn = sqlite3.connect("test_database.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name=?", ('Charlie',))
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 0)
def test_delete_student_by_name_2(self):
student_data = {
'name': 'aaa',
'age': 18,
'gender': 'male',
'grade': 95
}
self.processor.insert_student(student_data)
self.processor.delete_student_by_name('aaa')
conn = sqlite3.connect("test_database.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name=?", ('aaa',))
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 0)
def test_delete_student_by_name_3(self):
student_data = {
'name': 'bbb',
'age': 18,
'gender': 'male',
'grade': 95
}
self.processor.insert_student(student_data)
self.processor.delete_student_by_name('bbb')
conn = sqlite3.connect("test_database.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name=?", ('bbb',))
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 0)
def test_delete_student_by_name_4(self):
student_data = {
'name': 'ccc',
'age': 18,
'gender': 'male',
'grade': 95
}
self.processor.insert_student(student_data)
self.processor.delete_student_by_name('ccc')
conn = sqlite3.connect("test_database.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name=?", ('ccc',))
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 0)
def test_delete_student_by_name_5(self):
student_data = {
'name': 'ddd',
'age': 18,
'gender': 'male',
'grade': 95
}
self.processor.insert_student(student_data)
self.processor.delete_student_by_name('ddd')
conn = sqlite3.connect("test_database.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name=?", ('ddd',))
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 0)
class StudentDatabaseProcessorTest(unittest.TestCase):
def setUp(self):
self.processor = StudentDatabaseProcessor("test_database.db")
self.processor.create_student_table()
def tearDown(self):
conn = sqlite3.connect("test_database.db")
conn.execute("DROP TABLE IF EXISTS students")
conn.commit()
conn.close()
def test_StudentDatabaseProcessor(self):
student_data = {
'name': 'Alice',
'age': 20,
'gender': 'female',
'grade': 90
}
self.processor.insert_student(student_data)
conn = sqlite3.connect("test_database.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name=?", ('Alice',))
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'Alice')
student_data = {
'name': 'Bob',
'age': 19,
'gender': 'male',
'grade': 85
}
self.processor.insert_student(student_data)
result = self.processor.search_student_by_name('Bob')
self.assertEqual(len(result), 1)
self.assertEqual(result[0][1], 'Bob')
student_data = {
'name': 'Charlie',
'age': 18,
'gender': 'male',
'grade': 95
}
self.processor.insert_student(student_data)
self.processor.delete_student_by_name('Charlie')
conn = sqlite3.connect("test_database.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name=?", ('Charlie',))
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 0) | import sqlite3
class StudentDatabaseProcessor:
def __init__(self, database_name):
self.database_name = database_name
def create_student_table(self):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
create_table_query = """
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
gender TEXT,
grade INTEGER
)
"""
cursor.execute(create_table_query)
conn.commit()
conn.close()
def insert_student(self, student_data):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
insert_query = """
INSERT INTO students (name, age, gender, grade)
VALUES (?, ?, ?, ?)
"""
cursor.execute(insert_query,
(student_data['name'], student_data['age'], student_data['gender'], student_data['grade']))
conn.commit()
conn.close()
def search_student_by_name(self, name):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
select_query = "SELECT * FROM students WHERE name = ?"
cursor.execute(select_query, (name,))
result = cursor.fetchall()
conn.close()
return result
def delete_student_by_name(self, name):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
delete_query = "DELETE FROM students WHERE name = ?"
cursor.execute(delete_query, (name,))
conn.commit()
conn.close() | [
"import sqlite3"
] | """
This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name.
"""
| [
{
"method_name": "create_student_table",
"method_description": "def create_student_table(self):\n \"\"\"\n Creates a \"students\" table in the database if it does not exist already.Fields include ID of type int, name of type str, age of type int, gender of type str, and grade of type int\n :return: None\n >>> processor = StudentDatabaseProcessor(\"students.db\")\n >>> processor.create_student_table()\n \"\"\"",
"test_class": "StudentDatabaseProcessorTestInsertStudent",
"test_code": "class StudentDatabaseProcessorTestInsertStudent(unittest.TestCase):\n def setUp(self):\n self.processor = StudentDatabaseProcessor(\"test_database.db\")\n self.processor.create_student_table()\n\n def tearDown(self):\n conn = sqlite3.connect(\"test_database.db\")\n conn.execute(\"DROP TABLE IF EXISTS students\")\n conn.commit()\n conn.close()\n\n def test_insert_student_1(self):\n student_data = {\n 'name': 'Alice',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('Alice',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')\n\n def test_insert_student_2(self):\n student_data = {\n 'name': 'aaa',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('aaa',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'aaa')\n\n def test_insert_student_3(self):\n student_data = {\n 'name': 'bbb',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('bbb',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'bbb')\n\n def test_insert_student_4(self):\n student_data = {\n 'name': 'ccc',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('ccc',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'ccc')\n\n def test_insert_student_5(self):\n student_data = {\n 'name': 'ddd',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('ddd',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'ddd')",
"solution_code": "def create_student_table(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS students (\n id INTEGER PRIMARY KEY,\n name TEXT,\n age INTEGER,\n gender TEXT,\n grade INTEGER\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"sqlite3"
],
"field_dependencies": [
"self.database_name"
],
"method_dependencies": []
}
},
{
"method_name": "insert_student",
"method_description": "def insert_student(self, student_data):\n \"\"\"\n Inserts a new student into the \"students\" table.\n :param student_data: dict, a dictionary containing the student's information (name, age, gender, grade).\n :return: None\n >>> processor = StudentDatabaseProcessor(\"students.db\")\n >>> processor.create_student_table()\n >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9}\n >>> processor.insert_student(student_data)\n \"\"\"",
"test_class": "StudentDatabaseProcessorTestSearchStudentByName",
"test_code": "class StudentDatabaseProcessorTestSearchStudentByName(unittest.TestCase):\n def setUp(self):\n self.processor = StudentDatabaseProcessor(\"test_database.db\")\n self.processor.create_student_table()\n\n def tearDown(self):\n conn = sqlite3.connect(\"test_database.db\")\n conn.execute(\"DROP TABLE IF EXISTS students\")\n conn.commit()\n conn.close()\n\n def test_search_student_by_name_1(self):\n student_data = {\n 'name': 'Bob',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('Bob')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Bob')\n\n def test_search_student_by_name_2(self):\n student_data = {\n 'name': 'aaa',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('aaa')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'aaa')\n\n def test_search_student_by_name_3(self):\n student_data = {\n 'name': 'bbb',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('bbb')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'bbb')\n\n def test_search_student_by_name_4(self):\n student_data = {\n 'name': 'ccc',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('ccc')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'ccc')\n\n def test_search_student_by_name_5(self):\n student_data = {\n 'name': 'ddd',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('ddd')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'ddd')",
"solution_code": "def insert_student(self, student_data):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n insert_query = \"\"\"\n INSERT INTO students (name, age, gender, grade)\n VALUES (?, ?, ?, ?)\n \"\"\"\n cursor.execute(insert_query,\n (student_data['name'], student_data['age'], student_data['gender'], student_data['grade']))\n\n conn.commit()\n conn.close()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"sqlite3"
],
"field_dependencies": [
"self.database_name"
],
"method_dependencies": []
}
},
{
"method_name": "search_student_by_name",
"method_description": "def search_student_by_name(self, name):\n \"\"\"\n Searches for a student in the \"students\" table by their name.\n :param name: str, the name of the student to search for.\n :return: list of tuples, the rows from the \"students\" table that match the search criteria.\n >>> processor = StudentDatabaseProcessor(\"students.db\")\n >>> processor.create_student_table()\n >>> result = processor.search_student_by_name(\"John\")\n \"\"\"",
"test_class": "StudentDatabaseProcessorTestDeleteStudentByName",
"test_code": "class StudentDatabaseProcessorTestDeleteStudentByName(unittest.TestCase):\n def setUp(self):\n self.processor = StudentDatabaseProcessor(\"test_database.db\")\n self.processor.create_student_table()\n\n def tearDown(self):\n conn = sqlite3.connect(\"test_database.db\")\n conn.execute(\"DROP TABLE IF EXISTS students\")\n conn.commit()\n conn.close()\n\n def test_delete_student_by_name_1(self):\n student_data = {\n 'name': 'Charlie',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('Charlie')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('Charlie',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_student_by_name_2(self):\n student_data = {\n 'name': 'aaa',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('aaa')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('aaa',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_student_by_name_3(self):\n student_data = {\n 'name': 'bbb',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('bbb')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('bbb',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_student_by_name_4(self):\n student_data = {\n 'name': 'ccc',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('ccc')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('ccc',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_student_by_name_5(self):\n student_data = {\n 'name': 'ddd',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('ddd')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('ddd',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)",
"solution_code": "def search_student_by_name(self, name):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n select_query = \"SELECT * FROM students WHERE name = ?\"\n cursor.execute(select_query, (name,))\n result = cursor.fetchall()\n\n conn.close()\n\n return result",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"sqlite3"
],
"field_dependencies": [
"self.database_name"
],
"method_dependencies": []
}
},
{
"method_name": "delete_student_by_name",
"method_description": "def delete_student_by_name(self, name):\n \"\"\"\n Deletes a student from the \"students\" table by their name.\n :param name: str, the name of the student to delete.\n :return: None\n >>> processor = StudentDatabaseProcessor(\"students.db\")\n >>> processor.create_student_table()\n >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9}\n >>> processor.insert_student(student_data)\n >>> processor.delete_student_by_name(\"John\")\n \"\"\"",
"test_class": "StudentDatabaseProcessorTest",
"test_code": "class StudentDatabaseProcessorTest(unittest.TestCase):\n def setUp(self):\n self.processor = StudentDatabaseProcessor(\"test_database.db\")\n self.processor.create_student_table()\n\n def tearDown(self):\n conn = sqlite3.connect(\"test_database.db\")\n conn.execute(\"DROP TABLE IF EXISTS students\")\n conn.commit()\n conn.close()\n\n def test_StudentDatabaseProcessor(self):\n student_data = {\n 'name': 'Alice',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('Alice',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')\n\n student_data = {\n 'name': 'Bob',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('Bob')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Bob')\n\n student_data = {\n 'name': 'Charlie',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('Charlie')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('Charlie',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)",
"solution_code": "def delete_student_by_name(self, name):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n delete_query = \"DELETE FROM students WHERE name = ?\"\n cursor.execute(delete_query, (name,))\n\n conn.commit()\n conn.close()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"sqlite3"
],
"field_dependencies": [
"self.database_name"
],
"method_dependencies": []
}
}
] | StudentDatabaseProcessor | [
"StudentDatabaseProcessorTestInsertStudent",
"StudentDatabaseProcessorTestSearchStudentByName",
"StudentDatabaseProcessorTestDeleteStudentByName",
"StudentDatabaseProcessorTest"
] | class StudentDatabaseProcessor:
def __init__(self, database_name):
"""
Initializes the StudentDatabaseProcessor object with the specified database name.
:param database_name: str, the name of the SQLite database.
"""
self.database_name = database_name
| [
"self.database_name"
] |
ClassEval_84 | import json
class TextFileProcessor:
"""
The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters.
"""
def __init__(self, file_path):
"""
Initialize the file path.
:param file_path: str
"""
self.file_path = file_path
def read_file_as_json(self):
"""
Read the self.file_path file as json format.
if the file content doesn't obey json format, the code will raise error.
:return data: dict if the file is stored as json format, or str/int/float.. according to the file content otherwise.
>>> textFileProcessor = TextFileProcessor('test.json')
>>> textFileProcessor.read_file_as_json()
{'name': 'test', 'age': 12}
>>> type(textFileProcessor.read_file_as_json())
<class 'dict'>
"""
def read_file(self):
"""
Read the return the content of self.file_path file.
:return: the same return as the read() method
>>> textFileProcessor = TextFileProcessor('test.json')
>>> textFileProcessor.read_file()
'{\n "name": "test",\n "age": 12\n}'
"""
def write_file(self, content):
"""
Write content into the self.file_path file, and overwrite if the file has already existed.
:param content: any content
>>> textFileProcessor = TextFileProcessor('test.json')
>>> textFileProcessor.write_file('Hello world!')
>>> textFileProcessor.read_file()
'Hello world!'
"""
def process_file(self):
"""
Read the self.file_path file and filter out non-alphabetic characters from the content string.
Overwrite the after-processed data into the same self.file_path file.
>>> textFileProcessor = TextFileProcessor('test.json')
>>> textFileProcessor.read_file()
'{\n "name": "test",\n "age": 12\n}'
>>> textFileProcessor.process_file()
'nametestage'
""" | import unittest
import json
from unittest.mock import MagicMock
import os
class TextFileProcessorTestReadFileAsJson(unittest.TestCase):
def setUp(self):
self.files = ['test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'test_5.txt']
self.contents = ['{\n "name": "test",\n "age": 12\n}', '12345', '\"hello\"', '\"aaa\"', '\"bbb\"']
for index, file in enumerate(self.files):
with open(file, 'w') as f:
f.write(self.contents[index])
# the dict type
def test_read_file_as_json_1(self):
textFileProcessor = TextFileProcessor(self.files[0])
data = textFileProcessor.read_file_as_json()
expected = {"name": "test", "age": 12}
self.assertEqual(dict, type(data))
self.assertEqual(expected, data)
# the int type
def test_read_file_as_json_2(self):
textFileProcessor = TextFileProcessor(self.files[1])
data = textFileProcessor.read_file_as_json()
expected = 12345
self.assertEqual(int, type(data))
self.assertEqual(expected, data)
# the str type
def test_read_file_as_json_3(self):
textFileProcessor = TextFileProcessor(self.files[2])
data = textFileProcessor.read_file_as_json()
expected = 'hello'
self.assertEqual(str, type(data))
self.assertEqual(expected, data)
def test_read_file_as_json_4(self):
textFileProcessor = TextFileProcessor(self.files[3])
data = textFileProcessor.read_file_as_json()
expected = 'aaa'
self.assertEqual(str, type(data))
self.assertEqual(expected, data)
def test_read_file_as_json_5(self):
textFileProcessor = TextFileProcessor(self.files[4])
data = textFileProcessor.read_file_as_json()
expected = 'bbb'
self.assertEqual(str, type(data))
self.assertEqual(expected, data)
class TextFileProcessorTestReadFile(unittest.TestCase):
def setUp(self) -> None:
self.files = ['test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'test_5.txt']
self.contents = ['123aac\n&^(*&43)', '12345', 'aaa', 'bbb', 'ccc']
for index, file in enumerate(self.files):
with open(file, 'w') as f:
f.write(self.contents[index])
def test_read_file_1(self):
textFileProcessor = TextFileProcessor(self.files[0])
data = textFileProcessor.read_file()
self.assertEqual(str, type(data))
self.assertEqual(data, self.contents[0])
def test_read_file_2(self):
textFileProcessor = TextFileProcessor(self.files[1])
data = textFileProcessor.read_file()
self.assertEqual(str, type(data))
self.assertEqual(data, self.contents[1])
def test_read_file_3(self):
textFileProcessor = TextFileProcessor(self.files[2])
data = textFileProcessor.read_file()
self.assertEqual(str, type(data))
self.assertEqual(data, self.contents[2])
def test_read_file_4(self):
textFileProcessor = TextFileProcessor(self.files[3])
data = textFileProcessor.read_file()
self.assertEqual(str, type(data))
self.assertEqual(data, self.contents[3])
def test_read_file_5(self):
textFileProcessor = TextFileProcessor(self.files[4])
data = textFileProcessor.read_file()
self.assertEqual(str, type(data))
self.assertEqual(data, self.contents[4])
class TextFileProcessorTestWriteFile(unittest.TestCase):
def setUp(self) -> None:
self.files = ['test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'test_5.txt']
self.contents = ['123aac\n&^(*&43)', '12345', 'aaa', 'bbb', 'ccc']
def tearDown(self) -> None:
for file in self.files:
if os.path.exists(file):
os.remove(file)
def test_write_file_1(self):
textFileProcessor = TextFileProcessor(self.files[0])
textFileProcessor.write_file(self.contents[0])
with open(self.files[0], 'r') as f:
data = f.read()
self.assertEqual(data, self.contents[0])
def test_write_file_2(self):
textFileProcessor = TextFileProcessor(self.files[1])
textFileProcessor.write_file(self.contents[1])
with open(self.files[1], 'r') as f:
data = f.read()
self.assertEqual(data, self.contents[1])
def test_write_file_3(self):
textFileProcessor = TextFileProcessor(self.files[2])
textFileProcessor.write_file(self.contents[2])
with open(self.files[2], 'r') as f:
data = f.read()
self.assertEqual(data, self.contents[2])
def test_write_file_4(self):
textFileProcessor = TextFileProcessor(self.files[3])
textFileProcessor.write_file(self.contents[3])
with open(self.files[3], 'r') as f:
data = f.read()
self.assertEqual(data, self.contents[3])
def test_write_file_5(self):
textFileProcessor = TextFileProcessor(self.files[4])
textFileProcessor.write_file(self.contents[4])
with open(self.files[4], 'r') as f:
data = f.read()
self.assertEqual(data, self.contents[4])
class TextFileProcessorTestProcessFile(unittest.TestCase):
def test_process_file_1(self):
self.file = 'test.txt'
self.content = 'Hello, 123 World!'
self.expected_result = 'HelloWorld'
textFileProcessor = TextFileProcessor(self.file)
textFileProcessor.read_file = MagicMock(return_value=self.content)
textFileProcessor.write_file = MagicMock()
result = textFileProcessor.process_file()
self.assertEqual(result, self.expected_result)
textFileProcessor.read_file.assert_called_once()
textFileProcessor.write_file.assert_called_once_with(self.expected_result)
def test_process_file_2(self):
self.file = 'test.txt'
self.content = 'Hello, abc World!'
self.expected_result = 'HelloabcWorld'
textFileProcessor = TextFileProcessor(self.file)
textFileProcessor.read_file = MagicMock(return_value=self.content)
textFileProcessor.write_file = MagicMock()
result = textFileProcessor.process_file()
self.assertEqual(result, self.expected_result)
textFileProcessor.read_file.assert_called_once()
textFileProcessor.write_file.assert_called_once_with(self.expected_result)
def test_process_file_3(self):
self.file = 'test.txt'
self.content = ', 123 !'
self.expected_result = ''
textFileProcessor = TextFileProcessor(self.file)
textFileProcessor.read_file = MagicMock(return_value=self.content)
textFileProcessor.write_file = MagicMock()
result = textFileProcessor.process_file()
self.assertEqual(result, self.expected_result)
textFileProcessor.read_file.assert_called_once()
textFileProcessor.write_file.assert_called_once_with(self.expected_result)
def test_process_file_4(self):
self.file = 'test.txt'
self.content = 'Hello, World!'
self.expected_result = 'HelloWorld'
textFileProcessor = TextFileProcessor(self.file)
textFileProcessor.read_file = MagicMock(return_value=self.content)
textFileProcessor.write_file = MagicMock()
result = textFileProcessor.process_file()
self.assertEqual(result, self.expected_result)
textFileProcessor.read_file.assert_called_once()
textFileProcessor.write_file.assert_called_once_with(self.expected_result)
def test_process_file_5(self):
self.file = 'test.txt'
self.content = 'Hello, 123a World!'
self.expected_result = 'HelloaWorld'
textFileProcessor = TextFileProcessor(self.file)
textFileProcessor.read_file = MagicMock(return_value=self.content)
textFileProcessor.write_file = MagicMock()
result = textFileProcessor.process_file()
self.assertEqual(result, self.expected_result)
textFileProcessor.read_file.assert_called_once()
textFileProcessor.write_file.assert_called_once_with(self.expected_result)
class TextFileProcessorTestMain(unittest.TestCase):
def setUp(self) -> None:
self.file = 'test.txt'
self.content = '{\n "name": "test",\n "age": 12\n}'
with open(self.file, 'w') as f:
f.write(self.content)
def test_main(self):
textFileProcessor = TextFileProcessor(self.file)
data1 = textFileProcessor.read_file_as_json()
expected1 = {"name": "test", "age": 12}
self.assertEqual(dict, type(data1))
self.assertEqual(expected1, data1)
textFileProcessor.write_file(self.content)
data2 = textFileProcessor.read_file()
self.assertEqual(str, type(data2))
self.assertEqual(self.content, data2)
data3 = textFileProcessor.process_file()
self.assertEqual(str, type(data3))
expected2 = 'nametestage'
self.assertEqual(expected2, data3) | import json
class TextFileProcessor:
def __init__(self, file_path):
self.file_path = file_path
def read_file_as_json(self):
with open(self.file_path, 'r') as file:
data = json.load(file)
return data
def read_file(self):
with open(self.file_path, 'r') as file:
return file.read()
def write_file(self, content):
with open(self.file_path, 'w') as file:
file.write(content)
def process_file(self):
content = self.read_file()
content = ''.join([char for char in content if char.isalpha()])
self.write_file(content)
return content | [
"import json"
] | """
The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters.
"""
| [
{
"method_name": "read_file_as_json",
"method_description": "def read_file_as_json(self):\n \"\"\"\n Read the self.file_path file as json format.\n if the file content doesn't obey json format, the code will raise error.\n :return data: dict if the file is stored as json format, or str/int/float.. according to the file content otherwise.\n >>> textFileProcessor = TextFileProcessor('test.json')\n >>> textFileProcessor.read_file_as_json()\n {'name': 'test', 'age': 12}\n >>> type(textFileProcessor.read_file_as_json())\n <class 'dict'>\n \"\"\"",
"test_class": "TextFileProcessorTestReadFileAsJson",
"test_code": "class TextFileProcessorTestReadFileAsJson(unittest.TestCase):\n def setUp(self):\n self.files = ['test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'test_5.txt']\n self.contents = ['{\\n \"name\": \"test\",\\n \"age\": 12\\n}', '12345', '\\\"hello\\\"', '\\\"aaa\\\"', '\\\"bbb\\\"']\n for index, file in enumerate(self.files):\n with open(file, 'w') as f:\n f.write(self.contents[index])\n\n # the dict type\n def test_read_file_as_json_1(self):\n textFileProcessor = TextFileProcessor(self.files[0])\n data = textFileProcessor.read_file_as_json()\n expected = {\"name\": \"test\", \"age\": 12}\n self.assertEqual(dict, type(data))\n self.assertEqual(expected, data)\n\n # the int type\n def test_read_file_as_json_2(self):\n textFileProcessor = TextFileProcessor(self.files[1])\n data = textFileProcessor.read_file_as_json()\n expected = 12345\n self.assertEqual(int, type(data))\n self.assertEqual(expected, data)\n\n # the str type\n def test_read_file_as_json_3(self):\n textFileProcessor = TextFileProcessor(self.files[2])\n data = textFileProcessor.read_file_as_json()\n expected = 'hello'\n self.assertEqual(str, type(data))\n self.assertEqual(expected, data)\n\n def test_read_file_as_json_4(self):\n textFileProcessor = TextFileProcessor(self.files[3])\n data = textFileProcessor.read_file_as_json()\n expected = 'aaa'\n self.assertEqual(str, type(data))\n self.assertEqual(expected, data)\n\n def test_read_file_as_json_5(self):\n textFileProcessor = TextFileProcessor(self.files[4])\n data = textFileProcessor.read_file_as_json()\n expected = 'bbb'\n self.assertEqual(str, type(data))\n self.assertEqual(expected, data)",
"solution_code": "def read_file_as_json(self):\n with open(self.file_path, 'r') as file:\n data = json.load(file)\n\n return data",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"json"
],
"field_dependencies": [
"self.file_path"
],
"method_dependencies": []
}
},
{
"method_name": "read_file",
"method_description": "def read_file(self):\n \"\"\"\n Read the return the content of self.file_path file.\n :return: the same return as the read() method\n >>> textFileProcessor = TextFileProcessor('test.json')\n >>> textFileProcessor.read_file()\n '{\\n \"name\": \"test\",\\n \"age\": 12\\n}'\n \"\"\"",
"test_class": "TextFileProcessorTestReadFile",
"test_code": "class TextFileProcessorTestReadFile(unittest.TestCase):\n def setUp(self) -> None:\n self.files = ['test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'test_5.txt']\n self.contents = ['123aac\\n&^(*&43)', '12345', 'aaa', 'bbb', 'ccc']\n for index, file in enumerate(self.files):\n with open(file, 'w') as f:\n f.write(self.contents[index])\n\n def test_read_file_1(self):\n textFileProcessor = TextFileProcessor(self.files[0])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[0])\n\n def test_read_file_2(self):\n textFileProcessor = TextFileProcessor(self.files[1])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[1])\n\n def test_read_file_3(self):\n textFileProcessor = TextFileProcessor(self.files[2])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[2])\n\n def test_read_file_4(self):\n textFileProcessor = TextFileProcessor(self.files[3])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[3])\n\n def test_read_file_5(self):\n textFileProcessor = TextFileProcessor(self.files[4])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[4])",
"solution_code": "def read_file(self):\n with open(self.file_path, 'r') as file:\n return file.read()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.file_path"
],
"method_dependencies": []
}
},
{
"method_name": "write_file",
"method_description": "def write_file(self, content):\n \"\"\"\n Write content into the self.file_path file, and overwrite if the file has already existed.\n :param content: any content\n >>> textFileProcessor = TextFileProcessor('test.json')\n >>> textFileProcessor.write_file('Hello world!')\n >>> textFileProcessor.read_file()\n 'Hello world!'\n \"\"\"",
"test_class": "TextFileProcessorTestWriteFile",
"test_code": "class TextFileProcessorTestWriteFile(unittest.TestCase):\n def setUp(self) -> None:\n self.files = ['test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'test_5.txt']\n self.contents = ['123aac\\n&^(*&43)', '12345', 'aaa', 'bbb', 'ccc']\n\n def tearDown(self) -> None:\n for file in self.files:\n if os.path.exists(file):\n os.remove(file)\n\n def test_write_file_1(self):\n textFileProcessor = TextFileProcessor(self.files[0])\n textFileProcessor.write_file(self.contents[0])\n with open(self.files[0], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[0])\n\n def test_write_file_2(self):\n textFileProcessor = TextFileProcessor(self.files[1])\n textFileProcessor.write_file(self.contents[1])\n with open(self.files[1], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[1])\n\n def test_write_file_3(self):\n textFileProcessor = TextFileProcessor(self.files[2])\n textFileProcessor.write_file(self.contents[2])\n with open(self.files[2], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[2])\n\n def test_write_file_4(self):\n textFileProcessor = TextFileProcessor(self.files[3])\n textFileProcessor.write_file(self.contents[3])\n with open(self.files[3], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[3])\n\n def test_write_file_5(self):\n textFileProcessor = TextFileProcessor(self.files[4])\n textFileProcessor.write_file(self.contents[4])\n with open(self.files[4], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[4])",
"solution_code": "def write_file(self, content):\n with open(self.file_path, 'w') as file:\n file.write(content)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.file_path"
],
"method_dependencies": []
}
},
{
"method_name": "process_file",
"method_description": "def process_file(self):\n \"\"\"\n Read the self.file_path file and filter out non-alphabetic characters from the content string.\n Overwrite the after-processed data into the same self.file_path file.\n >>> textFileProcessor = TextFileProcessor('test.json')\n >>> textFileProcessor.read_file()\n '{\\n \"name\": \"test\",\\n \"age\": 12\\n}'\n >>> textFileProcessor.process_file()\n 'nametestage'\n \"\"\"",
"test_class": "TextFileProcessorTestProcessFile",
"test_code": "class TextFileProcessorTestProcessFile(unittest.TestCase):\n def test_process_file_1(self):\n self.file = 'test.txt'\n self.content = 'Hello, 123 World!'\n self.expected_result = 'HelloWorld'\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)\n\n def test_process_file_2(self):\n self.file = 'test.txt'\n self.content = 'Hello, abc World!'\n self.expected_result = 'HelloabcWorld'\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)\n\n def test_process_file_3(self):\n self.file = 'test.txt'\n self.content = ', 123 !'\n self.expected_result = ''\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)\n\n def test_process_file_4(self):\n self.file = 'test.txt'\n self.content = 'Hello, World!'\n self.expected_result = 'HelloWorld'\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)\n\n def test_process_file_5(self):\n self.file = 'test.txt'\n self.content = 'Hello, 123a World!'\n self.expected_result = 'HelloaWorld'\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)",
"solution_code": "def process_file(self):\n content = self.read_file()\n content = ''.join([char for char in content if char.isalpha()])\n self.write_file(content)\n return content",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"read_file",
"write_file"
]
}
}
] | TextFileProcessor | [
"TextFileProcessorTestReadFileAsJson",
"TextFileProcessorTestReadFile",
"TextFileProcessorTestWriteFile",
"TextFileProcessorTestProcessFile",
"TextFileProcessorTestMain"
] | class TextFileProcessor:
def __init__(self, file_path):
"""
Initialize the file path.
:param file_path: str
"""
self.file_path = file_path
| [
"self.file_path"
] |
ClassEval_85 | import time
class Thermostat:
"""
The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation.
"""
def __init__(self, current_temperature, target_temperature, mode):
"""
initialize instances of the Thermostat class, including the current temperature, target temperature, and operating mode.
:param current_temperature: float
:param target_temperature: float
:param mode: str, the work mode
"""
self.current_temperature = current_temperature
self.target_temperature = target_temperature
self.mode = mode
def get_target_temperature(self):
"""
Get the target temperature of an instance of the Thermostat class.
:return self.current_temperature: int
>>> thermostat.get_target_temperature()
37.5
"""
def set_target_temperature(self, temperature):
"""
Set the target temperature
:param temperature: float, the target temperature
>>> thermostat.set_target_temperature(37.6)
>>> thermostat.target_temperature
37.6
"""
def get_mode(self):
"""
Get the current work mode
:return mode: str, working mode. only ['heat', 'cool']
"""
def set_mode(self, mode):
"""
Get the current work mode
:param mode: str, working mode. only ['heat', 'cool']
>>> thermostat.set_mode('cool')
>>> thermostat.mode
'cool'
"""
def auto_set_mode(self):
"""
Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'.
>>> thermostat = Thermostat(20.4, 37.5, 'cool')
>>> thermostat.auto_set_mode()
>>> thermostat.mode
'heat'
"""
def auto_check_conflict(self):
"""
Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature.
If there is a conflict, the operating mode will be adjusted automatically.
:return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise.
>>> thermostat = Thermostat(20.4, 37.5, 'cool')
>>> thermostat.auto_check_conflict()
False
>>> thermostat.mode
'heat'
"""
def simulate_operation(self):
"""
simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode,
and then automatically adjust the current temperature according to the operating mode until the target temperature is reached.
:return time: int, the time it took to complete the simulation.
>>> thermostat = Thermostat(20.4, 37.5, 'cool')
>>> thermostat.simulate_operation()
18
""" | import unittest
class ThermostatTestGetTargetTemperature(unittest.TestCase):
def test_get_target_temperature_1(self):
t = Thermostat(20, 25, 'heat')
self.assertEqual(t.get_target_temperature(), 25)
def test_get_target_temperature_2(self):
t = Thermostat(20, 25, 'cool')
self.assertEqual(t.get_target_temperature(), 25)
def test_get_target_temperature_3(self):
t = Thermostat(20, 25, 'test')
self.assertEqual(t.get_target_temperature(), 25)
def test_get_target_temperature_4(self):
t = Thermostat(25, 25, 'cool')
self.assertEqual(t.get_target_temperature(), 25)
def test_get_target_temperature_5(self):
t = Thermostat(25, 25, 'heat')
self.assertEqual(t.get_target_temperature(), 25)
class ThermostatTestSetTargetTemperature(unittest.TestCase):
def test_set_target_temperature_1(self):
t = Thermostat(20, 25, 'heat')
t.set_target_temperature(30)
self.assertEqual(t.get_target_temperature(), 30)
def test_set_target_temperature_2(self):
t = Thermostat(20, 25, 'cool')
t.set_target_temperature(10)
self.assertEqual(t.get_target_temperature(), 10)
def test_set_target_temperature_3(self):
t = Thermostat(20, 25, 'test')
t.set_target_temperature(10)
self.assertEqual(t.get_target_temperature(), 10)
def test_set_target_temperature_4(self):
t = Thermostat(25, 25, 'cool')
t.set_target_temperature(10)
self.assertEqual(t.get_target_temperature(), 10)
def test_set_target_temperature_5(self):
t = Thermostat(25, 25, 'heat')
t.set_target_temperature(10)
self.assertEqual(t.get_target_temperature(), 10)
class ThermostatTestGetMode(unittest.TestCase):
def test_get_mode_1(self):
t = Thermostat(20, 25, 'heat')
self.assertEqual(t.get_mode(), 'heat')
def test_get_mode_2(self):
t = Thermostat(20, 25, 'cool')
self.assertEqual(t.get_mode(), 'cool')
def test_get_mode_3(self):
t = Thermostat(20, 25, 'test')
self.assertEqual(t.get_mode(), 'test')
def test_get_mode_4(self):
t = Thermostat(25, 25, 'cool')
self.assertEqual(t.get_mode(), 'cool')
def test_get_mode_5(self):
t = Thermostat(25, 25, 'heat')
self.assertEqual(t.get_mode(), 'heat')
class ThermostatTestSetMode(unittest.TestCase):
def test_set_mode_1(self):
t = Thermostat(20, 25, 'heat')
t.set_mode('cool')
self.assertEqual(t.get_mode(), 'cool')
# use mode that not in ['heat', 'cool']
def test_set_mode_2(self):
t = Thermostat(20, 25, 'heat')
self.assertFalse(t.set_mode('test'))
def test_set_mode_3(self):
t = Thermostat(20, 25, 'cool')
t.set_mode('heat')
self.assertEqual(t.get_mode(), 'heat')
def test_set_mode_4(self):
t = Thermostat(20, 25, 'test')
t.set_mode('heat')
self.assertEqual(t.get_mode(), 'heat')
def test_set_mode_5(self):
t = Thermostat(25, 25, 'cool')
t.set_mode('heat')
self.assertEqual(t.get_mode(), 'heat')
class ThermostatTestAutoSetMode(unittest.TestCase):
def test_auto_set_mode_1(self):
t = Thermostat(20, 25, 'heat')
t.auto_set_mode()
self.assertEqual(t.get_mode(), 'heat')
def test_auto_set_mode_2(self):
t = Thermostat(25, 20, 'heat')
t.auto_set_mode()
self.assertEqual(t.get_mode(), 'cool')
def test_auto_set_mode_3(self):
t = Thermostat(25, 20, 'cool')
t.auto_set_mode()
self.assertEqual(t.get_mode(), 'cool')
def test_auto_set_mode_4(self):
t = Thermostat(20, 25, 'cool')
t.auto_set_mode()
self.assertEqual(t.get_mode(), 'heat')
def test_auto_set_mode_5(self):
t = Thermostat(25, 25, 'cool')
t.auto_set_mode()
self.assertEqual(t.get_mode(), 'cool')
class ThermostatTestAutoCheckConflict(unittest.TestCase):
def test_auto_check_conflict_1(self):
t = Thermostat(30, 25, 'cool')
self.assertTrue(t.auto_check_conflict())
def test_auto_check_conflict_2(self):
t = Thermostat(30, 25, 'heat')
self.assertFalse(t.auto_check_conflict())
self.assertEqual(t.mode, 'cool')
def test_auto_check_conflict_3(self):
t = Thermostat(25, 30, 'heat')
self.assertTrue(t.auto_check_conflict())
def test_auto_check_conflict_4(self):
t = Thermostat(25, 30, 'cool')
self.assertFalse(t.auto_check_conflict())
self.assertEqual(t.mode, 'heat')
def test_auto_check_conflict_5(self):
t = Thermostat(25, 25, 'cool')
self.assertFalse(t.auto_check_conflict())
self.assertEqual(t.mode, 'cool')
class ThermostatTestSimulateOperation(unittest.TestCase):
def test_simulate_operation_1(self):
t = Thermostat(20, 25, 'heat')
self.assertEqual(t.simulate_operation(), 5)
self.assertEqual(t.get_mode(), 'heat')
self.assertEqual(t.current_temperature, 25)
def test_simulate_operation_2(self):
t = Thermostat(25.7, 20, 'cool')
self.assertEqual(t.simulate_operation(), 6)
self.assertEqual(t.get_mode(), 'cool')
self.assertEqual(t.current_temperature, 19.7)
def test_simulate_operation_3(self):
t = Thermostat(25, 25, 'heat')
self.assertEqual(t.simulate_operation(), 0)
self.assertEqual(t.get_mode(), 'cool')
self.assertEqual(t.current_temperature, 25)
def test_simulate_operation_4(self):
t = Thermostat(25, 25, 'cool')
self.assertEqual(t.simulate_operation(), 0)
self.assertEqual(t.get_mode(), 'cool')
self.assertEqual(t.current_temperature, 25)
def test_simulate_operation_5(self):
t = Thermostat(25, 25, 'test')
self.assertEqual(t.simulate_operation(), 0)
self.assertEqual(t.get_mode(), 'cool')
self.assertEqual(t.current_temperature, 25)
class ThermostatTestMain(unittest.TestCase):
def test_main(self):
t = Thermostat(20, 37.5, 'cool')
self.assertEqual(t.get_target_temperature(), 37.5)
t.set_target_temperature(37.6)
self.assertEqual(t.target_temperature, 37.6)
self.assertEqual(t.get_mode(), 'cool')
self.assertFalse(t.set_mode('test'))
self.assertFalse(t.auto_check_conflict())
self.assertEqual(t.get_mode(), 'heat')
self.assertEqual(t.simulate_operation(), 18) | import time
class Thermostat:
def __init__(self, current_temperature, target_temperature, mode):
self.current_temperature = current_temperature
self.target_temperature = target_temperature
self.mode = mode
def get_target_temperature(self):
return self.target_temperature
def set_target_temperature(self, temperature):
self.target_temperature = temperature
def get_mode(self):
return self.mode
def set_mode(self, mode):
if mode in ['heat', 'cool']:
self.mode = mode
else:
return False
def auto_set_mode(self):
if self.current_temperature < self.target_temperature:
self.mode = 'heat'
else:
self.mode = 'cool'
def auto_check_conflict(self):
if self.current_temperature > self.target_temperature:
if self.mode == 'cool':
return True
else:
self.auto_set_mode()
return False
else:
if self.mode == 'heat':
return True
else:
self.auto_set_mode()
return False
def simulate_operation(self):
self.auto_set_mode()
use_time = 0
if self.mode == 'heat':
while(self.current_temperature < self.target_temperature):
self.current_temperature += 1
use_time += 1
else:
while(self.current_temperature > self.target_temperature):
self.current_temperature -= 1
use_time += 1
return use_time | [
"import time"
] | """
The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation.
"""
| [
{
"method_name": "get_target_temperature",
"method_description": "def get_target_temperature(self):\n \"\"\"\n Get the target temperature of an instance of the Thermostat class.\n :return self.current_temperature: int\n >>> thermostat.get_target_temperature()\n 37.5\n \"\"\"",
"test_class": "ThermostatTestGetTargetTemperature",
"test_code": "class ThermostatTestGetTargetTemperature(unittest.TestCase):\n def test_get_target_temperature_1(self):\n t = Thermostat(20, 25, 'heat')\n self.assertEqual(t.get_target_temperature(), 25)\n\n def test_get_target_temperature_2(self):\n t = Thermostat(20, 25, 'cool')\n self.assertEqual(t.get_target_temperature(), 25)\n\n def test_get_target_temperature_3(self):\n t = Thermostat(20, 25, 'test')\n self.assertEqual(t.get_target_temperature(), 25)\n\n def test_get_target_temperature_4(self):\n t = Thermostat(25, 25, 'cool')\n self.assertEqual(t.get_target_temperature(), 25)\n\n def test_get_target_temperature_5(self):\n t = Thermostat(25, 25, 'heat')\n self.assertEqual(t.get_target_temperature(), 25)",
"solution_code": "def get_target_temperature(self):\n return self.target_temperature",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.target_temperature"
],
"method_dependencies": []
}
},
{
"method_name": "set_target_temperature",
"method_description": "def set_target_temperature(self, temperature):\n \"\"\"\n Set the target temperature\n :param temperature: float, the target temperature\n >>> thermostat.set_target_temperature(37.6)\n >>> thermostat.target_temperature\n 37.6\n \"\"\"",
"test_class": "ThermostatTestSetTargetTemperature",
"test_code": "class ThermostatTestSetTargetTemperature(unittest.TestCase):\n def test_set_target_temperature_1(self):\n t = Thermostat(20, 25, 'heat')\n t.set_target_temperature(30)\n self.assertEqual(t.get_target_temperature(), 30)\n\n def test_set_target_temperature_2(self):\n t = Thermostat(20, 25, 'cool')\n t.set_target_temperature(10)\n self.assertEqual(t.get_target_temperature(), 10)\n\n def test_set_target_temperature_3(self):\n t = Thermostat(20, 25, 'test')\n t.set_target_temperature(10)\n self.assertEqual(t.get_target_temperature(), 10)\n\n def test_set_target_temperature_4(self):\n t = Thermostat(25, 25, 'cool')\n t.set_target_temperature(10)\n self.assertEqual(t.get_target_temperature(), 10)\n\n def test_set_target_temperature_5(self):\n t = Thermostat(25, 25, 'heat')\n t.set_target_temperature(10)\n self.assertEqual(t.get_target_temperature(), 10)",
"solution_code": "def set_target_temperature(self, temperature):\n self.target_temperature = temperature",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.target_temperature"
],
"method_dependencies": []
}
},
{
"method_name": "get_mode",
"method_description": "def get_mode(self):\n \"\"\"\n Get the current work mode\n :return mode: str, working mode. only ['heat', 'cool']\n \"\"\"",
"test_class": "ThermostatTestGetMode",
"test_code": "class ThermostatTestGetMode(unittest.TestCase):\n def test_get_mode_1(self):\n t = Thermostat(20, 25, 'heat')\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_get_mode_2(self):\n t = Thermostat(20, 25, 'cool')\n self.assertEqual(t.get_mode(), 'cool')\n\n def test_get_mode_3(self):\n t = Thermostat(20, 25, 'test')\n self.assertEqual(t.get_mode(), 'test')\n\n def test_get_mode_4(self):\n t = Thermostat(25, 25, 'cool')\n self.assertEqual(t.get_mode(), 'cool')\n\n def test_get_mode_5(self):\n t = Thermostat(25, 25, 'heat')\n self.assertEqual(t.get_mode(), 'heat')",
"solution_code": "def get_mode(self):\n return self.mode",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.mode"
],
"method_dependencies": []
}
},
{
"method_name": "set_mode",
"method_description": "def set_mode(self, mode):\n \"\"\"\n Get the current work mode\n :param mode: str, working mode. only ['heat', 'cool']\n >>> thermostat.set_mode('cool')\n >>> thermostat.mode\n 'cool'\n \"\"\"",
"test_class": "ThermostatTestSetMode",
"test_code": "class ThermostatTestSetMode(unittest.TestCase):\n def test_set_mode_1(self):\n t = Thermostat(20, 25, 'heat')\n t.set_mode('cool')\n self.assertEqual(t.get_mode(), 'cool')\n\n # use mode that not in ['heat', 'cool']\n def test_set_mode_2(self):\n t = Thermostat(20, 25, 'heat')\n self.assertFalse(t.set_mode('test'))\n\n def test_set_mode_3(self):\n t = Thermostat(20, 25, 'cool')\n t.set_mode('heat')\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_set_mode_4(self):\n t = Thermostat(20, 25, 'test')\n t.set_mode('heat')\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_set_mode_5(self):\n t = Thermostat(25, 25, 'cool')\n t.set_mode('heat')\n self.assertEqual(t.get_mode(), 'heat')",
"solution_code": "def set_mode(self, mode):\n if mode in ['heat', 'cool']:\n self.mode = mode\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.mode"
],
"method_dependencies": []
}
},
{
"method_name": "auto_set_mode",
"method_description": "def auto_set_mode(self):\n \"\"\"\n Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'.\n >>> thermostat = Thermostat(20.4, 37.5, 'cool')\n >>> thermostat.auto_set_mode()\n >>> thermostat.mode\n 'heat'\n \"\"\"",
"test_class": "ThermostatTestAutoSetMode",
"test_code": "class ThermostatTestAutoSetMode(unittest.TestCase):\n def test_auto_set_mode_1(self):\n t = Thermostat(20, 25, 'heat')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_auto_set_mode_2(self):\n t = Thermostat(25, 20, 'heat')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'cool')\n\n def test_auto_set_mode_3(self):\n t = Thermostat(25, 20, 'cool')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'cool')\n\n def test_auto_set_mode_4(self):\n t = Thermostat(20, 25, 'cool')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_auto_set_mode_5(self):\n t = Thermostat(25, 25, 'cool')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'cool')",
"solution_code": "def auto_set_mode(self):\n if self.current_temperature < self.target_temperature:\n self.mode = 'heat'\n else:\n self.mode = 'cool'",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.current_temperature",
"self.mode",
"self.target_temperature"
],
"method_dependencies": []
}
},
{
"method_name": "auto_check_conflict",
"method_description": "def auto_check_conflict(self):\n \"\"\"\n Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature.\n If there is a conflict, the operating mode will be adjusted automatically.\n :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise.\n >>> thermostat = Thermostat(20.4, 37.5, 'cool')\n >>> thermostat.auto_check_conflict()\n False\n >>> thermostat.mode\n 'heat'\n \"\"\"",
"test_class": "ThermostatTestAutoCheckConflict",
"test_code": "class ThermostatTestAutoCheckConflict(unittest.TestCase):\n def test_auto_check_conflict_1(self):\n t = Thermostat(30, 25, 'cool')\n self.assertTrue(t.auto_check_conflict())\n\n def test_auto_check_conflict_2(self):\n t = Thermostat(30, 25, 'heat')\n self.assertFalse(t.auto_check_conflict())\n self.assertEqual(t.mode, 'cool')\n\n def test_auto_check_conflict_3(self):\n t = Thermostat(25, 30, 'heat')\n self.assertTrue(t.auto_check_conflict())\n\n def test_auto_check_conflict_4(self):\n t = Thermostat(25, 30, 'cool')\n self.assertFalse(t.auto_check_conflict())\n self.assertEqual(t.mode, 'heat')\n\n def test_auto_check_conflict_5(self):\n t = Thermostat(25, 25, 'cool')\n self.assertFalse(t.auto_check_conflict())\n self.assertEqual(t.mode, 'cool')",
"solution_code": "def auto_check_conflict(self):\n if self.current_temperature > self.target_temperature:\n if self.mode == 'cool':\n return True\n else:\n self.auto_set_mode()\n return False\n else:\n if self.mode == 'heat':\n return True\n else:\n self.auto_set_mode()\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.current_temperature",
"self.mode",
"self.target_temperature"
],
"method_dependencies": [
"set_mode",
"auto_set_mode"
]
}
},
{
"method_name": "simulate_operation",
"method_description": "def simulate_operation(self):\n \"\"\"\n simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode,\n and then automatically adjust the current temperature according to the operating mode until the target temperature is reached.\n :return time: int, the time it took to complete the simulation.\n >>> thermostat = Thermostat(20.4, 37.5, 'cool')\n >>> thermostat.simulate_operation()\n 18\n \"\"\"",
"test_class": "ThermostatTestSimulateOperation",
"test_code": "class ThermostatTestSimulateOperation(unittest.TestCase):\n def test_simulate_operation_1(self):\n t = Thermostat(20, 25, 'heat')\n self.assertEqual(t.simulate_operation(), 5)\n self.assertEqual(t.get_mode(), 'heat')\n self.assertEqual(t.current_temperature, 25)\n\n def test_simulate_operation_2(self):\n t = Thermostat(25.7, 20, 'cool')\n self.assertEqual(t.simulate_operation(), 6)\n self.assertEqual(t.get_mode(), 'cool')\n self.assertEqual(t.current_temperature, 19.7)\n\n def test_simulate_operation_3(self):\n t = Thermostat(25, 25, 'heat')\n self.assertEqual(t.simulate_operation(), 0)\n self.assertEqual(t.get_mode(), 'cool')\n self.assertEqual(t.current_temperature, 25)\n\n def test_simulate_operation_4(self):\n t = Thermostat(25, 25, 'cool')\n self.assertEqual(t.simulate_operation(), 0)\n self.assertEqual(t.get_mode(), 'cool')\n self.assertEqual(t.current_temperature, 25)\n\n def test_simulate_operation_5(self):\n t = Thermostat(25, 25, 'test')\n self.assertEqual(t.simulate_operation(), 0)\n self.assertEqual(t.get_mode(), 'cool')\n self.assertEqual(t.current_temperature, 25)",
"solution_code": "def simulate_operation(self):\n self.auto_set_mode()\n use_time = 0\n if self.mode == 'heat':\n while(self.current_temperature < self.target_temperature):\n self.current_temperature += 1\n use_time += 1\n else:\n while(self.current_temperature > self.target_temperature):\n self.current_temperature -= 1\n use_time += 1\n return use_time",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.current_temperature",
"self.mode",
"self.target_temperature"
],
"method_dependencies": [
"set_mode",
"auto_set_mode"
]
}
}
] | Thermostat | [
"ThermostatTestGetTargetTemperature",
"ThermostatTestSetTargetTemperature",
"ThermostatTestGetMode",
"ThermostatTestSetMode",
"ThermostatTestAutoSetMode",
"ThermostatTestAutoCheckConflict",
"ThermostatTestSimulateOperation",
"ThermostatTestMain"
] | class Thermostat:
def __init__(self, current_temperature, target_temperature, mode):
"""
initialize instances of the Thermostat class, including the current temperature, target temperature, and operating mode.
:param current_temperature: float
:param target_temperature: float
:param mode: str, the work mode
"""
self.current_temperature = current_temperature
self.target_temperature = target_temperature
self.mode = mode
| [
"self.current_temperature",
"self.mode",
"self.target_temperature"
] |
ClassEval_86 | class TicTacToe:
"""
The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full.
"""
def __init__(self, N=3):
"""
Initialize a 3x3 game board with all empty spaces and current symble player, default is 'X'.
"""
self.board = [[' ' for _ in range(N)] for _ in range(3)]
self.current_player = 'X'
def make_move(self, row, col):
"""
Place the current player's mark at the specified position on the board and switch the mark.
:param row: int, the row index of the position
:param col: int, the column index of the position
:return: bool, indicating whether the move was successful or not
>>> ttt.current_player
'X'
>>> ttt.make_move(1, 1)
>>> ttt.current_player
'O'
"""
def check_winner(self):
"""
Check if there is a winner on the board in rows, columns and diagonals three directions
:return: str or None, the mark of the winner ('X' or 'O'), or None if there is no winner yet
>>> moves = [(1, 0), (2, 0), (1, 1), (2, 1), (1, 2)]
>>> for move in moves:
... ttt.make_move(move[0], move[1])
>>> ttt.check_winner()
'X'
"""
def is_board_full(self):
"""
Check if the game board is completely filled.
:return: bool, indicating whether the game board is full or not
>>> ttt.is_board_full()
False
""" | import unittest
class TicTacToeTestMakeMove(unittest.TestCase):
def test_make_move_1(self):
ttt = TicTacToe()
self.assertEqual(ttt.current_player, 'X')
self.assertTrue(ttt.make_move(0, 0))
self.assertEqual(ttt.current_player, 'O')
# move invalid
def test_make_move_2(self):
ttt = TicTacToe()
self.assertEqual(ttt.current_player, 'X')
self.assertTrue(ttt.make_move(0, 0))
self.assertTrue(ttt.make_move(0, 1))
self.assertFalse(ttt.make_move(0, 0))
self.assertEqual(ttt.current_player, 'X')
def test_make_move_3(self):
ttt = TicTacToe()
self.assertEqual(ttt.current_player, 'X')
self.assertTrue(ttt.make_move(0, 0))
self.assertTrue(ttt.make_move(0, 1))
self.assertTrue(ttt.make_move(1, 1))
self.assertEqual(ttt.current_player, 'O')
def test_make_move_4(self):
ttt = TicTacToe()
self.assertEqual(ttt.current_player, 'X')
self.assertTrue(ttt.make_move(0, 0))
self.assertTrue(ttt.make_move(0, 1))
self.assertTrue(ttt.make_move(1, 1))
self.assertTrue(ttt.make_move(1, 2))
self.assertEqual(ttt.current_player, 'X')
def test_make_move_5(self):
ttt = TicTacToe()
self.assertEqual(ttt.current_player, 'X')
self.assertTrue(ttt.make_move(0, 0))
self.assertTrue(ttt.make_move(0, 1))
self.assertTrue(ttt.make_move(1, 1))
self.assertTrue(ttt.make_move(1, 2))
self.assertTrue(ttt.make_move(2, 2))
self.assertEqual(ttt.current_player, 'O')
class TicTacToeTestCheckWinner(unittest.TestCase):
# rows
def test_check_winner_1(self):
ttt = TicTacToe()
moves = [(1, 0), (2, 0), (1, 1), (2, 1), (1, 2)]
for move in moves:
ttt.make_move(move[0], move[1])
self.assertEqual(ttt.check_winner(), 'X')
# columns
def test_check_winner_2(self):
ttt = TicTacToe()
moves = [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0)]
for move in moves:
ttt.make_move(move[0], move[1])
self.assertEqual(ttt.check_winner(), 'X')
# main diagonals
def test_check_winner_3(self):
ttt = TicTacToe()
moves = [(0, 0), (0, 1), (1, 1), (0, 2), (2, 2)]
for move in moves:
ttt.make_move(move[0], move[1])
self.assertEqual(ttt.check_winner(), 'X')
# secondary diagonals
def test_check_winner_4(self):
ttt = TicTacToe()
moves = [(0, 2), (0, 1), (1, 1), (1, 0), (2, 0)]
for move in moves:
ttt.make_move(move[0], move[1])
self.assertEqual(ttt.check_winner(), 'X')
def test_check_winner_5(self):
ttt = TicTacToe()
moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0)]
for move in moves:
ttt.make_move(move[0], move[1])
self.assertEqual(ttt.check_winner(), None)
class TicTacToeTestIsBoardFull(unittest.TestCase):
# not full
def test_is_board_full_1(self):
ttt = TicTacToe()
self.assertFalse(ttt.is_board_full())
# full
def test_is_board_full_2(self):
ttt = TicTacToe()
moves = [(1, 1), (0, 2), (2, 2), (0, 0), (0, 1), (2, 1), (1, 0), (1, 2), (2, 0)]
for move in moves:
ttt.make_move(move[0], move[1])
self.assertTrue(ttt.is_board_full())
def test_is_board_full_3(self):
ttt = TicTacToe()
moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0)]
for move in moves:
ttt.make_move(move[0], move[1])
self.assertFalse(ttt.is_board_full())
def test_is_board_full_4(self):
ttt = TicTacToe()
moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (0, 2), (1, 2), (2, 1), (2, 2)]
for move in moves:
ttt.make_move(move[0], move[1])
self.assertTrue(ttt.is_board_full())
def test_is_board_full_5(self):
ttt = TicTacToe()
moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (0, 2), (1, 2), (2, 1)]
for move in moves:
ttt.make_move(move[0], move[1])
self.assertFalse(ttt.is_board_full())
class TicTacToeTestMain(unittest.TestCase):
def test_main(self):
# A draw down way
ttt = TicTacToe()
moves = [(1, 1), (0, 2), (2, 2), (0, 0), (0, 1), (2, 1), (1, 0), (1, 2), (2, 0)]
for move in moves:
self.assertTrue(ttt.make_move(move[0], move[1]))
# no winner in this case
self.assertFalse(ttt.check_winner())
if move != (2, 0):
self.assertFalse(ttt.is_board_full())
self.assertTrue(ttt.is_board_full()) | class TicTacToe:
def __init__(self, N=3):
self.board = [[' ' for _ in range(N)] for _ in range(3)]
self.current_player = 'X'
def make_move(self, row, col):
if self.board[row][col] == ' ':
self.board[row][col] = self.current_player
self.current_player = 'O' if self.current_player == 'X' else 'X'
return True
else:
return False
def check_winner(self):
for row in self.board:
if row[0] == row[1] == row[2] != ' ':
return row[0]
for col in range(3):
if self.board[0][col] == self.board[1][col] == self.board[2][col] != ' ':
return self.board[0][col]
if self.board[0][0] == self.board[1][1] == self.board[2][2] != ' ':
return self.board[0][0]
if self.board[0][2] == self.board[1][1] == self.board[2][0] != ' ':
return self.board[0][2]
return None
def is_board_full(self):
for row in self.board:
if ' ' in row:
return False
return True | [] | """
The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full.
"""
| [
{
"method_name": "make_move",
"method_description": "def make_move(self, row, col):\n \"\"\"\n Place the current player's mark at the specified position on the board and switch the mark.\n :param row: int, the row index of the position\n :param col: int, the column index of the position\n :return: bool, indicating whether the move was successful or not\n >>> ttt.current_player\n 'X'\n >>> ttt.make_move(1, 1)\n >>> ttt.current_player\n 'O'\n \"\"\"",
"test_class": "TicTacToeTestMakeMove",
"test_code": "class TicTacToeTestMakeMove(unittest.TestCase):\n def test_make_move_1(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertEqual(ttt.current_player, 'O')\n\n # move invalid\n def test_make_move_2(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertTrue(ttt.make_move(0, 1))\n self.assertFalse(ttt.make_move(0, 0))\n self.assertEqual(ttt.current_player, 'X')\n\n def test_make_move_3(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertTrue(ttt.make_move(0, 1))\n self.assertTrue(ttt.make_move(1, 1))\n self.assertEqual(ttt.current_player, 'O')\n\n def test_make_move_4(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertTrue(ttt.make_move(0, 1))\n self.assertTrue(ttt.make_move(1, 1))\n self.assertTrue(ttt.make_move(1, 2))\n self.assertEqual(ttt.current_player, 'X')\n\n def test_make_move_5(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertTrue(ttt.make_move(0, 1))\n self.assertTrue(ttt.make_move(1, 1))\n self.assertTrue(ttt.make_move(1, 2))\n self.assertTrue(ttt.make_move(2, 2))\n self.assertEqual(ttt.current_player, 'O')",
"solution_code": "def make_move(self, row, col):\n if self.board[row][col] == ' ':\n self.board[row][col] = self.current_player\n self.current_player = 'O' if self.current_player == 'X' else 'X'\n return True\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.board",
"self.current_player"
],
"method_dependencies": []
}
},
{
"method_name": "check_winner",
"method_description": "def check_winner(self):\n \"\"\"\n Check if there is a winner on the board in rows, columns and diagonals three directions\n :return: str or None, the mark of the winner ('X' or 'O'), or None if there is no winner yet\n >>> moves = [(1, 0), (2, 0), (1, 1), (2, 1), (1, 2)]\n >>> for move in moves:\n ... ttt.make_move(move[0], move[1])\n >>> ttt.check_winner()\n 'X'\n \"\"\"",
"test_class": "TicTacToeTestCheckWinner",
"test_code": "class TicTacToeTestCheckWinner(unittest.TestCase):\n # rows\n def test_check_winner_1(self):\n ttt = TicTacToe()\n moves = [(1, 0), (2, 0), (1, 1), (2, 1), (1, 2)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), 'X')\n\n # columns\n def test_check_winner_2(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), 'X')\n\n # main diagonals \n def test_check_winner_3(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (0, 2), (2, 2)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), 'X')\n\n # secondary diagonals \n def test_check_winner_4(self):\n ttt = TicTacToe()\n moves = [(0, 2), (0, 1), (1, 1), (1, 0), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), 'X')\n\n def test_check_winner_5(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), None)",
"solution_code": "def check_winner(self):\n for row in self.board:\n if row[0] == row[1] == row[2] != ' ':\n return row[0]\n for col in range(3):\n if self.board[0][col] == self.board[1][col] == self.board[2][col] != ' ':\n return self.board[0][col]\n if self.board[0][0] == self.board[1][1] == self.board[2][2] != ' ':\n return self.board[0][0]\n if self.board[0][2] == self.board[1][1] == self.board[2][0] != ' ':\n return self.board[0][2]\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.board"
],
"method_dependencies": []
}
},
{
"method_name": "is_board_full",
"method_description": "def is_board_full(self):\n \"\"\"\n Check if the game board is completely filled.\n :return: bool, indicating whether the game board is full or not\n >>> ttt.is_board_full()\n False\n \"\"\"",
"test_class": "TicTacToeTestIsBoardFull",
"test_code": "class TicTacToeTestIsBoardFull(unittest.TestCase):\n # not full\n def test_is_board_full_1(self):\n ttt = TicTacToe()\n self.assertFalse(ttt.is_board_full())\n\n # full\n def test_is_board_full_2(self):\n ttt = TicTacToe()\n moves = [(1, 1), (0, 2), (2, 2), (0, 0), (0, 1), (2, 1), (1, 0), (1, 2), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertTrue(ttt.is_board_full())\n\n def test_is_board_full_3(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertFalse(ttt.is_board_full())\n\n def test_is_board_full_4(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (0, 2), (1, 2), (2, 1), (2, 2)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertTrue(ttt.is_board_full())\n\n def test_is_board_full_5(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (0, 2), (1, 2), (2, 1)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertFalse(ttt.is_board_full())",
"solution_code": "def is_board_full(self):\n for row in self.board:\n if ' ' in row:\n return False\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.board"
],
"method_dependencies": []
}
}
] | TicTacToe | [
"TicTacToeTestMakeMove",
"TicTacToeTestCheckWinner",
"TicTacToeTestIsBoardFull",
"TicTacToeTestMain"
] | class TicTacToe:
def __init__(self, N=3):
"""
Initialize a 3x3 game board with all empty spaces and current symble player, default is 'X'.
"""
self.board = [[' ' for _ in range(N)] for _ in range(3)]
self.current_player = 'X'
| [
"self.board",
"self.current_player"
] |
ClassEval_87 | import datetime
import time
class TimeUtils:
"""
This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object.
"""
def __init__(self):
"""
Get the current datetime
"""
self.datetime = datetime.datetime.now()
def get_current_time(self):
"""
Return the current time in the format of '%H:%M:%S'
:return: string
>>> timeutils = TimeUtils()
>>> timeutils.get_current_time()
"19:19:22"
"""
def get_current_date(self):
"""
Return the current date in the format of "%Y-%m-%d"
:return: string
>>> timeutils.get_current_date()
"2023-06-14"
"""
def add_seconds(self, seconds):
"""
Add the specified number of seconds to the current time
:param seconds: int, number of seconds to add
:return: string, time after adding the specified number of seconds in the format '%H:%M:%S'
>>> timeutils.add_seconds(600)
"19:29:22"
"""
def string_to_datetime(self, string):
"""
Convert the time string to a datetime instance
:param string: string, string before converting format
:return: datetime instance
>>> timeutils.string_to_datetime("2001-7-18 1:1:1")
2001-07-18 01:01:01
"""
def datetime_to_string(self, datetime):
"""
Convert a datetime instance to a string
:param datetime: the datetime instance to convert
:return: string, converted time string
>>> timeutils.datetime_to_string(timeutils.datetime)
"2023-06-14 19:30:03"
"""
def get_minutes(self, string_time1, string_time2):
"""
Calculate how many minutes have passed between two times, and round the results to the nearest
:return: int, the number of minutes between two times, rounded off
>>> timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1")
60
"""
def get_format_time(self, year, month, day, hour, minute, second):
"""
get format time
:param year: int
:param month: int
:param day: int
:param hour: int
:param minute: int
:param second: int
:return: formatted time string
>>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1)
"2001-07-18 01:01:01"
""" | import unittest
class TimeUtilsTestGetCurrentTime(unittest.TestCase):
def test_get_current_time_1(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime("%H:%M:%S"))
def test_get_current_time_2(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime("%H:%M:%S"))
def test_get_current_time_3(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime("%H:%M:%S"))
def test_get_current_time_4(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime("%H:%M:%S"))
def test_get_current_time_5(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime("%H:%M:%S"))
class TimeUtilsTestGetCurrentDate(unittest.TestCase):
def test_get_current_date_1(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime("%Y-%m-%d"))
def test_get_current_date_2(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime("%Y-%m-%d"))
def test_get_current_date_3(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime("%Y-%m-%d"))
def test_get_current_date_4(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime("%Y-%m-%d"))
def test_get_current_date_5(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime("%Y-%m-%d"))
class TimeUtilsTestAddSeconds(unittest.TestCase):
def test_add_seconds_1(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.add_seconds(600),
(timeutils.datetime + datetime.timedelta(seconds=600)).strftime("%H:%M:%S"))
def test_add_seconds_2(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.add_seconds(500),
(timeutils.datetime + datetime.timedelta(seconds=500)).strftime("%H:%M:%S"))
def test_add_seconds_3(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.add_seconds(400),
(timeutils.datetime + datetime.timedelta(seconds=400)).strftime("%H:%M:%S"))
def test_add_seconds_4(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.add_seconds(300),
(timeutils.datetime + datetime.timedelta(seconds=300)).strftime("%H:%M:%S"))
def test_add_seconds_5(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.add_seconds(200),
(timeutils.datetime + datetime.timedelta(seconds=200)).strftime("%H:%M:%S"))
class TimeUtilsTestStringToDatetime(unittest.TestCase):
def test_string_to_datetime_1(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.string_to_datetime('2001-7-18 1:1:1'), datetime.datetime(2001, 7, 18, 1, 1, 1))
def test_string_to_datetime_2(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.string_to_datetime('2001-7-17 1:1:1'), datetime.datetime(2001, 7, 17, 1, 1, 1))
def test_string_to_datetime_3(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.string_to_datetime('2001-7-16 1:1:1'), datetime.datetime(2001, 7, 16, 1, 1, 1))
def test_string_to_datetime_4(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.string_to_datetime('2001-7-15 1:1:1'), datetime.datetime(2001, 7, 15, 1, 1, 1))
def test_string_to_datetime_5(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.string_to_datetime('2001-7-14 1:1:1'), datetime.datetime(2001, 7, 14, 1, 1, 1))
class TimeUtilsTestDatetimeToString(unittest.TestCase):
def test_datetime_to_string_1(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),
timeutils.datetime.strftime("%Y-%m-%d %H:%M:%S"))
def test_datetime_to_string_2(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),
timeutils.datetime.strftime("%Y-%m-%d %H:%M:%S"))
def test_datetime_to_string_3(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),
timeutils.datetime.strftime("%Y-%m-%d %H:%M:%S"))
def test_datetime_to_string_4(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),
timeutils.datetime.strftime("%Y-%m-%d %H:%M:%S"))
def test_datetime_to_string_5(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),
timeutils.datetime.strftime("%Y-%m-%d %H:%M:%S"))
class TimeUtilsTestGetMinutes(unittest.TestCase):
def test_get_minutes_1(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1"), 60)
def test_get_minutes_2(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 3:1:1"), 120)
def test_get_minutes_3(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 4:1:1"), 180)
def test_get_minutes_4(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 5:1:1"), 240)
def test_get_minutes_5(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 6:1:1"), 300)
class TimeUtilsTestGetFormatTime(unittest.TestCase):
def test_get_format_time_1(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_format_time(2001, 7, 18, 1, 1, 1), "2001-07-18 01:01:01")
def test_get_format_time_2(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_format_time(2001, 7, 17, 1, 1, 1), "2001-07-17 01:01:01")
def test_get_format_time_3(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_format_time(2001, 7, 16, 1, 1, 1), "2001-07-16 01:01:01")
def test_get_format_time_4(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_format_time(2001, 7, 15, 1, 1, 1), "2001-07-15 01:01:01")
def test_get_format_time_5(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_format_time(2001, 7, 14, 1, 1, 1), "2001-07-14 01:01:01")
class TimeUtilsTest(unittest.TestCase):
def test_timeutils(self):
timeutils = TimeUtils()
self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime("%H:%M:%S"))
self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime("%Y-%m-%d"))
self.assertEqual(timeutils.add_seconds(600),
(timeutils.datetime + datetime.timedelta(seconds=600)).strftime("%H:%M:%S"))
self.assertEqual(timeutils.string_to_datetime('2001-7-18 1:1:1'), datetime.datetime(2001, 7, 18, 1, 1, 1))
self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),
timeutils.datetime.strftime("%Y-%m-%d %H:%M:%S"))
self.assertEqual(timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1"), 60)
self.assertEqual(timeutils.get_format_time(2001, 7, 18, 1, 1, 1), "2001-07-18 01:01:01") | import datetime
import time
class TimeUtils:
def __init__(self):
self.datetime = datetime.datetime.now()
def get_current_time(self):
format = "%H:%M:%S"
return self.datetime.strftime(format)
def get_current_date(self):
format = "%Y-%m-%d"
return self.datetime.strftime(format)
def add_seconds(self, seconds):
new_datetime = self.datetime + datetime.timedelta(seconds=seconds)
format = "%H:%M:%S"
return new_datetime.strftime(format)
def string_to_datetime(self, string):
return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")
def datetime_to_string(self, datetime):
return datetime.strftime("%Y-%m-%d %H:%M:%S")
def get_minutes(self, string_time1, string_time2):
time1 = self.string_to_datetime(string_time1)
time2 = self.string_to_datetime(string_time2)
return round((time2 - time1).seconds / 60)
def get_format_time(self, year, month, day, hour, minute, second):
format = "%Y-%m-%d %H:%M:%S"
time_item = datetime.datetime(year, month, day, hour, minute, second)
return time_item.strftime(format) | [
"import datetime",
"import time"
] | """
This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object.
"""
| [
{
"method_name": "get_current_time",
"method_description": "def get_current_time(self):\n \"\"\"\n Return the current time in the format of '%H:%M:%S'\n :return: string\n >>> timeutils = TimeUtils()\n >>> timeutils.get_current_time()\n \"19:19:22\"\n \"\"\"",
"test_class": "TimeUtilsTestGetCurrentTime",
"test_code": "class TimeUtilsTestGetCurrentTime(unittest.TestCase):\n def test_get_current_time_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n\n def test_get_current_time_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n\n def test_get_current_time_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n\n def test_get_current_time_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n\n def test_get_current_time_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))",
"solution_code": "def get_current_time(self):\n format = \"%H:%M:%S\"\n return self.datetime.strftime(format)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"datetime",
"time"
],
"field_dependencies": [
"self.datetime"
],
"method_dependencies": []
}
},
{
"method_name": "get_current_date",
"method_description": "def get_current_date(self):\n \"\"\"\n Return the current date in the format of \"%Y-%m-%d\"\n :return: string\n >>> timeutils.get_current_date()\n \"2023-06-14\"\n \"\"\"",
"test_class": "TimeUtilsTestGetCurrentDate",
"test_code": "class TimeUtilsTestGetCurrentDate(unittest.TestCase):\n def test_get_current_date_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n\n def test_get_current_date_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n\n def test_get_current_date_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n\n def test_get_current_date_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n\n def test_get_current_date_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))",
"solution_code": "def get_current_date(self):\n format = \"%Y-%m-%d\"\n return self.datetime.strftime(format)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"datetime",
"time"
],
"field_dependencies": [
"self.datetime"
],
"method_dependencies": []
}
},
{
"method_name": "add_seconds",
"method_description": "def add_seconds(self, seconds):\n \"\"\"\n Add the specified number of seconds to the current time\n :param seconds: int, number of seconds to add\n :return: string, time after adding the specified number of seconds in the format '%H:%M:%S'\n >>> timeutils.add_seconds(600)\n \"19:29:22\"\n \"\"\"",
"test_class": "TimeUtilsTestAddSeconds",
"test_code": "class TimeUtilsTestAddSeconds(unittest.TestCase):\n def test_add_seconds_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(600),\n (timeutils.datetime + datetime.timedelta(seconds=600)).strftime(\"%H:%M:%S\"))\n\n def test_add_seconds_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(500),\n (timeutils.datetime + datetime.timedelta(seconds=500)).strftime(\"%H:%M:%S\"))\n\n def test_add_seconds_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(400),\n (timeutils.datetime + datetime.timedelta(seconds=400)).strftime(\"%H:%M:%S\"))\n\n def test_add_seconds_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(300),\n (timeutils.datetime + datetime.timedelta(seconds=300)).strftime(\"%H:%M:%S\"))\n\n def test_add_seconds_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(200),\n (timeutils.datetime + datetime.timedelta(seconds=200)).strftime(\"%H:%M:%S\"))",
"solution_code": "def add_seconds(self, seconds):\n new_datetime = self.datetime + datetime.timedelta(seconds=seconds)\n format = \"%H:%M:%S\"\n return new_datetime.strftime(format)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"datetime",
"time"
],
"field_dependencies": [
"self.datetime"
],
"method_dependencies": []
}
},
{
"method_name": "string_to_datetime",
"method_description": "def string_to_datetime(self, string):\n \"\"\"\n Convert the time string to a datetime instance\n :param string: string, string before converting format\n :return: datetime instance\n >>> timeutils.string_to_datetime(\"2001-7-18 1:1:1\")\n 2001-07-18 01:01:01\n \"\"\"",
"test_class": "TimeUtilsTestStringToDatetime",
"test_code": "class TimeUtilsTestStringToDatetime(unittest.TestCase):\n def test_string_to_datetime_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-18 1:1:1'), datetime.datetime(2001, 7, 18, 1, 1, 1))\n\n def test_string_to_datetime_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-17 1:1:1'), datetime.datetime(2001, 7, 17, 1, 1, 1))\n\n def test_string_to_datetime_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-16 1:1:1'), datetime.datetime(2001, 7, 16, 1, 1, 1))\n\n def test_string_to_datetime_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-15 1:1:1'), datetime.datetime(2001, 7, 15, 1, 1, 1))\n\n def test_string_to_datetime_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-14 1:1:1'), datetime.datetime(2001, 7, 14, 1, 1, 1))",
"solution_code": "def string_to_datetime(self, string):\n return datetime.datetime.strptime(string, \"%Y-%m-%d %H:%M:%S\")",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"datetime",
"time"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "datetime_to_string",
"method_description": "def datetime_to_string(self, datetime):\n \"\"\"\n Convert a datetime instance to a string\n :param datetime: the datetime instance to convert\n :return: string, converted time string\n >>> timeutils.datetime_to_string(timeutils.datetime)\n \"2023-06-14 19:30:03\"\n \"\"\"",
"test_class": "TimeUtilsTestDatetimeToString",
"test_code": "class TimeUtilsTestDatetimeToString(unittest.TestCase):\n def test_datetime_to_string_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n def test_datetime_to_string_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n def test_datetime_to_string_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n def test_datetime_to_string_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n def test_datetime_to_string_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))",
"solution_code": "def datetime_to_string(self, datetime):\n return datetime.strftime(\"%Y-%m-%d %H:%M:%S\")",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"datetime",
"time"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "get_minutes",
"method_description": "def get_minutes(self, string_time1, string_time2):\n \"\"\"\n Calculate how many minutes have passed between two times, and round the results to the nearest\n :return: int, the number of minutes between two times, rounded off\n >>> timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 2:1:1\")\n 60\n \"\"\"",
"test_class": "TimeUtilsTestGetMinutes",
"test_code": "class TimeUtilsTestGetMinutes(unittest.TestCase):\n def test_get_minutes_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 2:1:1\"), 60)\n\n def test_get_minutes_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 3:1:1\"), 120)\n\n def test_get_minutes_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 4:1:1\"), 180)\n\n def test_get_minutes_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 5:1:1\"), 240)\n\n def test_get_minutes_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 6:1:1\"), 300)",
"solution_code": "def get_minutes(self, string_time1, string_time2):\n time1 = self.string_to_datetime(string_time1)\n time2 = self.string_to_datetime(string_time2)\n return round((time2 - time1).seconds / 60)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"datetime",
"time"
],
"field_dependencies": [],
"method_dependencies": [
"string_to_datetime"
]
}
},
{
"method_name": "get_format_time",
"method_description": "def get_format_time(self, year, month, day, hour, minute, second):\n \"\"\"\n get format time\n :param year: int\n :param month: int\n :param day: int\n :param hour: int\n :param minute: int\n :param second: int\n :return: formatted time string\n >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1)\n \"2001-07-18 01:01:01\"\n \"\"\"",
"test_class": "TimeUtilsTestGetFormatTime",
"test_code": "class TimeUtilsTestGetFormatTime(unittest.TestCase):\n def test_get_format_time_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 18, 1, 1, 1), \"2001-07-18 01:01:01\")\n\n def test_get_format_time_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 17, 1, 1, 1), \"2001-07-17 01:01:01\")\n\n def test_get_format_time_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 16, 1, 1, 1), \"2001-07-16 01:01:01\")\n\n def test_get_format_time_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 15, 1, 1, 1), \"2001-07-15 01:01:01\")\n\n def test_get_format_time_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 14, 1, 1, 1), \"2001-07-14 01:01:01\")",
"solution_code": "def get_format_time(self, year, month, day, hour, minute, second):\n format = \"%Y-%m-%d %H:%M:%S\"\n time_item = datetime.datetime(year, month, day, hour, minute, second)\n return time_item.strftime(format)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"datetime",
"time"
],
"field_dependencies": [],
"method_dependencies": []
}
}
] | TimeUtils | [
"TimeUtilsTestGetCurrentTime",
"TimeUtilsTestGetCurrentDate",
"TimeUtilsTestAddSeconds",
"TimeUtilsTestStringToDatetime",
"TimeUtilsTestDatetimeToString",
"TimeUtilsTestGetMinutes",
"TimeUtilsTestGetFormatTime",
"TimeUtilsTest"
] | class TimeUtils:
def __init__(self):
"""
Get the current datetime
"""
self.datetime = datetime.datetime.now()
| [
"self.datetime"
] |
ClassEval_88 | from math import pi, fabs
class TriCalculator:
"""
The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations.
"""
def __init__(self):
pass
def cos(self, x):
"""
Calculate the cos value of the x-degree angle
:param x:float
:return:float
>>> tricalculator = TriCalculator()
>>> tricalculator.cos(60)
0.5
"""
def factorial(self, a):
"""
Calculate the factorial of a
:param a: int
:return: int
>>> tricalculator.factorial(5)
120
"""
def taylor(self, x, n):
"""
Finding the n-order Taylor expansion value of cos (x/180 * pi)
:param x: int
:param n: int
:return: float
>>> tricalculator.taylor(60, 50)
0.5000000000000001
"""
def sin(self, x):
"""
Calculate the sin value of the x-degree angle
:param x: float
:return: float
>>> tricalculator.sin(30)
0.5
"""
def tan(self, x):
"""
Calculate the tan value of the x-degree angle
:param x: float
:return: float
>>> tricalculator.tan(45)
1.0
""" | import unittest
class TriCalculatorTestCos(unittest.TestCase):
def test_cos_1(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.cos(60), 0.5)
def test_cos_2(self):
tricalculator = TriCalculator()
self.assertAlmostEqual(tricalculator.cos(30), 0.8660254038)
def test_cos_3(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.cos(0), 1.0)
def test_cos_4(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.cos(90), 0.0)
def test_cos_5(self):
tricalculator = TriCalculator()
self.assertAlmostEqual(tricalculator.cos(45), 0.7071067812)
class TriCalculatorTestFactorial(unittest.TestCase):
def test_factorial_1(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.factorial(5), 120)
def test_factorial_2(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.factorial(4), 24)
def test_factorial_3(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.factorial(3), 6)
def test_factorial_4(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.factorial(2), 2)
def test_factorial_5(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.factorial(1), 1)
class TriCalculatorTestTaylor(unittest.TestCase):
def test_taylor_1(self):
tricalculator = TriCalculator()
self.assertAlmostEqual(tricalculator.taylor(60, 50), 0.5)
def test_taylor_2(self):
tricalculator = TriCalculator()
self.assertAlmostEqual(tricalculator.taylor(30, 50), 0.8660254037844386)
def test_taylor_3(self):
tricalculator = TriCalculator()
self.assertAlmostEqual(tricalculator.taylor(90, 50), 0.0)
def test_taylor_4(self):
tricalculator = TriCalculator()
self.assertAlmostEqual(tricalculator.taylor(0, 50), 1.0)
def test_taylor_5(self):
tricalculator = TriCalculator()
self.assertAlmostEqual(tricalculator.taylor(45, 50), 0.7071067811865475)
class TriCalculatorTestSin(unittest.TestCase):
def test_sin_1(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.sin(30), 0.5)
def test_sin_2(self):
tricalculator = TriCalculator()
self.assertAlmostEqual(tricalculator.sin(60), 0.8660254038)
def test_sin_3(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.sin(0), 0.0)
def test_sin_4(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.sin(90), 1.0)
def test_sin_5(self):
tricalculator = TriCalculator()
self.assertAlmostEqual(tricalculator.sin(45), 0.7071067812)
class TriCalculatorTestTan(unittest.TestCase):
def test_tan_1(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.tan(45), 1.0)
def test_tan_2(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.tan(90), False)
def test_tan_3(self):
tricalculator = TriCalculator()
self.assertAlmostEqual(tricalculator.tan(30), 0.5773502692)
def test_tan_4(self):
tricalculator = TriCalculator()
self.assertAlmostEqual(tricalculator.tan(60), 1.7320508076)
def test_tan_5(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.tan(0), 0.0)
class TriCalculatorTest(unittest.TestCase):
def test_tricalculator(self):
tricalculator = TriCalculator()
self.assertEqual(tricalculator.cos(60), 0.5)
self.assertAlmostEqual(tricalculator.taylor(60, 50), 0.5)
self.assertEqual(tricalculator.sin(30), 0.5)
self.assertEqual(tricalculator.tan(45), 1.0)
self.assertEqual(tricalculator.tan(90), False) | from math import pi, fabs
class TriCalculator:
def __init__(self):
pass
def cos(self, x):
return round(self.taylor(x, 50), 10)
def factorial(self, a):
b = 1
while a != 1:
b *= a
a -= 1
return b
def taylor(self, x, n):
a = 1
x = x / 180 * pi
count = 1
for k in range(1, n):
if count % 2 != 0:
a -= (x ** (2 * k)) / self.factorial(2 * k)
else:
a += (x ** (2 * k)) / self.factorial(2 * k)
count += 1
return a
def sin(self, x):
x = x / 180 * pi
g = 0
t = x
n = 1
while fabs(t) >= 1e-15:
g += t
n += 1
t = -t * x * x / (2 * n - 1) / (2 * n - 2)
return round(g, 10)
def tan(self, x):
if self.cos(x) != 0:
result = self.sin(x) / self.cos(x)
return round(result, 10)
else:
return False | [
"from math import pi, fabs"
] | """
The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations.
"""
| [
{
"method_name": "cos",
"method_description": "def cos(self, x):\n \"\"\"\n Calculate the cos value of the x-degree angle\n :param x:float\n :return:float\n >>> tricalculator = TriCalculator()\n >>> tricalculator.cos(60)\n 0.5\n \"\"\"",
"test_class": "TriCalculatorTestCos",
"test_code": "class TriCalculatorTestCos(unittest.TestCase):\n def test_cos_1(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.cos(60), 0.5)\n\n def test_cos_2(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.cos(30), 0.8660254038)\n\n def test_cos_3(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.cos(0), 1.0)\n\n def test_cos_4(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.cos(90), 0.0)\n\n def test_cos_5(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.cos(45), 0.7071067812)",
"solution_code": "def cos(self, x):\n return round(self.taylor(x, 50), 10)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"taylor"
]
}
},
{
"method_name": "factorial",
"method_description": "def factorial(self, a):\n \"\"\"\n Calculate the factorial of a\n :param a: int\n :return: int\n >>> tricalculator.factorial(5)\n 120\n \"\"\"",
"test_class": "TriCalculatorTestFactorial",
"test_code": "class TriCalculatorTestFactorial(unittest.TestCase):\n def test_factorial_1(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(5), 120)\n\n def test_factorial_2(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(4), 24)\n\n def test_factorial_3(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(3), 6)\n\n def test_factorial_4(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(2), 2)\n\n def test_factorial_5(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(1), 1)",
"solution_code": "def factorial(self, a):\n b = 1\n while a != 1:\n b *= a\n a -= 1\n return b",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "taylor",
"method_description": "def taylor(self, x, n):\n \"\"\"\n Finding the n-order Taylor expansion value of cos (x/180 * pi)\n :param x: int\n :param n: int\n :return: float\n >>> tricalculator.taylor(60, 50)\n 0.5000000000000001\n \"\"\"",
"test_class": "TriCalculatorTestTaylor",
"test_code": "class TriCalculatorTestTaylor(unittest.TestCase):\n def test_taylor_1(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(60, 50), 0.5)\n\n def test_taylor_2(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(30, 50), 0.8660254037844386)\n\n def test_taylor_3(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(90, 50), 0.0)\n\n def test_taylor_4(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(0, 50), 1.0)\n\n def test_taylor_5(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(45, 50), 0.7071067811865475)",
"solution_code": "def taylor(self, x, n):\n a = 1\n x = x / 180 * pi\n count = 1\n for k in range(1, n):\n if count % 2 != 0:\n a -= (x ** (2 * k)) / self.factorial(2 * k)\n else:\n a += (x ** (2 * k)) / self.factorial(2 * k)\n count += 1\n return a",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"factorial"
]
}
},
{
"method_name": "sin",
"method_description": "def sin(self, x):\n \"\"\"\n Calculate the sin value of the x-degree angle\n :param x: float\n :return: float\n >>> tricalculator.sin(30)\n 0.5\n \"\"\"",
"test_class": "TriCalculatorTestSin",
"test_code": "class TriCalculatorTestSin(unittest.TestCase):\n def test_sin_1(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.sin(30), 0.5)\n\n def test_sin_2(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.sin(60), 0.8660254038)\n\n def test_sin_3(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.sin(0), 0.0)\n\n def test_sin_4(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.sin(90), 1.0)\n\n def test_sin_5(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.sin(45), 0.7071067812)",
"solution_code": "def sin(self, x):\n x = x / 180 * pi\n g = 0\n t = x\n n = 1\n\n while fabs(t) >= 1e-15:\n g += t\n n += 1\n t = -t * x * x / (2 * n - 1) / (2 * n - 2)\n return round(g, 10)",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "tan",
"method_description": "def tan(self, x):\n \"\"\"\n Calculate the tan value of the x-degree angle\n :param x: float\n :return: float\n >>> tricalculator.tan(45)\n 1.0\n \"\"\"",
"test_class": "TriCalculatorTestTan",
"test_code": "class TriCalculatorTestTan(unittest.TestCase):\n def test_tan_1(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.tan(45), 1.0)\n\n def test_tan_2(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.tan(90), False)\n\n def test_tan_3(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.tan(30), 0.5773502692)\n\n def test_tan_4(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.tan(60), 1.7320508076)\n\n def test_tan_5(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.tan(0), 0.0)",
"solution_code": "def tan(self, x):\n if self.cos(x) != 0:\n result = self.sin(x) / self.cos(x)\n return round(result, 10)\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"cos",
"sin"
]
}
}
] | TriCalculator | [
"TriCalculatorTestCos",
"TriCalculatorTestFactorial",
"TriCalculatorTestTaylor",
"TriCalculatorTestSin",
"TriCalculatorTestTan",
"TriCalculatorTest"
] | class TriCalculator:
def __init__(self):
pass
| [] |
ClassEval_89 | import random
class TwentyFourPointGame:
"""
This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24.
"""
def __init__(self) -> None:
self.nums = []
def _generate_cards(self):
"""
Generate random numbers between 1 and 9 for the cards.
"""
def get_my_cards(self):
"""
Get a list of four random numbers between 1 and 9 representing the player's cards.
:return: list of integers, representing the player's cards
>>> game = TwentyFourPointGame()
>>> game.get_my_cards()
"""
def answer(self, expression):
"""
Check if a given mathematical expression using the cards can evaluate to 24.
:param expression: string, mathematical expression using the cards
:return: bool, True if the expression evaluates to 24, False otherwise
>>> game = TwentyFourPointGame()
>>> game.nums = [4, 3, 6, 6]
>>> ans = "4*3+6+6"
>>> ret = game.answer(ans)
True
"""
def evaluate_expression(self, expression):
"""
Evaluate a mathematical expression and check if the result is 24.
:param expression: string, mathematical expression
:return: bool, True if the expression evaluates to 24, False otherwise
>>> game = TwentyFourPointGame()
>>> nums = [4, 3, 6, 6]
>>> ans = "4*3+6+6"
>>> ret = game.evaluate_expression(ans)
True
""" | import unittest
class TwentyFourPointGameTestGetMyCards(unittest.TestCase):
def test_get_my_cards_1(self):
game = TwentyFourPointGame()
cards = game.get_my_cards()
self.assertEqual(len(cards), 4)
for card in cards:
self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_get_my_cards_2(self):
game = TwentyFourPointGame()
cards = game.get_my_cards()
self.assertEqual(len(cards), 4)
for card in cards:
self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_get_my_cards_3(self):
game = TwentyFourPointGame()
cards = game.get_my_cards()
self.assertEqual(len(cards), 4)
for card in cards:
self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_get_my_cards_4(self):
game = TwentyFourPointGame()
cards = game.get_my_cards()
self.assertEqual(len(cards), 4)
for card in cards:
self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_get_my_cards_5(self):
game = TwentyFourPointGame()
cards = game.get_my_cards()
self.assertEqual(len(cards), 4)
for card in cards:
self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])
class TwentyFourPointGameTestAnswer(unittest.TestCase):
def test_answer_1(self):
game = TwentyFourPointGame()
cards = game.answer('pass')
self.assertEqual(len(cards), 4)
def test_answer_2(self):
game = TwentyFourPointGame()
result = game.answer('4*3+6+6')
self.assertTrue(result)
def test_answer_3(self):
game = TwentyFourPointGame()
result = game.answer('1+1+1+1')
self.assertFalse(result)
def test_answer_4(self):
game = TwentyFourPointGame()
result = game.answer('1+')
self.assertFalse(result)
def test_answer_5(self):
game = TwentyFourPointGame()
result = game.answer('abc')
self.assertFalse(result)
def test_answer_6(self):
game = TwentyFourPointGame()
game.nums = [1, 1, 1, 1]
result = game.answer('1+1+1+2')
self.assertFalse(result)
def test_answer_7(self):
game = TwentyFourPointGame()
game.nums = [1, 1, 1, 1]
result = game.answer('1+1+1+1+1')
self.assertFalse(result)
class TwentyFourPointGameTestEvaluateExpression(unittest.TestCase):
def test_evaluate_expression_1(self):
game = TwentyFourPointGame()
result = game.evaluate_expression('4+3+6+6')
self.assertFalse(result)
def test_evaluate_expression_2(self):
game = TwentyFourPointGame()
result = game.evaluate_expression('4*3+6+6')
self.assertTrue(result)
def test_evaluate_expression_3(self):
game = TwentyFourPointGame()
result = game.evaluate_expression('1+1+1+1')
self.assertFalse(result)
def test_evaluate_expression_4(self):
game = TwentyFourPointGame()
result = game.evaluate_expression('1+')
self.assertFalse(result)
def test_evaluate_expression_5(self):
game = TwentyFourPointGame()
result = game.evaluate_expression('abc')
self.assertFalse(result)
class TwentyFourPointGameTest(unittest.TestCase):
def test_TwentyFourPointGame(self):
game = TwentyFourPointGame()
cards = game.get_my_cards()
self.assertEqual(len(cards), 4)
for card in cards:
self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])
game.nums = [4, 3, 6, 6]
result = game.answer('4*3+6+6')
self.assertTrue(result)
result = game.evaluate_expression('4*3+6+6')
self.assertTrue(result) | import random
class TwentyFourPointGame:
def __init__(self) -> None:
self.nums = []
def _generate_cards(self):
for i in range(4):
self.nums.append(random.randint(1, 9))
assert len(self.nums) == 4
def get_my_cards(self):
self.nums = []
self._generate_cards()
return self.nums
def answer(self, expression):
if expression == 'pass':
return self.get_my_cards()
statistic = {}
for c in expression:
if c.isdigit() and int(c) in self.nums:
statistic[c] = statistic.get(c, 0) + 1
nums_used = statistic.copy()
for num in self.nums:
if nums_used.get(str(num), -100) != -100 and nums_used[str(num)] > 0:
nums_used[str(num)] -= 1
else:
return False
if all(count == 0 for count in nums_used.values()) == True:
return self.evaluate_expression(expression)
else:
return False
def evaluate_expression(self, expression):
try:
if eval(expression) == 24:
return True
else:
return False
except Exception as e:
return False | [
"import random"
] | """
This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24.
"""
| [
{
"method_name": "_generate_cards",
"method_description": "def _generate_cards(self):\n \"\"\"\n Generate random numbers between 1 and 9 for the cards.\n \"\"\"",
"test_class": "TwentyFourPointGameTestGetMyCards",
"test_code": "class TwentyFourPointGameTestGetMyCards(unittest.TestCase):\n def test_get_my_cards_1(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n def test_get_my_cards_2(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n def test_get_my_cards_3(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n def test_get_my_cards_4(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n def test_get_my_cards_5(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])",
"solution_code": "def _generate_cards(self):\n for i in range(4):\n self.nums.append(random.randint(1, 9))\n assert len(self.nums) == 4",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"random"
],
"field_dependencies": [
"self.nums"
],
"method_dependencies": []
}
},
{
"method_name": "get_my_cards",
"method_description": "def get_my_cards(self):\n \"\"\"\n Get a list of four random numbers between 1 and 9 representing the player's cards.\n :return: list of integers, representing the player's cards\n >>> game = TwentyFourPointGame()\n >>> game.get_my_cards()\n\n \"\"\"",
"test_class": "TwentyFourPointGameTestAnswer",
"test_code": "class TwentyFourPointGameTestAnswer(unittest.TestCase):\n def test_answer_1(self):\n game = TwentyFourPointGame()\n cards = game.answer('pass')\n self.assertEqual(len(cards), 4)\n\n def test_answer_2(self):\n game = TwentyFourPointGame()\n result = game.answer('4*3+6+6')\n self.assertTrue(result)\n\n def test_answer_3(self):\n game = TwentyFourPointGame()\n result = game.answer('1+1+1+1')\n self.assertFalse(result)\n\n def test_answer_4(self):\n game = TwentyFourPointGame()\n result = game.answer('1+')\n self.assertFalse(result)\n\n def test_answer_5(self):\n game = TwentyFourPointGame()\n result = game.answer('abc')\n self.assertFalse(result)\n\n def test_answer_6(self):\n game = TwentyFourPointGame()\n game.nums = [1, 1, 1, 1]\n result = game.answer('1+1+1+2')\n self.assertFalse(result)\n\n def test_answer_7(self):\n game = TwentyFourPointGame()\n game.nums = [1, 1, 1, 1]\n result = game.answer('1+1+1+1+1')\n self.assertFalse(result)",
"solution_code": "def get_my_cards(self):\n self.nums = []\n self._generate_cards()\n return self.nums",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.nums"
],
"method_dependencies": [
"_generate_cards"
]
}
},
{
"method_name": "answer",
"method_description": "def answer(self, expression):\n \"\"\"\n Check if a given mathematical expression using the cards can evaluate to 24.\n :param expression: string, mathematical expression using the cards\n :return: bool, True if the expression evaluates to 24, False otherwise\n >>> game = TwentyFourPointGame()\n >>> game.nums = [4, 3, 6, 6]\n >>> ans = \"4*3+6+6\"\n >>> ret = game.answer(ans)\n True\n \"\"\"",
"test_class": "TwentyFourPointGameTestEvaluateExpression",
"test_code": "class TwentyFourPointGameTestEvaluateExpression(unittest.TestCase):\n def test_evaluate_expression_1(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('4+3+6+6')\n self.assertFalse(result)\n\n def test_evaluate_expression_2(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('4*3+6+6')\n self.assertTrue(result)\n\n def test_evaluate_expression_3(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('1+1+1+1')\n self.assertFalse(result)\n\n def test_evaluate_expression_4(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('1+')\n self.assertFalse(result)\n\n def test_evaluate_expression_5(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('abc')\n self.assertFalse(result)",
"solution_code": "def answer(self, expression):\n if expression == 'pass':\n return self.get_my_cards()\n statistic = {}\n for c in expression:\n if c.isdigit() and int(c) in self.nums:\n statistic[c] = statistic.get(c, 0) + 1\n\n nums_used = statistic.copy()\n\n for num in self.nums:\n if nums_used.get(str(num), -100) != -100 and nums_used[str(num)] > 0:\n nums_used[str(num)] -= 1\n else:\n return False\n\n if all(count == 0 for count in nums_used.values()) == True:\n return self.evaluate_expression(expression)\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.nums"
],
"method_dependencies": [
"get_my_cards",
"evaluate_expression"
]
}
},
{
"method_name": "evaluate_expression",
"method_description": "def evaluate_expression(self, expression):\n \"\"\"\n Evaluate a mathematical expression and check if the result is 24.\n :param expression: string, mathematical expression\n :return: bool, True if the expression evaluates to 24, False otherwise\n >>> game = TwentyFourPointGame()\n >>> nums = [4, 3, 6, 6]\n >>> ans = \"4*3+6+6\"\n >>> ret = game.evaluate_expression(ans)\n True\n \"\"\"",
"test_class": "TwentyFourPointGameTest",
"test_code": "class TwentyFourPointGameTest(unittest.TestCase):\n def test_TwentyFourPointGame(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n game.nums = [4, 3, 6, 6]\n result = game.answer('4*3+6+6')\n self.assertTrue(result)\n result = game.evaluate_expression('4*3+6+6')\n self.assertTrue(result)",
"solution_code": "def evaluate_expression(self, expression):\n try:\n if eval(expression) == 24:\n return True\n else:\n return False\n except Exception as e:\n return False",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | TwentyFourPointGame | [
"TwentyFourPointGameTestGetMyCards",
"TwentyFourPointGameTestAnswer",
"TwentyFourPointGameTestEvaluateExpression",
"TwentyFourPointGameTest"
] | class TwentyFourPointGame:
def __init__(self) -> None:
self.nums = []
| [
"self.nums"
] |
ClassEval_90 | class URLHandler:
"""
The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment.
"""
def __init__(self, url):
"""
Initialize URLHandler's URL
"""
self.url = url
def get_scheme(self):
"""
get the scheme of the URL
:return: string, If successful, return the scheme of the URL
>>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page")
>>> urlhandler.get_scheme()
"https"
"""
def get_host(self):
"""
Get the second part of the URL, which is the host domain name
:return: string, If successful, return the host domain name of the URL
>>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page")
>>> urlhandler.get_host()
"www.baidu.com"
"""
def get_path(self):
"""
Get the third part of the URL, which is the address of the resource
:return: string, If successful, return the address of the resource of the URL
>>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page")
>>> urlhandler.get_path()
"/s?wd=aaa&rsv_spt=1#page"
"""
def get_query_params(self):
"""
Get the request parameters for the URL
:return: dict, If successful, return the request parameters of the URL
>>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page")
>>> urlhandler.get_query_params()
{"wd": "aaa", "rsv_spt": "1"}
"""
def get_fragment(self):
"""
Get the fragment after '#' in the URL
:return: string, If successful, return the fragment after '#' of the URL
>>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page")
>>> urlhandler.get_fragment()
"page"
""" | import unittest
class URLHandlerTestGetScheme(unittest.TestCase):
def test_get_scheme_1(self):
urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page")
temp = urlhandler.get_scheme()
self.assertEqual(temp, "https")
def test_get_scheme_2(self):
urlhandler = URLHandler(
"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN")
temp = urlhandler.get_scheme()
self.assertEqual(temp, "https")
def test_get_scheme_3(self):
urlhandler = URLHandler("https://github.com/openai/human-eval")
temp = urlhandler.get_scheme()
self.assertEqual(temp, "https")
def test_get_scheme_4(self):
urlhandler = URLHandler("aaa://github.com/openai/human-eval")
temp = urlhandler.get_scheme()
self.assertEqual(temp, "aaa")
def test_get_scheme_5(self):
urlhandler = URLHandler("bbb://github.com/openai/human-eval")
temp = urlhandler.get_scheme()
self.assertEqual(temp, "bbb")
def test_get_scheme_6(self):
urlhandler = URLHandler("abcdefg")
temp = urlhandler.get_scheme()
self.assertIsNone(temp)
class URLHandlerTestGetHost(unittest.TestCase):
def test_get_host_1(self):
urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page")
temp = urlhandler.get_host()
self.assertEqual(temp, "www.baidu.com")
def test_get_host_2(self):
urlhandler = URLHandler(
"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN")
temp = urlhandler.get_host()
self.assertEqual(temp, "www.bing.com")
def test_get_host_3(self):
urlhandler = URLHandler("https://github.com/openai/human-eval")
temp = urlhandler.get_host()
self.assertEqual(temp, "github.com")
def test_get_host_4(self):
urlhandler = URLHandler("https://aaa.com/openai/human-eval")
temp = urlhandler.get_host()
self.assertEqual(temp, "aaa.com")
def test_get_host_5(self):
urlhandler = URLHandler("https://bbb.com/openai/human-eval")
temp = urlhandler.get_host()
self.assertEqual(temp, "bbb.com")
def test_get_host_6(self):
urlhandler = URLHandler("abcdefg")
temp = urlhandler.get_host()
self.assertIsNone(temp)
def test_get_host_7(self):
urlhandler = URLHandler("https://bbb.com")
temp = urlhandler.get_host()
self.assertEqual(temp, "bbb.com")
def test_get_host_8(self):
urlhandler = URLHandler("https://bbb.com/")
temp = urlhandler.get_host()
self.assertEqual(temp, "bbb.com")
class URLHandlerTestGetPath(unittest.TestCase):
def test_get_path_1(self):
urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page")
temp = urlhandler.get_path()
self.assertEqual(temp, "/s?wd=aaa&rsv_spt=1#page")
def test_get_path_2(self):
urlhandler = URLHandler(
"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN")
temp = urlhandler.get_path()
self.assertEqual(temp,
"/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN")
def test_get_path_3(self):
urlhandler = URLHandler("https://github.com/openai/human-eval")
temp = urlhandler.get_path()
self.assertEqual(temp, "/openai/human-eval")
def test_get_path_4(self):
urlhandler = URLHandler("https://github.com/aaa/human-eval")
temp = urlhandler.get_path()
self.assertEqual(temp, "/aaa/human-eval")
def test_get_path_5(self):
urlhandler = URLHandler("https://github.com/bbb/human-eval")
temp = urlhandler.get_path()
self.assertEqual(temp, "/bbb/human-eval")
def test_get_path_6(self):
urlhandler = URLHandler("abcdefg")
temp = urlhandler.get_path()
self.assertIsNone(temp)
class URLHandlerTestGetQueryParams(unittest.TestCase):
def test_get_query_params_1(self):
urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page")
temp = urlhandler.get_query_params()
self.assertEqual(temp, {"wd": "aaa", "rsv_spt": "1"})
def test_get_query_params_2(self):
urlhandler = URLHandler(
"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531#")
temp = urlhandler.get_query_params()
self.assertEqual(temp, {"pglt": "41", "q": "humaneval", "cvid": "4dc2da2bb4bc429eb498c85245ae5253",
"aqs": "edge.0.0l7j69i61j69i60.10008j0j1", "FORM": "ANNTA1", "PC": "U531"})
def test_get_query_params_3(self):
urlhandler = URLHandler("https://github.com/openai/human-eval")
temp = urlhandler.get_query_params()
self.assertEqual(temp, None)
def test_get_query_params_4(self):
urlhandler = URLHandler("https://www.baidu.com/s?wd=bbb&rsv_spt=1#page")
temp = urlhandler.get_query_params()
self.assertEqual(temp, {"wd": "bbb", "rsv_spt": "1"})
def test_get_query_params_5(self):
urlhandler = URLHandler("https://www.baidu.com/s?wd=ccc&rsv_spt=1#page")
temp = urlhandler.get_query_params()
self.assertEqual(temp, {"wd": "ccc", "rsv_spt": "1"})
def test_get_query_params_6(self):
urlhandler = URLHandler("https://www.baidu.com/s?&#page")
temp = urlhandler.get_query_params()
self.assertEqual(temp, {})
class URLHandlerTestGetFragment(unittest.TestCase):
def test_get_fragment_1(self):
urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page")
temp = urlhandler.get_fragment()
self.assertEqual(temp, "page")
def test_get_fragment_2(self):
urlhandler = URLHandler(
"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN")
temp = urlhandler.get_fragment()
self.assertEqual(temp, None)
def test_get_fragment_3(self):
urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#aaa")
temp = urlhandler.get_fragment()
self.assertEqual(temp, "aaa")
def test_get_fragment_4(self):
urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#bbb")
temp = urlhandler.get_fragment()
self.assertEqual(temp, "bbb")
def test_get_fragment_5(self):
urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#ccc")
temp = urlhandler.get_fragment()
self.assertEqual(temp, "ccc")
class URLHandlerTest(unittest.TestCase):
def test_urlhandler(self):
urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page")
temp = urlhandler.get_scheme()
self.assertEqual(temp, "https")
temp = urlhandler.get_host()
self.assertEqual(temp, "www.baidu.com")
temp = urlhandler.get_path()
self.assertEqual(temp, "/s?wd=aaa&rsv_spt=1#page")
temp = urlhandler.get_query_params()
self.assertEqual(temp, {"wd": "aaa", "rsv_spt": "1"})
temp = urlhandler.get_fragment()
self.assertEqual(temp, "page") | class URLHandler:
def __init__(self, url):
self.url = url
def get_scheme(self):
scheme_end = self.url.find("://")
if scheme_end != -1:
return self.url[:scheme_end]
return None
def get_host(self):
scheme_end = self.url.find("://")
if scheme_end != -1:
url_without_scheme = self.url[scheme_end + 3:]
host_end = url_without_scheme.find("/")
if host_end != -1:
return url_without_scheme[:host_end]
return url_without_scheme
return None
def get_path(self):
scheme_end = self.url.find("://")
if scheme_end != -1:
url_without_scheme = self.url[scheme_end + 3:]
host_end = url_without_scheme.find("/")
if host_end != -1:
return url_without_scheme[host_end:]
return None
def get_query_params(self):
query_start = self.url.find("?")
fragment_start = self.url.find("#")
if query_start != -1:
query_string = self.url[query_start + 1:fragment_start]
params = {}
if len(query_string) > 0:
param_pairs = query_string.split("&")
for pair in param_pairs:
key_value = pair.split("=")
if len(key_value) == 2:
key, value = key_value
params[key] = value
return params
return None
def get_fragment(self):
fragment_start = self.url.find("#")
if fragment_start != -1:
return self.url[fragment_start + 1:]
return None | [] | """
The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment.
"""
| [
{
"method_name": "get_scheme",
"method_description": "def get_scheme(self):\n \"\"\"\n get the scheme of the URL\n :return: string, If successful, return the scheme of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_scheme()\n \"https\"\n \"\"\"",
"test_class": "URLHandlerTestGetScheme",
"test_code": "class URLHandlerTestGetScheme(unittest.TestCase):\n def test_get_scheme_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"https\")\n\n def test_get_scheme_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"https\")\n\n def test_get_scheme_3(self):\n urlhandler = URLHandler(\"https://github.com/openai/human-eval\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"https\")\n\n def test_get_scheme_4(self):\n urlhandler = URLHandler(\"aaa://github.com/openai/human-eval\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"aaa\")\n\n def test_get_scheme_5(self):\n urlhandler = URLHandler(\"bbb://github.com/openai/human-eval\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"bbb\")\n\n def test_get_scheme_6(self):\n urlhandler = URLHandler(\"abcdefg\")\n temp = urlhandler.get_scheme()\n self.assertIsNone(temp)",
"solution_code": "def get_scheme(self):\n scheme_end = self.url.find(\"://\")\n if scheme_end != -1:\n return self.url[:scheme_end]\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.url"
],
"method_dependencies": []
}
},
{
"method_name": "get_host",
"method_description": "def get_host(self):\n \"\"\"\n Get the second part of the URL, which is the host domain name\n :return: string, If successful, return the host domain name of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_host()\n \"www.baidu.com\"\n \"\"\"",
"test_class": "URLHandlerTestGetHost",
"test_code": "class URLHandlerTestGetHost(unittest.TestCase):\n def test_get_host_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"www.baidu.com\")\n\n def test_get_host_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"www.bing.com\")\n\n def test_get_host_3(self):\n urlhandler = URLHandler(\"https://github.com/openai/human-eval\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"github.com\")\n\n def test_get_host_4(self):\n urlhandler = URLHandler(\"https://aaa.com/openai/human-eval\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"aaa.com\")\n\n def test_get_host_5(self):\n urlhandler = URLHandler(\"https://bbb.com/openai/human-eval\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"bbb.com\")\n\n def test_get_host_6(self):\n urlhandler = URLHandler(\"abcdefg\")\n temp = urlhandler.get_host()\n self.assertIsNone(temp)\n\n def test_get_host_7(self):\n urlhandler = URLHandler(\"https://bbb.com\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"bbb.com\")\n\n def test_get_host_8(self):\n urlhandler = URLHandler(\"https://bbb.com/\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"bbb.com\")",
"solution_code": "def get_host(self):\n scheme_end = self.url.find(\"://\")\n if scheme_end != -1:\n url_without_scheme = self.url[scheme_end + 3:]\n host_end = url_without_scheme.find(\"/\")\n if host_end != -1:\n return url_without_scheme[:host_end]\n return url_without_scheme\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.url"
],
"method_dependencies": []
}
},
{
"method_name": "get_path",
"method_description": "def get_path(self):\n \"\"\"\n Get the third part of the URL, which is the address of the resource\n :return: string, If successful, return the address of the resource of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_path()\n \"/s?wd=aaa&rsv_spt=1#page\"\n \"\"\"",
"test_class": "URLHandlerTestGetPath",
"test_code": "class URLHandlerTestGetPath(unittest.TestCase):\n def test_get_path_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_path()\n self.assertEqual(temp, \"/s?wd=aaa&rsv_spt=1#page\")\n\n def test_get_path_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n temp = urlhandler.get_path()\n self.assertEqual(temp,\n \"/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n\n def test_get_path_3(self):\n urlhandler = URLHandler(\"https://github.com/openai/human-eval\")\n temp = urlhandler.get_path()\n self.assertEqual(temp, \"/openai/human-eval\")\n\n def test_get_path_4(self):\n urlhandler = URLHandler(\"https://github.com/aaa/human-eval\")\n temp = urlhandler.get_path()\n self.assertEqual(temp, \"/aaa/human-eval\")\n\n def test_get_path_5(self):\n urlhandler = URLHandler(\"https://github.com/bbb/human-eval\")\n temp = urlhandler.get_path()\n self.assertEqual(temp, \"/bbb/human-eval\")\n\n def test_get_path_6(self):\n urlhandler = URLHandler(\"abcdefg\")\n temp = urlhandler.get_path()\n self.assertIsNone(temp)",
"solution_code": "def get_path(self):\n scheme_end = self.url.find(\"://\")\n if scheme_end != -1:\n url_without_scheme = self.url[scheme_end + 3:]\n host_end = url_without_scheme.find(\"/\")\n if host_end != -1:\n return url_without_scheme[host_end:]\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.url"
],
"method_dependencies": []
}
},
{
"method_name": "get_query_params",
"method_description": "def get_query_params(self):\n \"\"\"\n Get the request parameters for the URL\n :return: dict, If successful, return the request parameters of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_query_params()\n {\"wd\": \"aaa\", \"rsv_spt\": \"1\"}\n \"\"\"",
"test_class": "URLHandlerTestGetQueryParams",
"test_code": "class URLHandlerTestGetQueryParams(unittest.TestCase):\n def test_get_query_params_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {\"wd\": \"aaa\", \"rsv_spt\": \"1\"})\n\n def test_get_query_params_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531#\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {\"pglt\": \"41\", \"q\": \"humaneval\", \"cvid\": \"4dc2da2bb4bc429eb498c85245ae5253\",\n \"aqs\": \"edge.0.0l7j69i61j69i60.10008j0j1\", \"FORM\": \"ANNTA1\", \"PC\": \"U531\"})\n\n def test_get_query_params_3(self):\n urlhandler = URLHandler(\"https://github.com/openai/human-eval\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, None)\n\n def test_get_query_params_4(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=bbb&rsv_spt=1#page\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {\"wd\": \"bbb\", \"rsv_spt\": \"1\"})\n\n def test_get_query_params_5(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=ccc&rsv_spt=1#page\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {\"wd\": \"ccc\", \"rsv_spt\": \"1\"})\n\n def test_get_query_params_6(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?&#page\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {})",
"solution_code": "def get_query_params(self):\n query_start = self.url.find(\"?\")\n fragment_start = self.url.find(\"#\")\n if query_start != -1:\n query_string = self.url[query_start + 1:fragment_start]\n params = {}\n if len(query_string) > 0:\n param_pairs = query_string.split(\"&\")\n for pair in param_pairs:\n key_value = pair.split(\"=\")\n if len(key_value) == 2:\n key, value = key_value\n params[key] = value\n return params\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.url"
],
"method_dependencies": []
}
},
{
"method_name": "get_fragment",
"method_description": "def get_fragment(self):\n \"\"\"\n Get the fragment after '#' in the URL\n :return: string, If successful, return the fragment after '#' of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_fragment()\n \"page\"\n \"\"\"",
"test_class": "URLHandlerTestGetFragment",
"test_code": "class URLHandlerTestGetFragment(unittest.TestCase):\n def test_get_fragment_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, \"page\")\n\n def test_get_fragment_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, None)\n\n def test_get_fragment_3(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#aaa\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, \"aaa\")\n\n def test_get_fragment_4(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#bbb\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, \"bbb\")\n\n def test_get_fragment_5(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#ccc\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, \"ccc\")",
"solution_code": "def get_fragment(self):\n fragment_start = self.url.find(\"#\")\n if fragment_start != -1:\n return self.url[fragment_start + 1:]\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.url"
],
"method_dependencies": []
}
}
] | URLHandler | [
"URLHandlerTestGetScheme",
"URLHandlerTestGetHost",
"URLHandlerTestGetPath",
"URLHandlerTestGetQueryParams",
"URLHandlerTestGetFragment",
"URLHandlerTest"
] | class URLHandler:
def __init__(self, url):
"""
Initialize URLHandler's URL
"""
self.url = url
| [
"self.url"
] |
ClassEval_91 | import urllib.parse
class UrlPath:
"""
The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding.
"""
def __init__(self):
"""
Initializes the UrlPath object with an empty list of segments and a flag indicating the presence of an end tag.
"""
self.segments = []
self.with_end_tag = False
def add(self, segment):
"""
Adds a segment to the list of segments in the UrlPath.
:param segment: str, the segment to add.
>>> url_path = UrlPath()
>>> url_path.add('foo')
>>> url_path.add('bar')
url_path.segments = ['foo', 'bar']
"""
def parse(self, path, charset):
"""
Parses a given path string and populates the list of segments in the UrlPath.
:param path: str, the path string to parse.
:param charset: str, the character encoding of the path string.
>>> url_path = UrlPath()
>>> url_path.parse('/foo/bar/', 'utf-8')
url_path.segments = ['foo', 'bar']
"""
@staticmethod
def fix_path(path):
"""
Fixes the given path string by removing leading and trailing slashes.
:param path: str, the path string to fix.
:return: str, the fixed path string.
>>> url_path = UrlPath()
>>> url_path.fix_path('/foo/bar/')
'foo/bar'
""" | import unittest
class UrlPathTestAdd(unittest.TestCase):
def test_add_1(self):
url_path = UrlPath()
url_path.add('foo')
url_path.add('bar')
self.assertEqual(url_path.segments, ['foo', 'bar'])
def test_add_2(self):
url_path = UrlPath()
url_path.add('aaa')
url_path.add('bbb')
self.assertEqual(url_path.segments, ['aaa', 'bbb'])
def test_add_3(self):
url_path = UrlPath()
url_path.add('123')
self.assertEqual(url_path.segments, ['123'])
def test_add_4(self):
url_path = UrlPath()
url_path.add('ddd')
self.assertEqual(url_path.segments, ['ddd'])
def test_add_5(self):
url_path = UrlPath()
url_path.add('eee')
self.assertEqual(url_path.segments, ['eee'])
class UrlPathTestParse(unittest.TestCase):
def test_parse_1(self):
url_path = UrlPath()
url_path.parse('/foo/bar/', 'utf-8')
self.assertEqual(url_path.segments, ['foo', 'bar'])
self.assertEqual(url_path.with_end_tag, True)
def test_parse_2(self):
url_path = UrlPath()
url_path.parse('aaa/bbb', 'utf-8')
self.assertEqual(url_path.segments, ['aaa', 'bbb'])
self.assertEqual(url_path.with_end_tag, False)
def test_parse_3(self):
url_path = UrlPath()
url_path.parse('/123/456/', 'utf-8')
self.assertEqual(url_path.segments, ['123', '456'])
self.assertEqual(url_path.with_end_tag, True)
def test_parse_4(self):
url_path = UrlPath()
url_path.parse('/123/456/789', 'utf-8')
self.assertEqual(url_path.segments, ['123', '456', '789'])
self.assertEqual(url_path.with_end_tag, False)
def test_parse_5(self):
url_path = UrlPath()
url_path.parse('/foo/bar', 'utf-8')
self.assertEqual(url_path.segments, ['foo', 'bar'])
self.assertEqual(url_path.with_end_tag, False)
def test_parse_6(self):
url_path = UrlPath()
url_path.parse('', 'utf-8')
self.assertEqual(url_path.segments, [])
self.assertEqual(url_path.with_end_tag, False)
def test_parse_7(self):
url_path = UrlPath()
url_path.parse('//', 'utf-8')
self.assertEqual(url_path.segments, [])
self.assertEqual(url_path.with_end_tag, True)
class UrlPathTestFixPath(unittest.TestCase):
def test_fix_path_1(self):
fixed_path = UrlPath.fix_path('/foo/bar/')
self.assertEqual(fixed_path, 'foo/bar')
def test_fix_path_2(self):
fixed_path = UrlPath.fix_path('/aaa/bbb/')
self.assertEqual(fixed_path, 'aaa/bbb')
def test_fix_path_3(self):
fixed_path = UrlPath.fix_path('/a/b/')
self.assertEqual(fixed_path, 'a/b')
def test_fix_path_4(self):
fixed_path = UrlPath.fix_path('/111/222/')
self.assertEqual(fixed_path, '111/222')
def test_fix_path_5(self):
fixed_path = UrlPath.fix_path('/a/')
self.assertEqual(fixed_path, 'a')
def test_fix_path_6(self):
fixed_path = UrlPath.fix_path('')
self.assertEqual(fixed_path, '')
class UrlPathTest(unittest.TestCase):
def test_urlpath(self):
url_path = UrlPath()
url_path.add('foo')
url_path.add('bar')
self.assertEqual(url_path.segments, ['foo', 'bar'])
url_path = UrlPath()
url_path.parse('/foo/bar/', 'utf-8')
self.assertEqual(url_path.segments, ['foo', 'bar'])
self.assertEqual(url_path.with_end_tag, True)
fixed_path = UrlPath.fix_path('/foo/bar/')
self.assertEqual(fixed_path, 'foo/bar') | import urllib.parse
class UrlPath:
def __init__(self):
self.segments = []
self.with_end_tag = False
def add(self, segment):
self.segments.append(self.fix_path(segment))
def parse(self, path, charset):
if path:
if path.endswith('/'):
self.with_end_tag = True
path = self.fix_path(path)
if path:
split = path.split('/')
for seg in split:
decoded_seg = urllib.parse.unquote(seg, encoding=charset)
self.segments.append(decoded_seg)
@staticmethod
def fix_path(path):
if not path:
return ''
segment_str = path.strip('/')
return segment_str | [
"import urllib.parse"
] | """
The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding.
"""
| [
{
"method_name": "add",
"method_description": "def add(self, segment):\n \"\"\"\n Adds a segment to the list of segments in the UrlPath.\n :param segment: str, the segment to add.\n >>> url_path = UrlPath()\n >>> url_path.add('foo')\n >>> url_path.add('bar')\n\n url_path.segments = ['foo', 'bar']\n \"\"\"",
"test_class": "UrlPathTestAdd",
"test_code": "class UrlPathTestAdd(unittest.TestCase):\n def test_add_1(self):\n url_path = UrlPath()\n url_path.add('foo')\n url_path.add('bar')\n self.assertEqual(url_path.segments, ['foo', 'bar'])\n\n def test_add_2(self):\n url_path = UrlPath()\n url_path.add('aaa')\n url_path.add('bbb')\n self.assertEqual(url_path.segments, ['aaa', 'bbb'])\n\n def test_add_3(self):\n url_path = UrlPath()\n url_path.add('123')\n self.assertEqual(url_path.segments, ['123'])\n\n def test_add_4(self):\n url_path = UrlPath()\n url_path.add('ddd')\n self.assertEqual(url_path.segments, ['ddd'])\n\n def test_add_5(self):\n url_path = UrlPath()\n url_path.add('eee')\n self.assertEqual(url_path.segments, ['eee'])",
"solution_code": "def add(self, segment):\n self.segments.append(self.fix_path(segment))",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.segments"
],
"method_dependencies": [
"fix_path"
]
}
},
{
"method_name": "parse",
"method_description": "def parse(self, path, charset):\n \"\"\"\n Parses a given path string and populates the list of segments in the UrlPath.\n :param path: str, the path string to parse.\n :param charset: str, the character encoding of the path string.\n >>> url_path = UrlPath()\n >>> url_path.parse('/foo/bar/', 'utf-8')\n\n url_path.segments = ['foo', 'bar']\n \"\"\"",
"test_class": "UrlPathTestParse",
"test_code": "class UrlPathTestParse(unittest.TestCase):\n def test_parse_1(self):\n url_path = UrlPath()\n url_path.parse('/foo/bar/', 'utf-8')\n self.assertEqual(url_path.segments, ['foo', 'bar'])\n self.assertEqual(url_path.with_end_tag, True)\n\n def test_parse_2(self):\n url_path = UrlPath()\n url_path.parse('aaa/bbb', 'utf-8')\n self.assertEqual(url_path.segments, ['aaa', 'bbb'])\n self.assertEqual(url_path.with_end_tag, False)\n\n def test_parse_3(self):\n url_path = UrlPath()\n url_path.parse('/123/456/', 'utf-8')\n self.assertEqual(url_path.segments, ['123', '456'])\n self.assertEqual(url_path.with_end_tag, True)\n\n def test_parse_4(self):\n url_path = UrlPath()\n url_path.parse('/123/456/789', 'utf-8')\n self.assertEqual(url_path.segments, ['123', '456', '789'])\n self.assertEqual(url_path.with_end_tag, False)\n\n def test_parse_5(self):\n url_path = UrlPath()\n url_path.parse('/foo/bar', 'utf-8')\n self.assertEqual(url_path.segments, ['foo', 'bar'])\n self.assertEqual(url_path.with_end_tag, False)\n\n def test_parse_6(self):\n url_path = UrlPath()\n url_path.parse('', 'utf-8')\n self.assertEqual(url_path.segments, [])\n self.assertEqual(url_path.with_end_tag, False)\n\n def test_parse_7(self):\n url_path = UrlPath()\n url_path.parse('//', 'utf-8')\n self.assertEqual(url_path.segments, [])\n self.assertEqual(url_path.with_end_tag, True)",
"solution_code": "def parse(self, path, charset):\n if path:\n if path.endswith('/'):\n self.with_end_tag = True\n\n path = self.fix_path(path)\n if path:\n split = path.split('/')\n for seg in split:\n decoded_seg = urllib.parse.unquote(seg, encoding=charset)\n self.segments.append(decoded_seg)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"urllib.parse"
],
"field_dependencies": [
"self.segments",
"self.with_end_tag"
],
"method_dependencies": [
"fix_path"
]
}
},
{
"method_name": "fix_path",
"method_description": "@staticmethod\n def fix_path(path):\n \"\"\"\n Fixes the given path string by removing leading and trailing slashes.\n :param path: str, the path string to fix.\n :return: str, the fixed path string.\n >>> url_path = UrlPath()\n >>> url_path.fix_path('/foo/bar/')\n 'foo/bar'\n\n \"\"\"",
"test_class": "UrlPathTestFixPath",
"test_code": "class UrlPathTestFixPath(unittest.TestCase):\n def test_fix_path_1(self):\n fixed_path = UrlPath.fix_path('/foo/bar/')\n self.assertEqual(fixed_path, 'foo/bar')\n\n def test_fix_path_2(self):\n fixed_path = UrlPath.fix_path('/aaa/bbb/')\n self.assertEqual(fixed_path, 'aaa/bbb')\n\n def test_fix_path_3(self):\n fixed_path = UrlPath.fix_path('/a/b/')\n self.assertEqual(fixed_path, 'a/b')\n\n def test_fix_path_4(self):\n fixed_path = UrlPath.fix_path('/111/222/')\n self.assertEqual(fixed_path, '111/222')\n\n def test_fix_path_5(self):\n fixed_path = UrlPath.fix_path('/a/')\n self.assertEqual(fixed_path, 'a')\n\n def test_fix_path_6(self):\n fixed_path = UrlPath.fix_path('')\n self.assertEqual(fixed_path, '')",
"solution_code": "@staticmethod\n def fix_path(path):\n if not path:\n return ''\n\n segment_str = path.strip('/')\n return segment_str",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | UrlPath | [
"UrlPathTestAdd",
"UrlPathTestParse",
"UrlPathTestFixPath",
"UrlPathTest"
] | class UrlPath:
def __init__(self):
"""
Initializes the UrlPath object with an empty list of segments and a flag indicating the presence of an end tag.
"""
self.segments = []
self.with_end_tag = False
| [
"self.segments",
"self.with_end_tag"
] |
ClassEval_92 | class UserLoginDB:
"""
This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login.
"""
def __init__(self, db_name):
"""
Initializes the UserLoginDB object with the specified database name.
:param db_name: str, the name of the SQLite database.
"""
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
def insert_user(self, username, password):
"""
Inserts a new user into the "users" table.
:param username: str, the username of the user.
:param password: str, the password of the user.
:return: None
>>> user_db = UserLoginDB("user_database.db")
>>> user_db.create_table()
>>> user_db.insert_user('user1', 'pass1')
"""
def search_user_by_username(self, username):
"""
Searches for users in the "users" table by username.
:param username: str, the username of the user to search for.
:return:list of tuples, the rows from the "users" table that match the search criteria.
>>> user_db = UserLoginDB("user_database.db")
>>> user_db.create_table()
>>> user_db.insert_user('user1', 'pass1')
>>> result = user_db.search_user_by_username('user1')
len(result) = 1
"""
def delete_user_by_username(self, username):
"""
Deletes a user from the "users" table by username.
:param username: str, the username of the user to delete.
:return: None
>>> user_db = UserLoginDB("user_database.db")
>>> user_db.create_table()
>>> user_db.insert_user('user1', 'pass1')
>>> user_db.delete_user_by_username('user1')
"""
def validate_user_login(self, username, password):
"""
Determine whether the user can log in, that is, the user is in the database and the password is correct
:param username:str, the username of the user to validate.
:param password:str, the password of the user to validate.
:return:bool, representing whether the user can log in correctly
>>> user_db = UserLoginDB("user_database.db")
>>> user_db.create_table()
>>> user_db.insert_user('user1', 'pass1')
>>> user_db.validate_user_login('user1', 'pass1')
True
""" | import unittest
import os
from tempfile import gettempdir
class UserLoginDBTestInsertUser(unittest.TestCase):
def setUp(self):
self.db_path = os.path.join(gettempdir(), 'test_db.db')
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
create_table_query = """
CREATE TABLE IF NOT EXISTS users (
username TEXT,
password TEXT
)
"""
cursor.execute(create_table_query)
conn.commit()
conn.close()
self.db = UserLoginDB(self.db_path)
def tearDown(self):
self.db.connection.close()
os.unlink(self.db_path)
def test_insert_user_1(self):
self.db.insert_user('user1', 'pass1')
user = self.db.search_user_by_username('user1')
self.assertIsNotNone(user)
self.assertEqual(user[0], 'user1')
self.assertEqual(user[1], 'pass1')
def test_insert_user_2(self):
self.db.insert_user('user2', 'pass2')
user = self.db.search_user_by_username('user2')
self.assertIsNotNone(user)
self.assertEqual(user[0], 'user2')
self.assertEqual(user[1], 'pass2')
def test_insert_user_3(self):
self.db.insert_user('user3', 'pass3')
user = self.db.search_user_by_username('user3')
self.assertIsNotNone(user)
self.assertEqual(user[0], 'user3')
self.assertEqual(user[1], 'pass3')
def test_insert_user_4(self):
self.db.insert_user('user4', 'pass4')
user = self.db.search_user_by_username('user4')
self.assertIsNotNone(user)
self.assertEqual(user[0], 'user4')
self.assertEqual(user[1], 'pass4')
def test_insert_user_5(self):
self.db.insert_user('user5', 'pass5')
user = self.db.search_user_by_username('user5')
self.assertIsNotNone(user)
self.assertEqual(user[0], 'user5')
self.assertEqual(user[1], 'pass5')
class UserLoginDBTestSearchUserByUsername(unittest.TestCase):
def setUp(self):
self.db_path = os.path.join(gettempdir(), 'test_db.db')
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
create_table_query = """
CREATE TABLE IF NOT EXISTS users (
username TEXT,
password TEXT
)
"""
cursor.execute(create_table_query)
conn.commit()
conn.close()
self.db = UserLoginDB(self.db_path)
def tearDown(self):
self.db.connection.close()
os.unlink(self.db_path)
def test_search_user_by_username_1(self):
self.db.insert_user('user1', 'pass1')
user = self.db.search_user_by_username('user1')
self.assertIsNotNone(user)
self.assertEqual(user[0], 'user1')
self.assertEqual(user[1], 'pass1')
def test_search_user_by_username_2(self):
self.db.insert_user('user2', 'pass2')
user = self.db.search_user_by_username('user2')
self.assertIsNotNone(user)
self.assertEqual(user[0], 'user2')
self.assertEqual(user[1], 'pass2')
def test_search_user_by_username_3(self):
self.db.insert_user('user3', 'pass3')
user = self.db.search_user_by_username('user3')
self.assertIsNotNone(user)
self.assertEqual(user[0], 'user3')
self.assertEqual(user[1], 'pass3')
def test_search_user_by_username_4(self):
self.db.insert_user('user4', 'pass4')
user = self.db.search_user_by_username('user4')
self.assertIsNotNone(user)
self.assertEqual(user[0], 'user4')
self.assertEqual(user[1], 'pass4')
def test_search_user_by_username_5(self):
self.db.insert_user('user5', 'pass5')
user = self.db.search_user_by_username('user5')
self.assertIsNotNone(user)
self.assertEqual(user[0], 'user5')
self.assertEqual(user[1], 'pass5')
class UserLoginDBTestDeleteUserByUsername(unittest.TestCase):
def setUp(self):
self.db_path = os.path.join(gettempdir(), 'test_db.db')
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
create_table_query = """
CREATE TABLE IF NOT EXISTS users (
username TEXT,
password TEXT
)
"""
cursor.execute(create_table_query)
conn.commit()
conn.close()
self.db = UserLoginDB(self.db_path)
def tearDown(self):
self.db.connection.close()
os.unlink(self.db_path)
def test_delete_user_by_username_1(self):
self.db.insert_user('user1', 'pass1')
self.db.delete_user_by_username('user1')
user = self.db.search_user_by_username('user1')
self.assertIsNone(user)
def test_delete_user_by_username_2(self):
self.db.insert_user('user2', 'pass2')
self.db.delete_user_by_username('user2')
user = self.db.search_user_by_username('user2')
self.assertIsNone(user)
def test_delete_user_by_username_3(self):
self.db.insert_user('user3', 'pass3')
self.db.delete_user_by_username('user3')
user = self.db.search_user_by_username('user3')
self.assertIsNone(user)
def test_delete_user_by_username_4(self):
self.db.insert_user('user4', 'pass4')
self.db.delete_user_by_username('user4')
user = self.db.search_user_by_username('user4')
self.assertIsNone(user)
def test_delete_user_by_username_5(self):
self.db.insert_user('user5', 'pass5')
self.db.delete_user_by_username('user5')
user = self.db.search_user_by_username('user5')
self.assertIsNone(user)
class UserLoginDBTestValidateUserLogin(unittest.TestCase):
def setUp(self):
self.db_path = os.path.join(gettempdir(), 'test_db.db')
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
create_table_query = """
CREATE TABLE IF NOT EXISTS users (
username TEXT,
password TEXT
)
"""
cursor.execute(create_table_query)
conn.commit()
conn.close()
self.db = UserLoginDB(self.db_path)
def tearDown(self):
self.db.connection.close()
os.unlink(self.db_path)
def test_validate_user_login_1(self):
self.db.insert_user('user1', 'pass1')
valid = self.db.validate_user_login('user1', 'pass1')
self.assertTrue(valid)
def test_validate_user_login_2(self):
self.db.insert_user('user1', 'pass1')
invalid = self.db.validate_user_login('user1', 'wrongpass')
self.assertFalse(invalid)
def test_validate_user_login_3(self):
valid = self.db.validate_user_login('nonexistentuser', 'somepass')
self.assertFalse(valid)
def test_validate_user_login_4(self):
self.db.insert_user('user2', 'pass2')
valid = self.db.validate_user_login('user2', 'pass2')
self.assertTrue(valid)
def test_validate_user_login_5(self):
self.db.insert_user('user3', 'pass3')
valid = self.db.validate_user_login('user3', 'pass3')
self.assertTrue(valid)
class UserLoginDBTest(unittest.TestCase):
def setUp(self):
self.db_path = os.path.join(gettempdir(), 'test_db.db')
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
create_table_query = """
CREATE TABLE IF NOT EXISTS users (
username TEXT,
password TEXT
)
"""
cursor.execute(create_table_query)
conn.commit()
conn.close()
self.db = UserLoginDB(self.db_path)
def tearDown(self):
self.db.connection.close()
os.unlink(self.db_path)
def test_UserLoginDB(self):
self.db.insert_user('user1', 'pass1')
user = self.db.search_user_by_username('user1')
self.assertIsNotNone(user)
self.assertEqual(user[0], 'user1')
self.assertEqual(user[1], 'pass1')
self.db.delete_user_by_username('user1')
user = self.db.search_user_by_username('user1')
self.assertIsNone(user)
self.db.insert_user('user1', 'pass1')
valid = self.db.validate_user_login('user1', 'pass1')
self.assertTrue(valid) | import sqlite3
class UserLoginDB:
def __init__(self, db_name):
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
def insert_user(self, username, password):
self.cursor.execute('''
INSERT INTO users (username, password)
VALUES (?, ?)
''', (username, password))
self.connection.commit()
def search_user_by_username(self, username):
self.cursor.execute('''
SELECT * FROM users WHERE username = ?
''', (username,))
user = self.cursor.fetchone()
return user
def delete_user_by_username(self, username):
self.cursor.execute('''
DELETE FROM users WHERE username = ?
''', (username,))
self.connection.commit()
def validate_user_login(self, username, password):
user = self.search_user_by_username(username)
if user is not None and user[1] == password:
return True
return False | [
"import sqlite3"
] | """
This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login.
"""
| [
{
"method_name": "insert_user",
"method_description": "def insert_user(self, username, password):\n \"\"\"\n Inserts a new user into the \"users\" table.\n :param username: str, the username of the user.\n :param password: str, the password of the user.\n :return: None\n >>> user_db = UserLoginDB(\"user_database.db\")\n >>> user_db.create_table()\n >>> user_db.insert_user('user1', 'pass1')\n \"\"\"",
"test_class": "UserLoginDBTestInsertUser",
"test_code": "class UserLoginDBTestInsertUser(unittest.TestCase):\n def setUp(self):\n self.db_path = os.path.join(gettempdir(), 'test_db.db')\n conn = sqlite3.connect(self.db_path)\n cursor = conn.cursor()\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n username TEXT,\n password TEXT\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n self.db = UserLoginDB(self.db_path)\n\n def tearDown(self):\n self.db.connection.close()\n os.unlink(self.db_path)\n\n def test_insert_user_1(self):\n self.db.insert_user('user1', 'pass1')\n user = self.db.search_user_by_username('user1')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user1')\n self.assertEqual(user[1], 'pass1')\n\n def test_insert_user_2(self):\n self.db.insert_user('user2', 'pass2')\n user = self.db.search_user_by_username('user2')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user2')\n self.assertEqual(user[1], 'pass2')\n\n def test_insert_user_3(self):\n self.db.insert_user('user3', 'pass3')\n user = self.db.search_user_by_username('user3')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user3')\n self.assertEqual(user[1], 'pass3')\n\n def test_insert_user_4(self):\n self.db.insert_user('user4', 'pass4')\n user = self.db.search_user_by_username('user4')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user4')\n self.assertEqual(user[1], 'pass4')\n\n def test_insert_user_5(self):\n self.db.insert_user('user5', 'pass5')\n user = self.db.search_user_by_username('user5')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user5')\n self.assertEqual(user[1], 'pass5')",
"solution_code": "def insert_user(self, username, password):\n self.cursor.execute('''\n INSERT INTO users (username, password)\n VALUES (?, ?)\n ''', (username, password))\n self.connection.commit()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.connection",
"self.cursor"
],
"method_dependencies": []
}
},
{
"method_name": "search_user_by_username",
"method_description": "def search_user_by_username(self, username):\n \"\"\"\n Searches for users in the \"users\" table by username.\n :param username: str, the username of the user to search for.\n :return:list of tuples, the rows from the \"users\" table that match the search criteria.\n >>> user_db = UserLoginDB(\"user_database.db\")\n >>> user_db.create_table()\n >>> user_db.insert_user('user1', 'pass1')\n >>> result = user_db.search_user_by_username('user1')\n len(result) = 1\n \"\"\"",
"test_class": "UserLoginDBTestSearchUserByUsername",
"test_code": "class UserLoginDBTestSearchUserByUsername(unittest.TestCase):\n def setUp(self):\n self.db_path = os.path.join(gettempdir(), 'test_db.db')\n conn = sqlite3.connect(self.db_path)\n cursor = conn.cursor()\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n username TEXT,\n password TEXT\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n self.db = UserLoginDB(self.db_path)\n\n def tearDown(self):\n self.db.connection.close()\n os.unlink(self.db_path)\n\n def test_search_user_by_username_1(self):\n self.db.insert_user('user1', 'pass1')\n user = self.db.search_user_by_username('user1')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user1')\n self.assertEqual(user[1], 'pass1')\n\n def test_search_user_by_username_2(self):\n self.db.insert_user('user2', 'pass2')\n user = self.db.search_user_by_username('user2')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user2')\n self.assertEqual(user[1], 'pass2')\n\n def test_search_user_by_username_3(self):\n self.db.insert_user('user3', 'pass3')\n user = self.db.search_user_by_username('user3')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user3')\n self.assertEqual(user[1], 'pass3')\n\n def test_search_user_by_username_4(self):\n self.db.insert_user('user4', 'pass4')\n user = self.db.search_user_by_username('user4')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user4')\n self.assertEqual(user[1], 'pass4')\n\n def test_search_user_by_username_5(self):\n self.db.insert_user('user5', 'pass5')\n user = self.db.search_user_by_username('user5')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user5')\n self.assertEqual(user[1], 'pass5')",
"solution_code": "def search_user_by_username(self, username):\n self.cursor.execute('''\n SELECT * FROM users WHERE username = ?\n ''', (username,))\n user = self.cursor.fetchone()\n return user",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.cursor"
],
"method_dependencies": []
}
},
{
"method_name": "delete_user_by_username",
"method_description": "def delete_user_by_username(self, username):\n \"\"\"\n Deletes a user from the \"users\" table by username.\n :param username: str, the username of the user to delete.\n :return: None\n >>> user_db = UserLoginDB(\"user_database.db\")\n >>> user_db.create_table()\n >>> user_db.insert_user('user1', 'pass1')\n >>> user_db.delete_user_by_username('user1')\n \"\"\"",
"test_class": "UserLoginDBTestDeleteUserByUsername",
"test_code": "class UserLoginDBTestDeleteUserByUsername(unittest.TestCase):\n def setUp(self):\n self.db_path = os.path.join(gettempdir(), 'test_db.db')\n conn = sqlite3.connect(self.db_path)\n cursor = conn.cursor()\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n username TEXT,\n password TEXT\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n self.db = UserLoginDB(self.db_path)\n\n def tearDown(self):\n self.db.connection.close()\n os.unlink(self.db_path)\n\n def test_delete_user_by_username_1(self):\n self.db.insert_user('user1', 'pass1')\n self.db.delete_user_by_username('user1')\n user = self.db.search_user_by_username('user1')\n self.assertIsNone(user)\n\n def test_delete_user_by_username_2(self):\n self.db.insert_user('user2', 'pass2')\n self.db.delete_user_by_username('user2')\n user = self.db.search_user_by_username('user2')\n self.assertIsNone(user)\n\n def test_delete_user_by_username_3(self):\n self.db.insert_user('user3', 'pass3')\n self.db.delete_user_by_username('user3')\n user = self.db.search_user_by_username('user3')\n self.assertIsNone(user)\n\n def test_delete_user_by_username_4(self):\n self.db.insert_user('user4', 'pass4')\n self.db.delete_user_by_username('user4')\n user = self.db.search_user_by_username('user4')\n self.assertIsNone(user)\n\n def test_delete_user_by_username_5(self):\n self.db.insert_user('user5', 'pass5')\n self.db.delete_user_by_username('user5')\n user = self.db.search_user_by_username('user5')\n self.assertIsNone(user)",
"solution_code": "def delete_user_by_username(self, username):\n self.cursor.execute('''\n DELETE FROM users WHERE username = ?\n ''', (username,))\n self.connection.commit()",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.connection",
"self.cursor"
],
"method_dependencies": []
}
},
{
"method_name": "validate_user_login",
"method_description": "def validate_user_login(self, username, password):\n \"\"\"\n Determine whether the user can log in, that is, the user is in the database and the password is correct\n :param username:str, the username of the user to validate.\n :param password:str, the password of the user to validate.\n :return:bool, representing whether the user can log in correctly\n >>> user_db = UserLoginDB(\"user_database.db\")\n >>> user_db.create_table()\n >>> user_db.insert_user('user1', 'pass1')\n >>> user_db.validate_user_login('user1', 'pass1')\n True\n \"\"\"",
"test_class": "UserLoginDBTestValidateUserLogin",
"test_code": "class UserLoginDBTestValidateUserLogin(unittest.TestCase):\n def setUp(self):\n self.db_path = os.path.join(gettempdir(), 'test_db.db')\n conn = sqlite3.connect(self.db_path)\n cursor = conn.cursor()\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n username TEXT,\n password TEXT\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n self.db = UserLoginDB(self.db_path)\n\n def tearDown(self):\n self.db.connection.close()\n os.unlink(self.db_path)\n\n def test_validate_user_login_1(self):\n self.db.insert_user('user1', 'pass1')\n valid = self.db.validate_user_login('user1', 'pass1')\n self.assertTrue(valid)\n\n def test_validate_user_login_2(self):\n self.db.insert_user('user1', 'pass1')\n invalid = self.db.validate_user_login('user1', 'wrongpass')\n self.assertFalse(invalid)\n\n def test_validate_user_login_3(self):\n valid = self.db.validate_user_login('nonexistentuser', 'somepass')\n self.assertFalse(valid)\n\n def test_validate_user_login_4(self):\n self.db.insert_user('user2', 'pass2')\n valid = self.db.validate_user_login('user2', 'pass2')\n self.assertTrue(valid)\n\n def test_validate_user_login_5(self):\n self.db.insert_user('user3', 'pass3')\n valid = self.db.validate_user_login('user3', 'pass3')\n self.assertTrue(valid)",
"solution_code": "def validate_user_login(self, username, password):\n user = self.search_user_by_username(username)\n if user is not None and user[1] == password:\n return True\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": [
"search_user_by_username"
]
}
}
] | UserLoginDB | [
"UserLoginDBTestInsertUser",
"UserLoginDBTestSearchUserByUsername",
"UserLoginDBTestDeleteUserByUsername",
"UserLoginDBTestValidateUserLogin",
"UserLoginDBTest"
] | class UserLoginDB:
def __init__(self, db_name):
"""
Initializes the UserLoginDB object with the specified database name.
:param db_name: str, the name of the SQLite database.
"""
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cursor()
| [
"self.connection",
"self.cursor"
] |
ClassEval_93 | import numpy as np
from gensim import matutils
from numpy import dot, array
class VectorUtil:
"""
The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights.
"""
@staticmethod
def similarity(vector_1, vector_2):
"""
Compute the cosine similarity between one vector and another vector.
:param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,).
:param vector_2: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,).
:return: numpy.ndarray, Contains cosine distance between `vector_1` and `vector_2`
>>> vector_1 = np.array([1, 1])
>>> vector_2 = np.array([1, 0])
>>> VectorUtil.similarity(vector_1, vector_2)
0.7071067811865475
"""
@staticmethod
def cosine_similarities(vector_1, vectors_all):
"""
Compute cosine similarities between one vector and a set of other vectors.
:param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,).
:param vectors_all: list of numpy.ndarray, For each row in vectors_all, distance from vector_1 is computed, expected shape (num_vectors, dim).
:return: numpy.ndarray, Contains cosine distance between `vector_1` and each row in `vectors_all`, shape (num_vectors,).
>>> vector1 = np.array([1, 2, 3])
>>> vectors_all = [np.array([4, 5, 6]), np.array([7, 8, 9])]
>>> VectorUtil.cosine_similarities(vector1, vectors_all)
[0.97463185 0.95941195]
"""
@staticmethod
def n_similarity(vector_list_1, vector_list_2):
"""
Compute cosine similarity between two sets of vectors.
:param vector_list_1: list of numpy vector
:param vector_list_2: list of numpy vector
:return: numpy.ndarray, Similarities between vector_list_1 and vector_list_2.
>>> vector_list1 = [np.array([1, 2, 3]), np.array([4, 5, 6])]
>>> vector_list2 = [np.array([7, 8, 9]), np.array([10, 11, 12])]
>>> VectorUtil.n_similarity(vector_list1, vector_list2)
0.9897287473881233
"""
@staticmethod
def compute_idf_weight_dict(total_num, number_dict):
"""
Calculate log(total_num+1/count+1) for each count in number_dict
:param total_num: int
:param number_dict: dict
:return: dict
>>> num_dict = {'key1':0.1, 'key2':0.5}
>>> VectorUtil.compute_idf_weight_dict(2, num_dict)
{'key1': 1.0033021088637848, 'key2': 0.6931471805599453}
""" | import unittest
class VectorUtilTestSimilarity(unittest.TestCase):
def test_similarity_1(self):
vector_1 = np.array([1, 1])
vector_2 = np.array([1, 0])
similarity = VectorUtil.similarity(vector_1, vector_2)
self.assertAlmostEqual(similarity, 0.7071067811865475)
def test_similarity_2(self):
vector_1 = np.array([1, 1])
vector_2 = np.array([0, 0])
similarity = VectorUtil.similarity(vector_1, vector_2)
self.assertAlmostEqual(similarity, 0.0)
def test_similarity_3(self):
vector_1 = np.array([1, 1])
vector_2 = np.array([1, 1])
similarity = VectorUtil.similarity(vector_1, vector_2)
self.assertAlmostEqual(similarity, 1.0)
def test_similarity_4(self):
vector_1 = np.array([1, 1, 0, 1, 0, 1, 0, 1])
vector_2 = np.array([1, 0, 0, 1, 0, 1, 0, 1])
similarity = VectorUtil.similarity(vector_1, vector_2)
self.assertAlmostEqual(similarity, 0.8944271909999159)
def test_similarity_5(self):
vector_1 = np.array([1, 1, 1, 1, 1, 1, 1, 1])
vector_2 = np.array([0, 0, 0, 0, 0, 0, 0, 0])
similarity = VectorUtil.similarity(vector_1, vector_2)
self.assertAlmostEqual(similarity, 0.0)
class VectorUtilTestCosineSimilarities(unittest.TestCase):
def test_cosine_similarities_1(self):
vector1 = np.array([1, 1])
vectors_all = [np.array([1, 0]), np.array([1, 1])]
similarities = VectorUtil.cosine_similarities(vector1, vectors_all)
res = [0.7071067811865475, 1.0]
for index, item in enumerate(similarities):
self.assertAlmostEqual(item, res[index])
def test_cosine_similarities_2(self):
vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])
vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([1, 1, 0, 1, 1, 1, 1, 0])]
similarities = VectorUtil.cosine_similarities(vector1, vectors_all)
res = [0.8660254037844387, 0.8164965809277261]
for index, item in enumerate(similarities):
self.assertAlmostEqual(item, res[index])
def test_cosine_similarities_3(self):
vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])
vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([1, 1, 1, 1, 1, 1, 1, 0])]
similarities = VectorUtil.cosine_similarities(vector1, vectors_all)
res = [0.8660254037844387, 0.7559289460184544]
for index, item in enumerate(similarities):
self.assertAlmostEqual(item, res[index])
def test_cosine_similarities_4(self):
vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])
vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([1, 1, 1, 1, 1, 1, 1, 1])]
similarities = VectorUtil.cosine_similarities(vector1, vectors_all)
res = [0.8660254037844387, 0.7071067811865475]
for index, item in enumerate(similarities):
self.assertAlmostEqual(item, res[index])
def test_cosine_similarities_5(self):
vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])
vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([0, 1, 1, 1, 1, 1, 1, 1])]
similarities = VectorUtil.cosine_similarities(vector1, vectors_all)
res = [0.8660254037844387, 0.5669467095138409]
for index, item in enumerate(similarities):
self.assertAlmostEqual(item, res[index])
class VectorUtilTestNSimilarity(unittest.TestCase):
def test_n_similarity_1(self):
vector_list1 = [np.array([1, 0]), np.array([0, 1])]
vector_list2 = [np.array([0, 0]), np.array([1, 1])]
similarity = VectorUtil.n_similarity(vector_list1, vector_list2)
self.assertAlmostEqual(similarity, 1.0)
def test_n_similarity_2(self):
vector_list1 = [np.array([1, 1]), np.array([0, 1])]
vector_list2 = [np.array([0, 0]), np.array([1, 1])]
similarity = VectorUtil.n_similarity(vector_list1, vector_list2)
self.assertAlmostEqual(similarity, 0.9486832980505137)
def test_n_similarity_3(self):
vector_list1 = [np.array([1, 0]), np.array([1, 1])]
vector_list2 = [np.array([0, 0]), np.array([1, 1])]
similarity = VectorUtil.n_similarity(vector_list1, vector_list2)
self.assertAlmostEqual(similarity, 0.9486832980505137)
def test_n_similarity_4(self):
vector_list1 = [np.array([1, 0]), np.array([0, 1])]
vector_list2 = [np.array([1, 0]), np.array([1, 1])]
similarity = VectorUtil.n_similarity(vector_list1, vector_list2)
self.assertAlmostEqual(similarity, 0.9486832980505137)
def test_n_similarity_5(self):
vector_list1 = [np.array([1, 0]), np.array([0, 1])]
vector_list2 = [np.array([0, 1]), np.array([1, 1])]
similarity = VectorUtil.n_similarity(vector_list1, vector_list2)
self.assertAlmostEqual(similarity, 0.9486832980505137)
def test_n_similarity_6(self):
try:
vector_list1 = []
vector_list2 = []
similarity = VectorUtil.n_similarity(vector_list1, vector_list2)
except:
pass
class VectorUtilTestComputeIdfWeightDict(unittest.TestCase):
def test_compute_idf_weight_dict_1(self):
num_dict = {'key1': 0.1, 'key2': 0.5}
res = VectorUtil.compute_idf_weight_dict(2, num_dict)
self.assertAlmostEqual(res['key1'], 1.0033021088637848)
self.assertAlmostEqual(res['key2'], 0.6931471805599453)
def test_compute_idf_weight_dict_2(self):
num_dict = {'key1': 0.2, 'key2': 0.5}
res = VectorUtil.compute_idf_weight_dict(2, num_dict)
self.assertAlmostEqual(res['key1'], 0.9162907318741551)
self.assertAlmostEqual(res['key2'], 0.6931471805599453)
def test_compute_idf_weight_dict_3(self):
num_dict = {'key1': 0.3, 'key2': 0.5}
res = VectorUtil.compute_idf_weight_dict(2, num_dict)
self.assertAlmostEqual(res['key1'], 0.8362480242006185)
self.assertAlmostEqual(res['key2'], 0.6931471805599453)
def test_compute_idf_weight_dict_4(self):
num_dict = {'key1': 0.4, 'key2': 0.5}
res = VectorUtil.compute_idf_weight_dict(2, num_dict)
self.assertAlmostEqual(res['key1'], 0.7621400520468967)
self.assertAlmostEqual(res['key2'], 0.6931471805599453)
def test_compute_idf_weight_dict_5(self):
num_dict = {'key1': 0.5, 'key2': 0.5}
res = VectorUtil.compute_idf_weight_dict(2, num_dict)
self.assertAlmostEqual(res['key1'], 0.6931471805599453)
self.assertAlmostEqual(res['key2'], 0.6931471805599453)
class VectorUtilTest(unittest.TestCase):
def test_vectorutil(self):
vector_1 = np.array([1, 1])
vector_2 = np.array([1, 0])
similarity = VectorUtil.similarity(vector_1, vector_2)
self.assertAlmostEqual(similarity, 0.7071067811865475)
vector1 = np.array([1, 1])
vectors_all = [np.array([1, 0]), np.array([1, 1])]
similarities = VectorUtil.cosine_similarities(vector1, vectors_all)
res = [0.7071067811865475, 1.0]
for index, item in enumerate(similarities):
self.assertAlmostEqual(item, res[index])
vector_list1 = [np.array([1, 0]), np.array([0, 1])]
vector_list2 = [np.array([0, 0]), np.array([1, 1])]
similarity = VectorUtil.n_similarity(vector_list1, vector_list2)
self.assertAlmostEqual(similarity, 1.0)
num_dict = {'key1': 0.1, 'key2': 0.5}
res = VectorUtil.compute_idf_weight_dict(2, num_dict)
self.assertAlmostEqual(res['key1'], 1.0033021088637848)
self.assertAlmostEqual(res['key2'], 0.6931471805599453) | import numpy as np
from gensim import matutils
from numpy import dot, array
class VectorUtil:
@staticmethod
def similarity(vector_1, vector_2):
return dot(matutils.unitvec(vector_1), matutils.unitvec(vector_2))
@staticmethod
def cosine_similarities(vector_1, vectors_all):
norm = np.linalg.norm(vector_1)
all_norms = np.linalg.norm(vectors_all, axis=1)
dot_products = dot(vectors_all, vector_1)
similarities = dot_products / (norm * all_norms)
return similarities
@staticmethod
def n_similarity(vector_list_1, vector_list_2):
if not (len(vector_list_1) and len(vector_list_2)):
raise ZeroDivisionError('At least one of the passed list is empty.')
return dot(matutils.unitvec(array(vector_list_1).mean(axis=0)),
matutils.unitvec(array(vector_list_2).mean(axis=0)))
@staticmethod
def compute_idf_weight_dict(total_num, number_dict):
index_2_key_map = {}
index = 0
count_list = []
for key, count in number_dict.items():
index_2_key_map[index] = key
count_list.append(count)
index = index + 1
a = np.array(count_list)
## smooth, in case the divide by zero error
a = np.log((total_num + 1) / (a + 1))
result = {}
for index, w in enumerate(a):
key = index_2_key_map[index]
result[key] = w
return result | [
"import numpy as np",
"from gensim import matutils",
"from numpy import dot, array"
] | """
The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights.
"""
| [
{
"method_name": "similarity",
"method_description": "def similarity(vector_1, vector_2):\n \"\"\"\n Compute the cosine similarity between one vector and another vector.\n :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,).\n :param vector_2: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,).\n :return: numpy.ndarray, Contains cosine distance between `vector_1` and `vector_2`\n >>> vector_1 = np.array([1, 1])\n >>> vector_2 = np.array([1, 0])\n >>> VectorUtil.similarity(vector_1, vector_2)\n 0.7071067811865475\n \"\"\"",
"test_class": "VectorUtilTestSimilarity",
"test_code": "class VectorUtilTestSimilarity(unittest.TestCase):\n def test_similarity_1(self):\n vector_1 = np.array([1, 1])\n vector_2 = np.array([1, 0])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 0.7071067811865475)\n\n def test_similarity_2(self):\n vector_1 = np.array([1, 1])\n vector_2 = np.array([0, 0])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 0.0)\n\n def test_similarity_3(self):\n vector_1 = np.array([1, 1])\n vector_2 = np.array([1, 1])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 1.0)\n\n def test_similarity_4(self):\n vector_1 = np.array([1, 1, 0, 1, 0, 1, 0, 1])\n vector_2 = np.array([1, 0, 0, 1, 0, 1, 0, 1])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 0.8944271909999159)\n\n def test_similarity_5(self):\n vector_1 = np.array([1, 1, 1, 1, 1, 1, 1, 1])\n vector_2 = np.array([0, 0, 0, 0, 0, 0, 0, 0])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 0.0)",
"solution_code": "def similarity(vector_1, vector_2):\n return dot(matutils.unitvec(vector_1), matutils.unitvec(vector_2))",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"matutils"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "cosine_similarities",
"method_description": "@staticmethod\n def cosine_similarities(vector_1, vectors_all):\n \"\"\"\n Compute cosine similarities between one vector and a set of other vectors.\n :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,).\n :param vectors_all: list of numpy.ndarray, For each row in vectors_all, distance from vector_1 is computed, expected shape (num_vectors, dim).\n :return: numpy.ndarray, Contains cosine distance between `vector_1` and each row in `vectors_all`, shape (num_vectors,).\n >>> vector1 = np.array([1, 2, 3])\n >>> vectors_all = [np.array([4, 5, 6]), np.array([7, 8, 9])]\n >>> VectorUtil.cosine_similarities(vector1, vectors_all)\n [0.97463185 0.95941195]\n \"\"\"",
"test_class": "VectorUtilTestCosineSimilarities",
"test_code": "class VectorUtilTestCosineSimilarities(unittest.TestCase):\n def test_cosine_similarities_1(self):\n vector1 = np.array([1, 1])\n vectors_all = [np.array([1, 0]), np.array([1, 1])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.7071067811865475, 1.0]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n def test_cosine_similarities_2(self):\n vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])\n vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([1, 1, 0, 1, 1, 1, 1, 0])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.8660254037844387, 0.8164965809277261]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n def test_cosine_similarities_3(self):\n vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])\n vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([1, 1, 1, 1, 1, 1, 1, 0])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.8660254037844387, 0.7559289460184544]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n def test_cosine_similarities_4(self):\n vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])\n vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([1, 1, 1, 1, 1, 1, 1, 1])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.8660254037844387, 0.7071067811865475]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n def test_cosine_similarities_5(self):\n vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])\n vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([0, 1, 1, 1, 1, 1, 1, 1])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.8660254037844387, 0.5669467095138409]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])",
"solution_code": "@staticmethod\n def cosine_similarities(vector_1, vectors_all):\n norm = np.linalg.norm(vector_1)\n all_norms = np.linalg.norm(vectors_all, axis=1)\n dot_products = dot(vectors_all, vector_1)\n similarities = dot_products / (norm * all_norms)\n return similarities",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "n_similarity",
"method_description": "@staticmethod\n def n_similarity(vector_list_1, vector_list_2):\n \"\"\"\n Compute cosine similarity between two sets of vectors.\n :param vector_list_1: list of numpy vector\n :param vector_list_2: list of numpy vector\n :return: numpy.ndarray, Similarities between vector_list_1 and vector_list_2.\n >>> vector_list1 = [np.array([1, 2, 3]), np.array([4, 5, 6])]\n >>> vector_list2 = [np.array([7, 8, 9]), np.array([10, 11, 12])]\n >>> VectorUtil.n_similarity(vector_list1, vector_list2)\n 0.9897287473881233\n \"\"\"",
"test_class": "VectorUtilTestNSimilarity",
"test_code": "class VectorUtilTestNSimilarity(unittest.TestCase):\n def test_n_similarity_1(self):\n vector_list1 = [np.array([1, 0]), np.array([0, 1])]\n vector_list2 = [np.array([0, 0]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 1.0)\n\n def test_n_similarity_2(self):\n vector_list1 = [np.array([1, 1]), np.array([0, 1])]\n vector_list2 = [np.array([0, 0]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 0.9486832980505137)\n\n def test_n_similarity_3(self):\n vector_list1 = [np.array([1, 0]), np.array([1, 1])]\n vector_list2 = [np.array([0, 0]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 0.9486832980505137)\n\n def test_n_similarity_4(self):\n vector_list1 = [np.array([1, 0]), np.array([0, 1])]\n vector_list2 = [np.array([1, 0]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 0.9486832980505137)\n\n def test_n_similarity_5(self):\n vector_list1 = [np.array([1, 0]), np.array([0, 1])]\n vector_list2 = [np.array([0, 1]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 0.9486832980505137)\n\n def test_n_similarity_6(self):\n try:\n vector_list1 = []\n vector_list2 = []\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n except:\n pass",
"solution_code": "@staticmethod\n def n_similarity(vector_list_1, vector_list_2):\n if not (len(vector_list_1) and len(vector_list_2)):\n raise ZeroDivisionError('At least one of the passed list is empty.')\n\n return dot(matutils.unitvec(array(vector_list_1).mean(axis=0)),\n matutils.unitvec(array(vector_list_2).mean(axis=0)))",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"matutils"
],
"field_dependencies": [],
"method_dependencies": []
}
},
{
"method_name": "compute_idf_weight_dict",
"method_description": "@staticmethod\n def compute_idf_weight_dict(total_num, number_dict):\n \"\"\"\n Calculate log(total_num+1/count+1) for each count in number_dict\n :param total_num: int\n :param number_dict: dict\n :return: dict\n >>> num_dict = {'key1':0.1, 'key2':0.5}\n >>> VectorUtil.compute_idf_weight_dict(2, num_dict)\n {'key1': 1.0033021088637848, 'key2': 0.6931471805599453}\n \"\"\"",
"test_class": "VectorUtilTestComputeIdfWeightDict",
"test_code": "class VectorUtilTestComputeIdfWeightDict(unittest.TestCase):\n def test_compute_idf_weight_dict_1(self):\n num_dict = {'key1': 0.1, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 1.0033021088637848)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)\n\n def test_compute_idf_weight_dict_2(self):\n num_dict = {'key1': 0.2, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 0.9162907318741551)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)\n\n def test_compute_idf_weight_dict_3(self):\n num_dict = {'key1': 0.3, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 0.8362480242006185)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)\n\n def test_compute_idf_weight_dict_4(self):\n num_dict = {'key1': 0.4, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 0.7621400520468967)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)\n\n def test_compute_idf_weight_dict_5(self):\n num_dict = {'key1': 0.5, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 0.6931471805599453)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)",
"solution_code": "@staticmethod\n def compute_idf_weight_dict(total_num, number_dict):\n index_2_key_map = {}\n\n index = 0\n\n count_list = []\n for key, count in number_dict.items():\n index_2_key_map[index] = key\n count_list.append(count)\n index = index + 1\n\n a = np.array(count_list)\n ## smooth, in case the divide by zero error\n a = np.log((total_num + 1) / (a + 1))\n result = {}\n\n for index, w in enumerate(a):\n key = index_2_key_map[index]\n result[key] = w\n\n return result",
"dependencies": {
"Standalone": true,
"lib_dependencies": [],
"field_dependencies": [],
"method_dependencies": []
}
}
] | VectorUtil | [
"VectorUtilTestSimilarity",
"VectorUtilTestCosineSimilarities",
"VectorUtilTestNSimilarity",
"VectorUtilTestComputeIdfWeightDict",
"VectorUtilTest"
] | class VectorUtil:
| [] |
ClassEval_94 | class VendingMachine:
"""
This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information.
"""
def __init__(self):
"""
Initializes the vending machine's inventory and balance.
"""
self.inventory = {}
self.balance = 0
def add_item(self, item_name, price, quantity):
"""
Adds a product to the vending machine's inventory.
:param item_name: The name of the product to be added, str.
:param price: The price of the product to be added, float.
:param quantity: The quantity of the product to be added, int.
:return: None
>>> vendingMachine = VendingMachine()
>>> vendingMachine.add_item('Coke', 1.25, 10)
>>> vendingMachine.inventory
{'Coke': {'price': 1.25, 'quantity': 10}}
"""
def insert_coin(self, amount):
"""
Inserts coins into the vending machine.
:param amount: The amount of coins to be inserted, float.
:return: The balance of the vending machine after the coins are inserted, float.
>>> vendingMachine = VendingMachine()
>>> vendingMachine.insert_coin(1.25)
1.25
"""
def purchase_item(self, item_name):
"""
Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock.
:param item_name: The name of the product to be purchased, str.
:return: If successful, returns the balance of the vending machine after the product is purchased, float,otherwise,returns False.
>>> vendingMachine = VendingMachine()
>>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}
>>> vendingMachine.balance = 1.25
>>> vendingMachine.purchase_item('Coke')
0.0
>>> vendingMachine.purchase_item('Pizza')
False
"""
def restock_item(self, item_name, quantity):
"""
Replenishes the inventory of a product already in the vending machine.
:param item_name: The name of the product to be replenished, str.
:param quantity: The quantity of the product to be replenished, int.
:return: If the product is already in the vending machine, returns True, otherwise, returns False.
>>> vendingMachine = VendingMachine()
>>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}
>>> vendingMachine.restock_item('Coke', 10)
True
>>> vendingMachine.restock_item('Pizza', 10)
False
"""
def display_items(self):
"""
Displays the products in the vending machine.
:return: If the vending machine is empty, returns False, otherwise, returns a list of the products in the vending machine, str.
>>> vendingMachine = VendingMachine()
>>> vendingMachine.display_items()
False
>>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10} }
>>> vendingMachine.display_items()
'Coke - $1.25 [10]'
""" | import unittest
class VendingMachineTestAddItem(unittest.TestCase):
def test_add_item(self):
vendingMachine = VendingMachine()
vendingMachine.add_item('Coke', 1.25, 10)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})
def test_add_item_2(self):
vendingMachine = VendingMachine()
vendingMachine.add_item('Coke', 1.25, 10)
vendingMachine.add_item('Coke', 1.25, 10)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 20}})
def test_add_item_3(self):
vendingMachine = VendingMachine()
vendingMachine.add_item('Coke', 1.25, 10)
vendingMachine.add_item('Pizza', 1.25, 10)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}})
def test_add_item_4(self):
vendingMachine = VendingMachine()
vendingMachine.add_item('Coke', 1.25, 10)
vendingMachine.add_item('Pizza', 1.25, 10)
vendingMachine.add_item('Pizza', 1.25, 10)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 20}})
def test_add_item_5(self):
vendingMachine = VendingMachine()
vendingMachine.add_item('Coke', 1.25, 10)
vendingMachine.add_item('Pizza', 1.25, 10)
vendingMachine.add_item('Pizza', 1.25, 10)
vendingMachine.add_item('Coke', 1.25, 10)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 20}, 'Pizza': {'price': 1.25, 'quantity': 20}})
class VendingMachineTestInsertCoin(unittest.TestCase):
def test_insert_coin(self):
vendingMachine = VendingMachine()
self.assertEqual(vendingMachine.insert_coin(1.25), 1.25)
def test_insert_coin_2(self):
vendingMachine = VendingMachine()
self.assertEqual(vendingMachine.insert_coin(2.5), 2.5)
def test_insert_coin_3(self):
vendingMachine = VendingMachine()
vendingMachine.insert_coin(1.25)
vendingMachine.insert_coin(1.25)
self.assertEqual(vendingMachine.balance, 2.50)
def test_insert_coin_4(self):
vendingMachine = VendingMachine()
vendingMachine.balance = 1.25
vendingMachine.insert_coin(1.25)
vendingMachine.insert_coin(1.25)
vendingMachine.insert_coin(1.25)
self.assertEqual(vendingMachine.balance, 5.0)
def test_insert_coin_5(self):
vendingMachine = VendingMachine()
vendingMachine.balance = 1.25
vendingMachine.insert_coin(1.25)
vendingMachine.insert_coin(1.25)
vendingMachine.insert_coin(1.25)
vendingMachine.insert_coin(1.25)
self.assertEqual(vendingMachine.balance, 6.25)
class VendingMachineTestPurchaseItem(unittest.TestCase):
def test_purchase_item(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}
vendingMachine.balance = 1.25
self.assertEqual(vendingMachine.purchase_item('Coke'), 0.0)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 9}})
def test_purchase_item_2(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}
vendingMachine.balance = 1.25
self.assertEqual(vendingMachine.purchase_item('Pizza'), False)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})
def test_purchase_item_3(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}
vendingMachine.balance = 0
self.assertEqual(vendingMachine.purchase_item('Coke'), False)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})
def test_purchase_item_4(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}}
vendingMachine.balance = 1.25
self.assertEqual(vendingMachine.purchase_item('Coke'), False)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 0}})
def test_purchase_item_5(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}
vendingMachine.balance = 1.25
self.assertEqual(vendingMachine.purchase_item('Pizza'), 0.0)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 9}})
class VendingMachineTestRestockItem(unittest.TestCase):
def test_restock_item(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}
self.assertEqual(vendingMachine.restock_item('Coke', 10), True)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 20}})
def test_restock_item_2(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}
self.assertEqual(vendingMachine.restock_item('Pizza', 10), False)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})
def test_restock_item_3(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}}
self.assertEqual(vendingMachine.restock_item('Coke', 10), True)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})
def test_restock_item_4(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}
self.assertEqual(vendingMachine.restock_item('Pizza', 10), True)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 20}})
def test_restock_item_5(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}
self.assertEqual(vendingMachine.restock_item('Pizza', 0), True)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}})
class VendingMachineTestDisplayItems(unittest.TestCase):
def test_display_items(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}
self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [10]')
def test_display_items_2(self):
vendingMachine = VendingMachine()
self.assertEqual(vendingMachine.display_items(), False)
def test_display_items_3(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}
self.assertEqual(vendingMachine.display_items(),"Coke - $1.25 [10]\nPizza - $1.25 [10]")
def test_display_items_4(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}}
self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [0]')
def test_display_items_5(self):
vendingMachine = VendingMachine()
vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}, 'Pizza': {'price': 1.25, 'quantity': 10}}
self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [0]\nPizza - $1.25 [10]')
class VendingMachineTestMain(unittest.TestCase):
def test_main(self):
vendingMachine = VendingMachine()
self.assertEqual(vendingMachine.display_items(), False)
vendingMachine.add_item('Coke', 1.25, 10)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})
self.assertEqual(vendingMachine.insert_coin(1.25), 1.25)
self.assertEqual(vendingMachine.purchase_item('Coke'), 0.0)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 9}})
self.assertEqual(vendingMachine.purchase_item('Pizza'), False)
self.assertEqual(vendingMachine.restock_item('Coke', 10), True)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 19}})
self.assertEqual(vendingMachine.restock_item('Pizza', 10), False)
self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [19]')
def test_main_2(self):
vendingMachine = VendingMachine()
self.assertEqual(vendingMachine.purchase_item('Coke'), False)
vendingMachine.add_item('Coke', 1.25, 10)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})
self.assertEqual(vendingMachine.restock_item('Pizza', 10), False)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})
self.assertEqual(vendingMachine.insert_coin(1.25), 1.25)
self.assertEqual(vendingMachine.purchase_item('Coke'), 0.0)
self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 9}})
self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [9]') | class VendingMachine:
def __init__(self):
self.inventory = {}
self.balance = 0
def add_item(self, item_name, price, quantity):
if not self.restock_item(item_name, quantity):
self.inventory[item_name] = {'price': price, 'quantity': quantity}
def insert_coin(self, amount):
self.balance += amount
return self.balance
def purchase_item(self, item_name):
if item_name in self.inventory:
item = self.inventory[item_name]
if item['quantity'] > 0 and self.balance >= item['price']:
self.balance -= item['price']
item['quantity'] -= 1
return self.balance
else:
return False
else:
return False
def restock_item(self, item_name, quantity):
if item_name in self.inventory:
self.inventory[item_name]['quantity'] += quantity
return True
else:
return False
def display_items(self):
if not self.inventory:
return False
else:
items = []
for item_name, item_info in self.inventory.items():
items.append(f"{item_name} - ${item_info['price']} [{item_info['quantity']}]")
return "\n".join(items) | [] | """
This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information.
"""
| [
{
"method_name": "add_item",
"method_description": "def add_item(self, item_name, price, quantity):\n \"\"\"\n Adds a product to the vending machine's inventory.\n :param item_name: The name of the product to be added, str.\n :param price: The price of the product to be added, float.\n :param quantity: The quantity of the product to be added, int.\n :return: None\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.add_item('Coke', 1.25, 10)\n >>> vendingMachine.inventory\n {'Coke': {'price': 1.25, 'quantity': 10}}\n\n \"\"\"",
"test_class": "VendingMachineTestAddItem",
"test_code": "class VendingMachineTestAddItem(unittest.TestCase):\n def test_add_item(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_add_item_2(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n vendingMachine.add_item('Coke', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 20}})\n\n def test_add_item_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}})\n\n def test_add_item_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 20}})\n\n def test_add_item_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n vendingMachine.add_item('Coke', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 20}, 'Pizza': {'price': 1.25, 'quantity': 20}})",
"solution_code": "def add_item(self, item_name, price, quantity):\n if not self.restock_item(item_name, quantity):\n self.inventory[item_name] = {'price': price, 'quantity': quantity}",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.inventory"
],
"method_dependencies": [
"restock_item"
]
}
},
{
"method_name": "insert_coin",
"method_description": "def insert_coin(self, amount):\n \"\"\"\n Inserts coins into the vending machine.\n :param amount: The amount of coins to be inserted, float.\n :return: The balance of the vending machine after the coins are inserted, float.\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.insert_coin(1.25)\n 1.25\n\n \"\"\"",
"test_class": "VendingMachineTestInsertCoin",
"test_code": "class VendingMachineTestInsertCoin(unittest.TestCase):\n def test_insert_coin(self):\n vendingMachine = VendingMachine()\n self.assertEqual(vendingMachine.insert_coin(1.25), 1.25)\n\n def test_insert_coin_2(self):\n vendingMachine = VendingMachine()\n self.assertEqual(vendingMachine.insert_coin(2.5), 2.5)\n\n def test_insert_coin_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n self.assertEqual(vendingMachine.balance, 2.50)\n\n def test_insert_coin_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.balance = 1.25\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n self.assertEqual(vendingMachine.balance, 5.0)\n\n def test_insert_coin_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.balance = 1.25\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n self.assertEqual(vendingMachine.balance, 6.25)",
"solution_code": "def insert_coin(self, amount):\n self.balance += amount\n return self.balance",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.balance"
],
"method_dependencies": []
}
},
{
"method_name": "purchase_item",
"method_description": "def purchase_item(self, item_name):\n \"\"\"\n Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock.\n :param item_name: The name of the product to be purchased, str.\n :return: If successful, returns the balance of the vending machine after the product is purchased, float,otherwise,returns False.\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n >>> vendingMachine.balance = 1.25\n >>> vendingMachine.purchase_item('Coke')\n 0.0\n >>> vendingMachine.purchase_item('Pizza')\n False\n\n \"\"\"",
"test_class": "VendingMachineTestPurchaseItem",
"test_code": "class VendingMachineTestPurchaseItem(unittest.TestCase):\n def test_purchase_item(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n vendingMachine.balance = 1.25\n self.assertEqual(vendingMachine.purchase_item('Coke'), 0.0)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 9}})\n\n def test_purchase_item_2(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n vendingMachine.balance = 1.25\n self.assertEqual(vendingMachine.purchase_item('Pizza'), False)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_purchase_item_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n vendingMachine.balance = 0\n self.assertEqual(vendingMachine.purchase_item('Coke'), False)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_purchase_item_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}}\n vendingMachine.balance = 1.25\n self.assertEqual(vendingMachine.purchase_item('Coke'), False)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 0}})\n\n def test_purchase_item_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n vendingMachine.balance = 1.25\n self.assertEqual(vendingMachine.purchase_item('Pizza'), 0.0)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 9}})",
"solution_code": "def purchase_item(self, item_name):\n if item_name in self.inventory:\n item = self.inventory[item_name]\n if item['quantity'] > 0 and self.balance >= item['price']:\n self.balance -= item['price']\n item['quantity'] -= 1\n return self.balance\n else:\n return False\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.balance",
"self.inventory"
],
"method_dependencies": []
}
},
{
"method_name": "restock_item",
"method_description": "def restock_item(self, item_name, quantity):\n \"\"\"\n Replenishes the inventory of a product already in the vending machine.\n :param item_name: The name of the product to be replenished, str.\n :param quantity: The quantity of the product to be replenished, int.\n :return: If the product is already in the vending machine, returns True, otherwise, returns False.\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n >>> vendingMachine.restock_item('Coke', 10)\n True\n >>> vendingMachine.restock_item('Pizza', 10)\n False\n\n \"\"\"",
"test_class": "VendingMachineTestRestockItem",
"test_code": "class VendingMachineTestRestockItem(unittest.TestCase):\n def test_restock_item(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.restock_item('Coke', 10), True)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 20}})\n\n def test_restock_item_2(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.restock_item('Pizza', 10), False)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_restock_item_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}}\n self.assertEqual(vendingMachine.restock_item('Coke', 10), True)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_restock_item_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.restock_item('Pizza', 10), True)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 20}})\n\n def test_restock_item_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.restock_item('Pizza', 0), True)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}})",
"solution_code": "def restock_item(self, item_name, quantity):\n if item_name in self.inventory:\n self.inventory[item_name]['quantity'] += quantity\n return True\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.inventory"
],
"method_dependencies": []
}
},
{
"method_name": "display_items",
"method_description": "def display_items(self):\n \"\"\"\n Displays the products in the vending machine.\n :return: If the vending machine is empty, returns False, otherwise, returns a list of the products in the vending machine, str.\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.display_items()\n False\n >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10} }\n >>> vendingMachine.display_items()\n 'Coke - $1.25 [10]'\n\n \"\"\"",
"test_class": "VendingMachineTestDisplayItems",
"test_code": "class VendingMachineTestDisplayItems(unittest.TestCase):\n def test_display_items(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [10]')\n\n def test_display_items_2(self):\n vendingMachine = VendingMachine()\n self.assertEqual(vendingMachine.display_items(), False)\n\n def test_display_items_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.display_items(),\"Coke - $1.25 [10]\\nPizza - $1.25 [10]\")\n\n def test_display_items_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}}\n self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [0]')\n\n def test_display_items_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [0]\\nPizza - $1.25 [10]')",
"solution_code": "def display_items(self):\n if not self.inventory:\n return False\n else:\n items = []\n for item_name, item_info in self.inventory.items():\n items.append(f\"{item_name} - ${item_info['price']} [{item_info['quantity']}]\")\n return \"\\n\".join(items)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.inventory"
],
"method_dependencies": []
}
}
] | VendingMachine | [
"VendingMachineTestAddItem",
"VendingMachineTestInsertCoin",
"VendingMachineTestPurchaseItem",
"VendingMachineTestRestockItem",
"VendingMachineTestDisplayItems",
"VendingMachineTestMain"
] | class VendingMachine:
def __init__(self):
"""
Initializes the vending machine's inventory and balance.
"""
self.inventory = {}
self.balance = 0
| [
"self.balance",
"self.inventory"
] |
ClassEval_95 | class Warehouse:
"""
The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders.
"""
def __init__(self):
"""
Initialize two fields.
self.inventory is a dict that stores the products.
self.inventory = {Product ID: Product}
self.orders is a dict that stores the products in a order.
self.orders = {Order ID: Order}
"""
self.inventory = {} # Product ID: Product
self.orders = {} # Order ID: Order
def add_product(self, product_id, name, quantity):
"""
Add product to inventory and plus the quantity if it has existed in inventory.
Or just add new product to dict otherwise.
:param product_id: int
:param name: str, product name
:param quantity: int, product quantity
>>> warehouse.add_product(1, "product1", 3)
>>> warehouse.inventory
{1: {'name': 'product1', 'quantity': 3}}
"""
def update_product_quantity(self, product_id, quantity):
"""
According to product_id, add the quantity to the corresponding product in inventory.
>>> warehouse.add_product(1, "product1", 3)
>>> warehouse.update_product_quantity(1, -1)
>>> warehouse.inventory
{1: {'name': 'product1', 'quantity': 2}}
"""
def get_product_quantity(self, product_id):
"""
Get the quantity of specific product by product_id.
:param product_id, int
:return: if the product_id is in inventory then return the corresponding quantity,
or False otherwise.
>>> warehouse.add_product(1, "product1", 3)
>>> warehouse.get_product_quantity(1)
3
>>> warehouse.get_product_quantity(2)
False
"""
def create_order(self, order_id, product_id, quantity):
"""
Create a order which includes the infomation of product, like id and quantity.
And put the new order into self.orders.
The default value of status is 'Shipped'.
:param order_id: int
:param product_id: int
:param quantity: the quantity of product that be selected.
:return False: only if product_id is not in inventory or the quantity is not adequate
>>> warehouse.add_product(1, "product1", 3)
>>> warehouse.create_order(1, 1, 2)
>>> warehouse.orders
{1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}}
>>> warehouse.create_order(1, 2, 2)
False
"""
def change_order_status(self, order_id, status):
"""
Change the status of order if the input order_id is in self.orders.
:param order_id: int
:param status: str, the state that is going to change to
:return False: only if the order_id is not in self.orders
>>> warehouse.add_product(1, "product1", 3)
>>> warehouse.create_order(1, 1, 2)
>>> warehouse.change_order_status(1, "done")
>>> warehouse.orders
{1: {'product_id': 1, 'quantity': 2, 'status': 'done'}}
"""
def track_order(self, order_id):
"""
Get the status of specific order.
:param order_id: int
:return False: only if the order_id is not in self.orders.
>>> warehouse.add_product(1, "product1", 3)
>>> warehouse.create_order(1, 1, 2)
>>> warehouse.track_order(1)
'Shipped'
""" | import unittest
class WarehouseTestAddProduct(unittest.TestCase):
def test_add_product_1(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 10)
self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 10}})
def test_add_product_2(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 10)
warehouse.add_product(2, 'product 2', 5)
self.assertEqual(warehouse.inventory,
{1: {'name': 'product 1', 'quantity': 10}, 2: {'name': 'product 2', 'quantity': 5}})
def test_add_product_3(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 3', 10)
self.assertEqual(warehouse.inventory, {1: {'name': 'product 3', 'quantity': 10}})
def test_add_product_4(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 4', 10)
self.assertEqual(warehouse.inventory, {1: {'name': 'product 4', 'quantity': 10}})
def test_add_product_5(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 5', 10)
self.assertEqual(warehouse.inventory, {1: {'name': 'product 5', 'quantity': 10}})
def test_add_product_6(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 5', 10)
warehouse.add_product(1, 'product 5', 10)
self.assertEqual(warehouse.inventory, {1: {'name': 'product 5', 'quantity': 20}})
class WarehouseTestUpdateProductQuantity(unittest.TestCase):
def test_update_product_quantity_1(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 10)
warehouse.update_product_quantity(1, 5)
self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 15}})
# quantity is negative
def test_update_product_quantity_2(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 10)
warehouse.update_product_quantity(1, -5)
self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 5}})
def test_update_product_quantity_3(self):
warehouse = Warehouse()
warehouse.update_product_quantity(1, -5)
self.assertEqual(warehouse.inventory, {})
def test_update_product_quantity_4(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 10)
warehouse.update_product_quantity(1, 1)
self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 11}})
def test_update_product_quantity_5(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 10)
warehouse.update_product_quantity(1, -9)
self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 1}})
class WarehouseTestGetProductQuantity(unittest.TestCase):
def test_get_product_quantity_1(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 10)
self.assertEqual(warehouse.get_product_quantity(1), 10)
def test_get_product_quantity_2(self):
warehouse = Warehouse()
self.assertEqual(warehouse.get_product_quantity(1), False)
def test_get_product_quantity_3(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 5)
self.assertEqual(warehouse.get_product_quantity(1), 5)
def test_get_product_quantity_4(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 100)
self.assertEqual(warehouse.get_product_quantity(1), 100)
def test_get_product_quantity_5(self):
warehouse = Warehouse()
warehouse.add_product(5, 'product 1', 10)
self.assertEqual(warehouse.get_product_quantity(5), 10)
class WarehouseTestCreateOrder(unittest.TestCase):
def test_create_order_1(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 10)
warehouse.create_order(1, 1, 5)
self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Shipped'}})
def test_create_order_2(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 10)
result = warehouse.create_order(1, 1, 15)
self.assertFalse(result)
def test_create_order_3(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 1)
warehouse.create_order(1, 1, 1)
self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 1, 'status': 'Shipped'}})
def test_create_order_4(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 4', 5)
warehouse.create_order(1, 1, 5)
self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Shipped'}})
def test_create_order_5(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 5', 100)
warehouse.create_order(1, 1, 50)
self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 50, 'status': 'Shipped'}})
class WarehouseTestChangeOrderStatus(unittest.TestCase):
def test_change_order_status_1(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 10)
warehouse.create_order(1, 1, 5)
warehouse.change_order_status(1, 'Delivered')
self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Delivered'}})
def test_change_order_status_2(self):
warehouse = Warehouse()
result = warehouse.change_order_status(1, 'Delivered')
self.assertFalse(result)
def test_change_order_status_3(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 3', 5)
warehouse.create_order(1, 1, 5)
warehouse.change_order_status(1, 'Delivered')
self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Delivered'}})
def test_change_order_status_4(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 4', 100)
warehouse.create_order(1, 1, 50)
warehouse.change_order_status(1, 'Delivered')
self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 50, 'status': 'Delivered'}})
def test_change_order_status_5(self):
warehouse = Warehouse()
result = warehouse.change_order_status(2, 'Delivered')
self.assertFalse(result)
class WarehouseTestTrackOrder(unittest.TestCase):
def test_track_order_1(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 10)
warehouse.create_order(1, 1, 5)
self.assertEqual(warehouse.track_order(1), 'Shipped')
def test_track_order_2(self):
warehouse = Warehouse()
result = warehouse.track_order(1)
self.assertFalse(result)
def test_track_order_3(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 3', 10)
warehouse.create_order(1, 1, 1)
self.assertEqual(warehouse.track_order(1), 'Shipped')
def test_track_order_4(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 4', 100)
warehouse.create_order(1, 1, 50)
self.assertEqual(warehouse.track_order(1), 'Shipped')
def test_track_order_5(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 5', 100)
warehouse.create_order(1, 1, 10)
self.assertEqual(warehouse.track_order(1), 'Shipped')
class WarehouseTestMain(unittest.TestCase):
def test_main(self):
warehouse = Warehouse()
warehouse.add_product(1, 'product 1', 10)
self.assertEqual({1: {'name': 'product 1', 'quantity': 10}}, warehouse.inventory)
warehouse.update_product_quantity(1, -5)
self.assertEqual({1: {'name': 'product 1', 'quantity': 5}}, warehouse.inventory)
self.assertEqual(warehouse.get_product_quantity(1), 5)
warehouse.create_order(1, 1, 3)
self.assertEqual({1: {'product_id': 1, 'quantity': 3, 'status': 'Shipped'}}, warehouse.orders)
warehouse.change_order_status(1, 'Delivered')
self.assertEqual({1: {'product_id': 1, 'quantity': 3, 'status': 'Delivered'}}, warehouse.orders)
self.assertEqual('Delivered', warehouse.track_order(1)) | class Warehouse:
def __init__(self):
self.inventory = {} # Product ID: Product
self.orders = {} # Order ID: Order
def add_product(self, product_id, name, quantity):
if product_id not in self.inventory:
self.inventory[product_id] = {'name': name, 'quantity': quantity}
else:
self.inventory[product_id]['quantity'] += quantity
def update_product_quantity(self, product_id, quantity):
if product_id in self.inventory:
self.inventory[product_id]['quantity'] += quantity
def get_product_quantity(self, product_id):
if product_id in self.inventory:
return self.inventory[product_id]['quantity']
else:
return False
def create_order(self, order_id, product_id, quantity):
if self.get_product_quantity(product_id) >= quantity:
self.update_product_quantity(product_id, -quantity)
self.orders[order_id] = {'product_id': product_id, 'quantity': quantity, 'status': 'Shipped'}
else:
return False
def change_order_status(self, order_id, status):
if order_id in self.orders:
self.orders[order_id]['status'] = status
else:
return False
def track_order(self, order_id):
if order_id in self.orders:
return self.orders[order_id]['status']
else:
return False | [] | """
The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders.
"""
| [
{
"method_name": "add_product",
"method_description": "def add_product(self, product_id, name, quantity):\n \"\"\"\n Add product to inventory and plus the quantity if it has existed in inventory.\n Or just add new product to dict otherwise.\n :param product_id: int\n :param name: str, product name\n :param quantity: int, product quantity\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.inventory\n {1: {'name': 'product1', 'quantity': 3}}\n \"\"\"",
"test_class": "WarehouseTestAddProduct",
"test_code": "class WarehouseTestAddProduct(unittest.TestCase):\n def test_add_product_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 10}})\n\n def test_add_product_2(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.add_product(2, 'product 2', 5)\n self.assertEqual(warehouse.inventory,\n {1: {'name': 'product 1', 'quantity': 10}, 2: {'name': 'product 2', 'quantity': 5}})\n\n def test_add_product_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 3', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 3', 'quantity': 10}})\n\n def test_add_product_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 4', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 4', 'quantity': 10}})\n\n def test_add_product_5(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 5', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 5', 'quantity': 10}})\n\n def test_add_product_6(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 5', 10)\n warehouse.add_product(1, 'product 5', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 5', 'quantity': 20}})",
"solution_code": "def add_product(self, product_id, name, quantity):\n if product_id not in self.inventory:\n self.inventory[product_id] = {'name': name, 'quantity': quantity}\n else:\n self.inventory[product_id]['quantity'] += quantity",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.inventory"
],
"method_dependencies": []
}
},
{
"method_name": "update_product_quantity",
"method_description": "def update_product_quantity(self, product_id, quantity):\n \"\"\"\n According to product_id, add the quantity to the corresponding product in inventory.\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.update_product_quantity(1, -1)\n >>> warehouse.inventory\n {1: {'name': 'product1', 'quantity': 2}}\n \"\"\"",
"test_class": "WarehouseTestUpdateProductQuantity",
"test_code": "class WarehouseTestUpdateProductQuantity(unittest.TestCase):\n def test_update_product_quantity_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.update_product_quantity(1, 5)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 15}})\n\n # quantity is negative\n def test_update_product_quantity_2(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.update_product_quantity(1, -5)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 5}})\n\n def test_update_product_quantity_3(self):\n warehouse = Warehouse()\n warehouse.update_product_quantity(1, -5)\n self.assertEqual(warehouse.inventory, {})\n\n def test_update_product_quantity_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.update_product_quantity(1, 1)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 11}})\n\n def test_update_product_quantity_5(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.update_product_quantity(1, -9)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 1}})",
"solution_code": "def update_product_quantity(self, product_id, quantity):\n if product_id in self.inventory:\n self.inventory[product_id]['quantity'] += quantity",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.inventory"
],
"method_dependencies": []
}
},
{
"method_name": "get_product_quantity",
"method_description": "def get_product_quantity(self, product_id):\n \"\"\"\n Get the quantity of specific product by product_id.\n :param product_id, int\n :return: if the product_id is in inventory then return the corresponding quantity,\n or False otherwise.\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.get_product_quantity(1)\n 3\n >>> warehouse.get_product_quantity(2)\n False\n \"\"\"",
"test_class": "WarehouseTestGetProductQuantity",
"test_code": "class WarehouseTestGetProductQuantity(unittest.TestCase):\n def test_get_product_quantity_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n self.assertEqual(warehouse.get_product_quantity(1), 10)\n\n def test_get_product_quantity_2(self):\n warehouse = Warehouse()\n self.assertEqual(warehouse.get_product_quantity(1), False)\n\n def test_get_product_quantity_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 5)\n self.assertEqual(warehouse.get_product_quantity(1), 5)\n\n def test_get_product_quantity_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 100)\n self.assertEqual(warehouse.get_product_quantity(1), 100)\n\n def test_get_product_quantity_5(self):\n warehouse = Warehouse()\n warehouse.add_product(5, 'product 1', 10)\n self.assertEqual(warehouse.get_product_quantity(5), 10)",
"solution_code": "def get_product_quantity(self, product_id):\n if product_id in self.inventory:\n return self.inventory[product_id]['quantity']\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.inventory"
],
"method_dependencies": []
}
},
{
"method_name": "create_order",
"method_description": "def create_order(self, order_id, product_id, quantity):\n \"\"\"\n Create a order which includes the infomation of product, like id and quantity.\n And put the new order into self.orders.\n The default value of status is 'Shipped'.\n :param order_id: int\n :param product_id: int\n :param quantity: the quantity of product that be selected.\n :return False: only if product_id is not in inventory or the quantity is not adequate\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.create_order(1, 1, 2)\n >>> warehouse.orders\n {1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}}\n >>> warehouse.create_order(1, 2, 2)\n False\n \"\"\"",
"test_class": "WarehouseTestCreateOrder",
"test_code": "class WarehouseTestCreateOrder(unittest.TestCase):\n def test_create_order_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.create_order(1, 1, 5)\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Shipped'}})\n\n def test_create_order_2(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n result = warehouse.create_order(1, 1, 15)\n self.assertFalse(result)\n\n def test_create_order_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 1)\n warehouse.create_order(1, 1, 1)\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 1, 'status': 'Shipped'}})\n\n def test_create_order_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 4', 5)\n warehouse.create_order(1, 1, 5)\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Shipped'}})\n\n def test_create_order_5(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 5', 100)\n warehouse.create_order(1, 1, 50)\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 50, 'status': 'Shipped'}})",
"solution_code": "def create_order(self, order_id, product_id, quantity):\n if self.get_product_quantity(product_id) >= quantity:\n self.update_product_quantity(product_id, -quantity)\n self.orders[order_id] = {'product_id': product_id, 'quantity': quantity, 'status': 'Shipped'}\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.orders"
],
"method_dependencies": [
"update_product_quantity",
"get_product_quantity"
]
}
},
{
"method_name": "change_order_status",
"method_description": "def change_order_status(self, order_id, status):\n \"\"\"\n Change the status of order if the input order_id is in self.orders.\n :param order_id: int\n :param status: str, the state that is going to change to\n :return False: only if the order_id is not in self.orders\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.create_order(1, 1, 2)\n >>> warehouse.change_order_status(1, \"done\")\n >>> warehouse.orders\n {1: {'product_id': 1, 'quantity': 2, 'status': 'done'}}\n \"\"\"",
"test_class": "WarehouseTestChangeOrderStatus",
"test_code": "class WarehouseTestChangeOrderStatus(unittest.TestCase):\n def test_change_order_status_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.create_order(1, 1, 5)\n warehouse.change_order_status(1, 'Delivered')\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Delivered'}})\n\n def test_change_order_status_2(self):\n warehouse = Warehouse()\n result = warehouse.change_order_status(1, 'Delivered')\n self.assertFalse(result)\n\n def test_change_order_status_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 3', 5)\n warehouse.create_order(1, 1, 5)\n warehouse.change_order_status(1, 'Delivered')\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Delivered'}})\n\n def test_change_order_status_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 4', 100)\n warehouse.create_order(1, 1, 50)\n warehouse.change_order_status(1, 'Delivered')\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 50, 'status': 'Delivered'}})\n\n def test_change_order_status_5(self):\n warehouse = Warehouse()\n result = warehouse.change_order_status(2, 'Delivered')\n self.assertFalse(result)",
"solution_code": "def change_order_status(self, order_id, status):\n if order_id in self.orders:\n self.orders[order_id]['status'] = status\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.orders"
],
"method_dependencies": []
}
},
{
"method_name": "track_order",
"method_description": "def track_order(self, order_id):\n \"\"\"\n Get the status of specific order.\n :param order_id: int\n :return False: only if the order_id is not in self.orders.\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.create_order(1, 1, 2)\n >>> warehouse.track_order(1)\n 'Shipped'\n \"\"\"",
"test_class": "WarehouseTestTrackOrder",
"test_code": "class WarehouseTestTrackOrder(unittest.TestCase):\n def test_track_order_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.create_order(1, 1, 5)\n self.assertEqual(warehouse.track_order(1), 'Shipped')\n\n def test_track_order_2(self):\n warehouse = Warehouse()\n result = warehouse.track_order(1)\n self.assertFalse(result)\n\n def test_track_order_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 3', 10)\n warehouse.create_order(1, 1, 1)\n self.assertEqual(warehouse.track_order(1), 'Shipped')\n\n def test_track_order_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 4', 100)\n warehouse.create_order(1, 1, 50)\n self.assertEqual(warehouse.track_order(1), 'Shipped')\n\n def test_track_order_5(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 5', 100)\n warehouse.create_order(1, 1, 10)\n self.assertEqual(warehouse.track_order(1), 'Shipped')",
"solution_code": "def track_order(self, order_id):\n if order_id in self.orders:\n return self.orders[order_id]['status']\n else:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.orders"
],
"method_dependencies": []
}
}
] | Warehouse | [
"WarehouseTestAddProduct",
"WarehouseTestUpdateProductQuantity",
"WarehouseTestGetProductQuantity",
"WarehouseTestCreateOrder",
"WarehouseTestChangeOrderStatus",
"WarehouseTestTrackOrder",
"WarehouseTestMain"
] | class Warehouse:
def __init__(self):
"""
Initialize two fields.
self.inventory is a dict that stores the products.
self.inventory = {Product ID: Product}
self.orders is a dict that stores the products in a order.
self.orders = {Order ID: Order}
"""
self.inventory = {} # Product ID: Product
self.orders = {} # Order ID: Order
| [
"self.inventory",
"self.orders"
] |
ClassEval_96 | class WeatherSystem:
"""
This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit.
"""
def __init__(self, city) -> None:
"""
Initialize the weather system with a city name.
"""
self.temperature = None
self.weather = None
self.city = city
self.weather_list = {}
def query(self, weather_list, tmp_units = 'celsius'):
"""
Query the weather system for the weather and temperature of the city,and convert the temperature units based on the input parameter.
:param weather_list: a dictionary of weather information for different cities,dict.
:param tmp_units: the temperature units to convert to, str.
:return: the temperature and weather of the city, tuple.
>>> weatherSystem = WeatherSystem('New York')
>>> weather_list = {'New York': {'weather': 'sunny','temperature': 27,'temperature units': 'celsius'},'Beijing': {'weather': 'cloudy','temperature': 23,'temperature units': 'celsius'}}
>>> weatherSystem.query(weather_list)
(27, 'sunny')
"""
def set_city(self, city):
"""
Set the city of the weather system.
:param city: the city to set, str.
:return: None
>>> weatherSystem = WeatherSystem('New York')
>>> weatherSystem.set_city('Beijing')
>>> weatherSystem.city
'Beijing'
"""
def celsius_to_fahrenheit(self):
"""
Convert the temperature from Celsius to Fahrenheit.
:return: the temperature in Fahrenheit, float.
>>> weatherSystem = WeatherSystem('New York')
>>> weatherSystem.temperature = 27
>>> weatherSystem.celsius_to_fahrenheit()
80.6
"""
def fahrenheit_to_celsius(self):
"""
Convert the temperature from Fahrenheit to Celsius.
:return: the temperature in Celsius, float.
>>> weatherSystem = WeatherSystem('New York')
>>> weatherSystem.temperature = 80.6
>>> weatherSystem.fahrenheit_to_celsius()
26.999999999999996
""" | import unittest
class WeatherSystemTestQuery(unittest.TestCase):
def test_query(self):
weatherSystem = WeatherSystem('New York')
weather_list = {
'New York': {
'weather': 'sunny',
'temperature': 27,
'temperature units': 'celsius'
},
'Beijing': {
'weather': 'cloudy',
'temperature': 23,
'temperature units': 'celsius'
}
}
self.assertEqual(weatherSystem.query(weather_list), (27, 'sunny'))
def test_query_2(self):
weatherSystem = WeatherSystem('Shanghai')
weather_list = {
'New York': {
'weather': 'sunny',
'temperature': 27,
'temperature units': 'celsius'
},
'Beijing': {
'weather': 'cloudy',
'temperature': 23,
'temperature units': 'celsius'
}
}
self.assertEqual(weatherSystem.query(weather_list), False)
def test_query_3(self):
weatherSystem = WeatherSystem('Beijing')
weather_list = {
'New York': {
'weather': 'sunny',
'temperature': 27,
'temperature units': 'celsius'
},
'Beijing': {
'weather': 'cloudy',
'temperature': 23,
'temperature units': 'celsius'
}
}
self.assertEqual(weatherSystem.query(weather_list, 'fahrenheit'), (73.4, 'cloudy'))
def test_query_4(self):
weatherSystem = WeatherSystem('Beijing')
weather_list = {
'New York': {
'weather': 'sunny',
'temperature': 73.47,
'temperature units': 'fahrenheit'
},
'Beijing': {
'weather': 'cloudy',
'temperature': 73.4,
'temperature units': 'fahrenheit'
}
}
self.assertEqual(weatherSystem.query(weather_list, 'celsius'), (23.000000000000004, 'cloudy'))
def test_query_5(self):
weatherSystem = WeatherSystem('New York')
weather_list = {
'New York': {
'weather': 'sunny',
'temperature': 80.6,
'temperature units': 'fahrenheit'
},
'Beijing': {
'weather': 'cloudy',
'temperature': 23,
'temperature units': 'celsius'
}
}
self.assertEqual(weatherSystem.query(weather_list, tmp_units='celsius'), (26.999999999999996, 'sunny'))
def test_query_6(self):
weatherSystem = WeatherSystem('New York')
weather_list = {
'New York': {
'weather': 'sunny',
'temperature': 27,
'temperature units': 'celsius'
},
'Beijing': {
'weather': 'cloudy',
'temperature': 23,
'temperature units': 'celsius'
}
}
self.assertEqual(weatherSystem.query(weather_list, tmp_units='fahrenheit'), (80.6, 'sunny'))
class WeatherSystemTestSetCity(unittest.TestCase):
def test_set_city(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.set_city('Beijing')
self.assertEqual(weatherSystem.city, 'Beijing')
def test_set_city_2(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.set_city('Shanghai')
self.assertEqual(weatherSystem.city, 'Shanghai')
def test_set_city_3(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.set_city('Shanghai')
self.assertNotEqual(weatherSystem.city, 'Beijing')
def test_set_city_4(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.set_city('Shanghai')
self.assertNotEqual(weatherSystem.city, 'New York')
def test_set_city_5(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.set_city('Shanghai')
self.assertNotEqual(weatherSystem.city, 'Tokyo')
class WeatherSystemTestCelsiusToFahrenheit(unittest.TestCase):
def test_celsius_to_fahrenheit(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.temperature = 27
self.assertEqual(weatherSystem.celsius_to_fahrenheit(), 80.6)
def test_celsius_to_fahrenheit_2(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.temperature = 23
self.assertEqual(weatherSystem.celsius_to_fahrenheit(), 73.4)
def test_celsius_to_fahrenheit_3(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.temperature = 23
self.assertNotEqual(weatherSystem.celsius_to_fahrenheit(), 80.6)
def test_celsius_to_fahrenheit_4(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.temperature = 27
self.assertNotEqual(weatherSystem.celsius_to_fahrenheit(), 73.4)
def test_celsius_to_fahrenheit_5(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.temperature = 27
self.assertNotEqual(weatherSystem.celsius_to_fahrenheit(), 23)
class WeatherSystemTestFahrenheitToCelsius(unittest.TestCase):
def test_fahrenheit_to_celsius(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.temperature = 80.6
self.assertEqual(weatherSystem.fahrenheit_to_celsius(), 26.999999999999996)
def test_fahrenheit_to_celsius_2(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.temperature = 73.4
self.assertEqual(weatherSystem.fahrenheit_to_celsius(), 23.000000000000004)
def test_fahrenheit_to_celsius_3(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.temperature = 80
self.assertNotEqual(weatherSystem.fahrenheit_to_celsius(), 23)
def test_fahrenheit_to_celsius_4(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.temperature = 73
self.assertNotEqual(weatherSystem.fahrenheit_to_celsius(), 27)
def test_fahrenheit_to_celsius_5(self):
weatherSystem = WeatherSystem('New York')
weatherSystem.temperature = 80
self.assertNotEqual(weatherSystem.fahrenheit_to_celsius(), 27)
class WeatherSystemTestMain(unittest.TestCase):
def test_main(self):
weatherSystem = WeatherSystem('New York')
weather_list = {
'New York': {
'weather': 'sunny',
'temperature': 27,
'temperature units': 'celsius'
},
'Beijing': {
'weather': 'cloudy',
'temperature': 23,
'temperature units': 'celsius'
}
}
self.assertEqual(weatherSystem.query(weather_list), (27, 'sunny'))
weatherSystem.set_city('Beijing')
self.assertEqual(weatherSystem.city, 'Beijing')
weatherSystem.temperature = 27
self.assertEqual(weatherSystem.celsius_to_fahrenheit(), 80.6)
weatherSystem.temperature = 80.6
self.assertEqual(weatherSystem.fahrenheit_to_celsius(), 26.999999999999996) | class WeatherSystem:
def __init__(self, city) -> None:
self.temperature = None
self.weather = None
self.city = city
self.weather_list = {}
def query(self, weather_list, tmp_units = 'celsius'):
self.weather_list = weather_list
if self.city not in weather_list:
return False
else:
self.temperature = self.weather_list[self.city]['temperature']
self.weather = self.weather_list[self.city]['weather']
if self.weather_list[self.city]['temperature units'] != tmp_units:
if tmp_units == 'celsius':
return self.fahrenheit_to_celsius(), self.weather
elif tmp_units == 'fahrenheit':
return self.celsius_to_fahrenheit(), self.weather
else:
return self.temperature, self.weather
def set_city(self, city):
self.city = city
def celsius_to_fahrenheit(self):
return (self.temperature * 9/5) + 32
def fahrenheit_to_celsius(self):
return (self.temperature - 32) * 5/9 | [] | """
This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit.
"""
| [
{
"method_name": "query",
"method_description": "def query(self, weather_list, tmp_units = 'celsius'):\n \"\"\"\n Query the weather system for the weather and temperature of the city,and convert the temperature units based on the input parameter.\n :param weather_list: a dictionary of weather information for different cities,dict.\n :param tmp_units: the temperature units to convert to, str.\n :return: the temperature and weather of the city, tuple.\n >>> weatherSystem = WeatherSystem('New York')\n >>> weather_list = {'New York': {'weather': 'sunny','temperature': 27,'temperature units': 'celsius'},'Beijing': {'weather': 'cloudy','temperature': 23,'temperature units': 'celsius'}}\n >>> weatherSystem.query(weather_list)\n (27, 'sunny')\n\n \"\"\"",
"test_class": "WeatherSystemTestQuery",
"test_code": "class WeatherSystemTestQuery(unittest.TestCase):\n def test_query(self):\n weatherSystem = WeatherSystem('New York')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 27,\n 'temperature units': 'celsius'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list), (27, 'sunny'))\n\n def test_query_2(self):\n weatherSystem = WeatherSystem('Shanghai')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 27,\n 'temperature units': 'celsius'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list), False)\n\n def test_query_3(self):\n weatherSystem = WeatherSystem('Beijing')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 27,\n 'temperature units': 'celsius'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list, 'fahrenheit'), (73.4, 'cloudy'))\n\n def test_query_4(self):\n weatherSystem = WeatherSystem('Beijing')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 73.47,\n 'temperature units': 'fahrenheit'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 73.4,\n 'temperature units': 'fahrenheit'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list, 'celsius'), (23.000000000000004, 'cloudy'))\n\n def test_query_5(self):\n weatherSystem = WeatherSystem('New York')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 80.6,\n 'temperature units': 'fahrenheit'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list, tmp_units='celsius'), (26.999999999999996, 'sunny'))\n\n def test_query_6(self):\n weatherSystem = WeatherSystem('New York')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 27,\n 'temperature units': 'celsius'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list, tmp_units='fahrenheit'), (80.6, 'sunny'))",
"solution_code": "def query(self, weather_list, tmp_units = 'celsius'):\n self.weather_list = weather_list\n if self.city not in weather_list:\n return False\n else:\n self.temperature = self.weather_list[self.city]['temperature']\n self.weather = self.weather_list[self.city]['weather']\n if self.weather_list[self.city]['temperature units'] != tmp_units:\n if tmp_units == 'celsius':\n return self.fahrenheit_to_celsius(), self.weather\n elif tmp_units == 'fahrenheit':\n return self.celsius_to_fahrenheit(), self.weather\n else:\n return self.temperature, self.weather",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.city",
"self.temperature",
"self.weather",
"self.weather_list"
],
"method_dependencies": [
"celsius_to_fahrenheit",
"fahrenheit_to_celsius"
]
}
},
{
"method_name": "set_city",
"method_description": "def set_city(self, city):\n \"\"\"\n Set the city of the weather system.\n :param city: the city to set, str.\n :return: None\n >>> weatherSystem = WeatherSystem('New York')\n >>> weatherSystem.set_city('Beijing')\n >>> weatherSystem.city\n 'Beijing'\n\n \"\"\"",
"test_class": "WeatherSystemTestSetCity",
"test_code": "class WeatherSystemTestSetCity(unittest.TestCase):\n def test_set_city(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Beijing')\n self.assertEqual(weatherSystem.city, 'Beijing')\n\n def test_set_city_2(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Shanghai')\n self.assertEqual(weatherSystem.city, 'Shanghai')\n\n def test_set_city_3(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Shanghai')\n self.assertNotEqual(weatherSystem.city, 'Beijing')\n\n def test_set_city_4(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Shanghai')\n self.assertNotEqual(weatherSystem.city, 'New York')\n\n def test_set_city_5(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Shanghai')\n self.assertNotEqual(weatherSystem.city, 'Tokyo')",
"solution_code": "def set_city(self, city):\n self.city = city",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.city"
],
"method_dependencies": []
}
},
{
"method_name": "celsius_to_fahrenheit",
"method_description": "def celsius_to_fahrenheit(self):\n \"\"\"\n Convert the temperature from Celsius to Fahrenheit.\n :return: the temperature in Fahrenheit, float.\n >>> weatherSystem = WeatherSystem('New York')\n >>> weatherSystem.temperature = 27\n >>> weatherSystem.celsius_to_fahrenheit()\n 80.6\n\n \"\"\"",
"test_class": "WeatherSystemTestCelsiusToFahrenheit",
"test_code": "class WeatherSystemTestCelsiusToFahrenheit(unittest.TestCase):\n def test_celsius_to_fahrenheit(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 27\n self.assertEqual(weatherSystem.celsius_to_fahrenheit(), 80.6)\n\n def test_celsius_to_fahrenheit_2(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 23\n self.assertEqual(weatherSystem.celsius_to_fahrenheit(), 73.4)\n\n def test_celsius_to_fahrenheit_3(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 23\n self.assertNotEqual(weatherSystem.celsius_to_fahrenheit(), 80.6)\n\n def test_celsius_to_fahrenheit_4(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 27\n self.assertNotEqual(weatherSystem.celsius_to_fahrenheit(), 73.4)\n\n def test_celsius_to_fahrenheit_5(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 27\n self.assertNotEqual(weatherSystem.celsius_to_fahrenheit(), 23)",
"solution_code": "def celsius_to_fahrenheit(self):\n return (self.temperature * 9/5) + 32",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.temperature"
],
"method_dependencies": []
}
},
{
"method_name": "fahrenheit_to_celsius",
"method_description": "def fahrenheit_to_celsius(self):\n \"\"\"\n Convert the temperature from Fahrenheit to Celsius.\n :return: the temperature in Celsius, float.\n >>> weatherSystem = WeatherSystem('New York')\n >>> weatherSystem.temperature = 80.6\n >>> weatherSystem.fahrenheit_to_celsius()\n 26.999999999999996\n\n \"\"\"",
"test_class": "WeatherSystemTestFahrenheitToCelsius",
"test_code": "class WeatherSystemTestFahrenheitToCelsius(unittest.TestCase):\n def test_fahrenheit_to_celsius(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 80.6\n self.assertEqual(weatherSystem.fahrenheit_to_celsius(), 26.999999999999996)\n\n def test_fahrenheit_to_celsius_2(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 73.4\n self.assertEqual(weatherSystem.fahrenheit_to_celsius(), 23.000000000000004)\n\n def test_fahrenheit_to_celsius_3(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 80\n self.assertNotEqual(weatherSystem.fahrenheit_to_celsius(), 23)\n\n def test_fahrenheit_to_celsius_4(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 73\n self.assertNotEqual(weatherSystem.fahrenheit_to_celsius(), 27)\n\n def test_fahrenheit_to_celsius_5(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 80\n self.assertNotEqual(weatherSystem.fahrenheit_to_celsius(), 27)",
"solution_code": "def fahrenheit_to_celsius(self):\n return (self.temperature - 32) * 5/9",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.temperature"
],
"method_dependencies": []
}
}
] | WeatherSystem | [
"WeatherSystemTestQuery",
"WeatherSystemTestSetCity",
"WeatherSystemTestCelsiusToFahrenheit",
"WeatherSystemTestFahrenheitToCelsius",
"WeatherSystemTestMain"
] | class WeatherSystem:
def __init__(self, city) -> None:
"""
Initialize the weather system with a city name.
"""
self.temperature = None
self.weather = None
self.city = city
self.weather_list = {}
| [
"self.city",
"self.temperature",
"self.weather",
"self.weather_list"
] |
ClassEval_97 | class Words2Numbers:
"""
The class provides a text-to-number conversion utility, allowing conversion of written numbers (in words) to their numerical representation.
"""
def __init__(self):
"""
Initialize the word lists and dictionaries required for conversion
"""
self.numwords = {}
self.units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]
self.tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
self.scales = ["hundred", "thousand", "million", "billion", "trillion"]
self.numwords["and"] = (1, 0)
for idx, word in enumerate(self.units):
self.numwords[word] = (1, idx)
for idx, word in enumerate(self.tens):
self.numwords[word] = (1, idx * 10)
for idx, word in enumerate(self.scales):
self.numwords[word] = (10 ** (idx * 3 or 2), 0)
self.ordinal_words = {'first': 1, 'second': 2, 'third': 3, 'fifth': 5, 'eighth': 8, 'ninth': 9, 'twelfth': 12}
self.ordinal_endings = [('ieth', 'y'), ('th', '')]
def text2int(self, textnum):
"""
Convert the word string to the corresponding integer string
:param textnum: string, the word string to be converted
:return: string, the final converted integer string
>>> w2n = Words2Numbers()
>>> w2n.text2int("thirty-two")
"32"
"""
def is_valid_input(self, textnum):
"""
Check if the input text contains only valid words that can be converted into numbers.
:param textnum: The input text containing words representing numbers.
:return: True if input is valid, False otherwise.
>>> w2n = Words2Numbers()
>>> w2n.is_valid_input("thirty-two")
False
""" | import unittest
class Words2NumbersTestText2Int(unittest.TestCase):
def test_text2int(self):
w2n = Words2Numbers()
self.assertEqual(w2n.text2int("thirty-two"), "32")
def test_text2int2(self):
w2n = Words2Numbers()
self.assertEqual(w2n.text2int("one hundred and twenty-three"), "123")
def test_text2int3(self):
w2n = Words2Numbers()
self.assertEqual(w2n.text2int("two thousand and nineteen"), "2019")
def test_text2int4(self):
w2n = Words2Numbers()
self.assertEqual(w2n.text2int("one hundred and one"), "101")
def test_text2int5(self):
w2n = Words2Numbers()
self.assertEqual(w2n.text2int("one million and eleven"), "1000011")
def test_text2int6(self):
w2n = Words2Numbers()
self.assertEqual(w2n.text2int("one million one hundred sixty-ninth"), "1000169")
class Words2NumbersTestIsValidInput(unittest.TestCase):
def test_is_valid_input(self):
w2n = Words2Numbers()
self.assertTrue(w2n.is_valid_input("twenty-five thousand three hundred and forty-two"))
def test_is_valid_input2(self):
w2n = Words2Numbers()
self.assertTrue(w2n.is_valid_input("second hundred and third"))
def test_is_valid_input3(self):
w2n = Words2Numbers()
self.assertTrue(w2n.is_valid_input("twenty-fifth thousand three hundred and forty-second"))
def test_is_valid_input4(self):
w2n = Words2Numbers()
self.assertFalse(w2n.is_valid_input("eleventy thousand and five"))
def test_is_valid_input5(self):
w2n = Words2Numbers()
self.assertTrue(w2n.is_valid_input("seventy two thousand and hundred eleven"))
def test_is_valid_input6(self):
w2n = Words2Numbers()
self.assertTrue(w2n.is_valid_input("fifteenth hundred"))
class Words2NumbersTestMain(unittest.TestCase):
def test_main(self):
w2n = Words2Numbers()
self.assertEqual(w2n.is_valid_input("seventy two thousand and hundred eleven"), True)
self.assertEqual(w2n.text2int("seventy two thousand and hundred eleven"), "72011") | class Words2Numbers:
def __init__(self):
self.numwords = {}
self.units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]
self.tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
self.scales = ["hundred", "thousand", "million", "billion", "trillion"]
self.numwords["and"] = (1, 0)
for idx, word in enumerate(self.units):
self.numwords[word] = (1, idx)
for idx, word in enumerate(self.tens):
self.numwords[word] = (1, idx * 10)
for idx, word in enumerate(self.scales):
self.numwords[word] = (10 ** (idx * 3 or 2), 0)
self.ordinal_words = {'first': 1, 'second': 2, 'third': 3, 'fifth': 5, 'eighth': 8, 'ninth': 9, 'twelfth': 12}
self.ordinal_endings = [('ieth', 'y'), ('th', '')]
def text2int(self, textnum):
textnum = textnum.replace('-', ' ')
current = result = 0
curstring = ""
onnumber = False
for word in textnum.split():
if word in self.ordinal_words:
scale, increment = (1, self.ordinal_words[word])
current = current * scale + increment
onnumber = True
else:
for ending, replacement in self.ordinal_endings:
if word.endswith(ending):
word = "%s%s" % (word[:-len(ending)], replacement)
if word not in self.numwords:
if onnumber:
curstring += repr(result + current) + " "
curstring += word + " "
result = current = 0
onnumber = False
else:
scale, increment = self.numwords[word]
current = current * scale + increment
if scale > 100:
result += current
current = 0
onnumber = True
if onnumber:
curstring += repr(result + current)
return curstring
def is_valid_input(self, textnum):
textnum = textnum.replace('-', ' ')
for word in textnum.split():
if word in self.ordinal_words:
continue
else:
for ending, replacement in self.ordinal_endings:
if word.endswith(ending):
word = "%s%s" % (word[:-len(ending)], replacement)
if word not in self.numwords:
return False
return True | [] | """
The class provides a text-to-number conversion utility, allowing conversion of written numbers (in words) to their numerical representation.
"""
| [
{
"method_name": "text2int",
"method_description": "def text2int(self, textnum):\n \"\"\"\n Convert the word string to the corresponding integer string\n :param textnum: string, the word string to be converted\n :return: string, the final converted integer string\n >>> w2n = Words2Numbers()\n >>> w2n.text2int(\"thirty-two\")\n \"32\"\n \"\"\"",
"test_class": "Words2NumbersTestText2Int",
"test_code": "class Words2NumbersTestText2Int(unittest.TestCase):\n def test_text2int(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"thirty-two\"), \"32\")\n\n def test_text2int2(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"one hundred and twenty-three\"), \"123\")\n\n def test_text2int3(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"two thousand and nineteen\"), \"2019\")\n\n def test_text2int4(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"one hundred and one\"), \"101\")\n\n def test_text2int5(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"one million and eleven\"), \"1000011\")\n\n def test_text2int6(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"one million one hundred sixty-ninth\"), \"1000169\")",
"solution_code": "def text2int(self, textnum):\n textnum = textnum.replace('-', ' ')\n\n current = result = 0\n curstring = \"\"\n onnumber = False\n for word in textnum.split():\n if word in self.ordinal_words:\n scale, increment = (1, self.ordinal_words[word])\n current = current * scale + increment\n onnumber = True\n else:\n for ending, replacement in self.ordinal_endings:\n if word.endswith(ending):\n word = \"%s%s\" % (word[:-len(ending)], replacement)\n\n if word not in self.numwords:\n if onnumber:\n curstring += repr(result + current) + \" \"\n curstring += word + \" \"\n result = current = 0\n onnumber = False\n else:\n scale, increment = self.numwords[word]\n current = current * scale + increment\n if scale > 100:\n result += current\n current = 0\n onnumber = True\n\n if onnumber:\n curstring += repr(result + current)\n\n return curstring",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.numwords",
"self.ordinal_endings",
"self.ordinal_words"
],
"method_dependencies": []
}
},
{
"method_name": "is_valid_input",
"method_description": "def is_valid_input(self, textnum):\n \"\"\"\n Check if the input text contains only valid words that can be converted into numbers.\n :param textnum: The input text containing words representing numbers.\n :return: True if input is valid, False otherwise.\n >>> w2n = Words2Numbers()\n >>> w2n.is_valid_input(\"thirty-two\")\n False\n \"\"\"",
"test_class": "Words2NumbersTestIsValidInput",
"test_code": "class Words2NumbersTestIsValidInput(unittest.TestCase):\n def test_is_valid_input(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"twenty-five thousand three hundred and forty-two\"))\n\n def test_is_valid_input2(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"second hundred and third\"))\n\n def test_is_valid_input3(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"twenty-fifth thousand three hundred and forty-second\"))\n\n def test_is_valid_input4(self):\n w2n = Words2Numbers()\n self.assertFalse(w2n.is_valid_input(\"eleventy thousand and five\"))\n\n def test_is_valid_input5(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"seventy two thousand and hundred eleven\"))\n\n def test_is_valid_input6(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"fifteenth hundred\"))",
"solution_code": "def is_valid_input(self, textnum):\n\n textnum = textnum.replace('-', ' ')\n\n for word in textnum.split():\n if word in self.ordinal_words:\n continue\n else:\n for ending, replacement in self.ordinal_endings:\n if word.endswith(ending):\n word = \"%s%s\" % (word[:-len(ending)], replacement)\n\n if word not in self.numwords:\n return False\n\n return True",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.numwords",
"self.ordinal_endings",
"self.ordinal_words"
],
"method_dependencies": []
}
}
] | Words2Numbers | [
"Words2NumbersTestText2Int",
"Words2NumbersTestIsValidInput",
" Words2NumbersTestMain"
] | class Words2Numbers:
def __init__(self):
"""
Initialize the word lists and dictionaries required for conversion
"""
self.numwords = {}
self.units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]
self.tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
self.scales = ["hundred", "thousand", "million", "billion", "trillion"]
self.numwords["and"] = (1, 0)
for idx, word in enumerate(self.units):
self.numwords[word] = (1, idx)
for idx, word in enumerate(self.tens):
self.numwords[word] = (1, idx * 10)
for idx, word in enumerate(self.scales):
self.numwords[word] = (10 ** (idx * 3 or 2), 0)
self.ordinal_words = {'first': 1, 'second': 2, 'third': 3, 'fifth': 5, 'eighth': 8, 'ninth': 9, 'twelfth': 12}
self.ordinal_endings = [('ieth', 'y'), ('th', '')]
| [
"self.numwords",
"self.ordinal_endings",
"self.ordinal_words",
"self.scales",
"self.tens",
"self.units"
] |
ClassEval_98 | import xml.etree.ElementTree as ET
class XMLProcessor:
"""
This is a class as XML files handler, including reading, writing, processing as well as finding elements in a XML file.
"""
def __init__(self, file_name):
"""
Initialize the XMLProcessor object with the given file name.
:param file_name:string, the name of the XML file to be processed.
"""
self.file_name = file_name
self.root = None
def read_xml(self):
"""
Reads the XML file and returns the root element.
:return: Element, the root element of the XML file.
>>> xml_processor = XMLProcessor('test.xml')
>>> root_element = xml_processor.read_xml()
>>> print(root_element)
<Element 'root' at 0x7f8e3b7eb180>
"""
def write_xml(self, file_name):
"""
Writes the XML data to the specified file.
:param file_name: string, the name of the file to write the XML data.
:return: bool, True if the write operation is successful, False otherwise.
>>> xml_processor = XMLProcessor('test.xml')
>>> root = xml_processor.read_xml()
>>> success = xml_processor.write_xml('output.xml')
>>> print(success)
True
"""
def process_xml_data(self, file_name):
"""
Modifies the data in XML elements and writes the updated XML data to a new file.
:param file_name: string, the name of the file to write the modified XML data.
:return: bool, True if the write operation is successful, False otherwise.
>>> xml_processor = XMLProcessor('test.xml')
>>> root = xml_processor.read_xml()
>>> success = xml_processor.process_xml_data('processed.xml')
>>> print(success)
True
"""
def find_element(self, element_name):
"""
Finds the XML elements with the specified name.
:param element_name: string, the name of the elements to find.
:return: list, a list of found elements with the specified name.
>>> xml_processor = XMLProcessor('test.xml')
>>> root = xml_processor.read_xml()
>>> items = xml_processor.find_element('item')
>>> for item in items:
>>> print(item.text)
apple
banana
orange
""" | import unittest
import os
class XMLProcessorTestReadXml(unittest.TestCase):
def test_read_xml_1(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>banana</item>\n <item>orange</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
root = self.processor.read_xml()
self.assertIsNotNone(root)
lst = root.findall('item')
self.assertEqual(lst[0].text, 'apple')
self.assertEqual(lst[1].text, 'banana')
self.assertEqual(lst[2].text, 'orange')
os.remove('test.xml')
def test_read_xml_2(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>aaa</item>\n <item>bbb</item>\n <item>ccc</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
root = self.processor.read_xml()
self.assertIsNotNone(root)
lst = root.findall('item')
self.assertEqual(lst[0].text, 'aaa')
self.assertEqual(lst[1].text, 'bbb')
self.assertEqual(lst[2].text, 'ccc')
os.remove('test.xml')
def test_read_xml_3(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
root = self.processor.read_xml()
self.assertIsNotNone(root)
lst = root.findall('item')
self.assertEqual(lst[0].text, 'apple')
os.remove('test.xml')
def test_read_xml_4(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>banana</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
root = self.processor.read_xml()
self.assertIsNotNone(root)
lst = root.findall('item')
self.assertEqual(lst[0].text, 'apple')
self.assertEqual(lst[1].text, 'banana')
os.remove('test.xml')
def test_read_xml_5(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>orange</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
root = self.processor.read_xml()
self.assertIsNotNone(root)
lst = root.findall('item')
self.assertEqual(lst[0].text, 'apple')
self.assertEqual(lst[1].text, 'orange')
os.remove('test.xml')
def test_read_xml_6(self):
self.xml_file = ''
self.processor = XMLProcessor(self.xml_file)
root = self.processor.read_xml()
self.assertIsNone(root)
class XMLProcessorTestWriteXml(unittest.TestCase):
def test_write_xml_1(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>banana</item>\n <item>orange</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
file_name = 'output.xml'
result = self.processor.write_xml(file_name)
self.assertTrue(result)
processor1 = XMLProcessor(file_name)
tree1 = ET.parse(processor1.file_name)
processor1.root = tree1.getroot()
self.assertIsNotNone(processor1.root)
lst = processor1.root.findall('item')
self.assertEqual(lst[0].text, 'apple')
self.assertEqual(lst[1].text, 'banana')
self.assertEqual(lst[2].text, 'orange')
os.remove('output.xml')
os.remove('test.xml')
def test_write_xml_2(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>banana</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
file_name = 'output.xml'
result = self.processor.write_xml(file_name)
self.assertTrue(result)
processor1 = XMLProcessor(file_name)
tree1 = ET.parse(processor1.file_name)
processor1.root = tree1.getroot()
self.assertIsNotNone(processor1.root)
lst = processor1.root.findall('item')
self.assertEqual(lst[0].text, 'apple')
self.assertEqual(lst[1].text, 'banana')
os.remove('output.xml')
os.remove('test.xml')
def test_write_xml_3(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
file_name = 'output.xml'
result = self.processor.write_xml(file_name)
self.assertTrue(result)
processor1 = XMLProcessor(file_name)
tree1 = ET.parse(processor1.file_name)
processor1.root = tree1.getroot()
self.assertIsNotNone(processor1.root)
lst = processor1.root.findall('item')
self.assertEqual(lst[0].text, 'apple')
os.remove('output.xml')
os.remove('test.xml')
def test_write_xml_4(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>aaa</item>\n <item>bbb</item>\n <item>ccc</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
file_name = 'output.xml'
result = self.processor.write_xml(file_name)
self.assertTrue(result)
processor1 = XMLProcessor(file_name)
tree1 = ET.parse(processor1.file_name)
processor1.root = tree1.getroot()
self.assertIsNotNone(processor1.root)
lst = processor1.root.findall('item')
self.assertEqual(lst[0].text, 'aaa')
self.assertEqual(lst[1].text, 'bbb')
self.assertEqual(lst[2].text, 'ccc')
os.remove('output.xml')
os.remove('test.xml')
def test_write_xml_5(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>orange</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
file_name = 'output.xml'
result = self.processor.write_xml(file_name)
self.assertTrue(result)
processor1 = XMLProcessor(file_name)
tree1 = ET.parse(processor1.file_name)
processor1.root = tree1.getroot()
self.assertIsNotNone(processor1.root)
lst = processor1.root.findall('item')
self.assertEqual(lst[0].text, 'apple')
self.assertEqual(lst[1].text, 'orange')
os.remove('output.xml')
os.remove('test.xml')
def test_write_xml_6(self):
self.xml_file = ''
self.processor = XMLProcessor(self.xml_file)
result = self.processor.write_xml("")
self.assertFalse(result)
class XMLProcessorTestProcessXmlData(unittest.TestCase):
def test_process_xml_data_1(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>banana</item>\n <item>orange</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
file_name = 'processed.xml'
result = self.processor.process_xml_data(file_name)
self.assertTrue(result)
processor1 = XMLProcessor(file_name)
tree1 = ET.parse(processor1.file_name)
processor1.root = tree1.getroot()
self.assertIsNotNone(processor1.root)
lst = processor1.root.findall('item')
self.assertEqual(lst[0].text, 'APPLE')
self.assertEqual(lst[1].text, 'BANANA')
self.assertEqual(lst[2].text, 'ORANGE')
os.remove('processed.xml')
os.remove('test.xml')
def test_process_xml_data_2(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>banana</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
file_name = 'processed.xml'
result = self.processor.process_xml_data(file_name)
self.assertTrue(result)
processor1 = XMLProcessor(file_name)
tree1 = ET.parse(processor1.file_name)
processor1.root = tree1.getroot()
self.assertIsNotNone(processor1.root)
lst = processor1.root.findall('item')
self.assertEqual(lst[0].text, 'APPLE')
self.assertEqual(lst[1].text, 'BANANA')
os.remove('processed.xml')
os.remove('test.xml')
def test_process_xml_data_3(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
file_name = 'processed.xml'
result = self.processor.process_xml_data(file_name)
self.assertTrue(result)
processor1 = XMLProcessor(file_name)
tree1 = ET.parse(processor1.file_name)
processor1.root = tree1.getroot()
self.assertIsNotNone(processor1.root)
lst = processor1.root.findall('item')
self.assertEqual(lst[0].text, 'APPLE')
os.remove('processed.xml')
os.remove('test.xml')
def test_process_xml_data_4(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>orange</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
file_name = 'processed.xml'
result = self.processor.process_xml_data(file_name)
self.assertTrue(result)
processor1 = XMLProcessor(file_name)
tree1 = ET.parse(processor1.file_name)
processor1.root = tree1.getroot()
self.assertIsNotNone(processor1.root)
lst = processor1.root.findall('item')
self.assertEqual(lst[0].text, 'APPLE')
self.assertEqual(lst[1].text, 'ORANGE')
os.remove('processed.xml')
os.remove('test.xml')
def test_process_xml_data_5(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>aaa</item>\n <item>bbb</item>\n <item>ccc</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
file_name = 'processed.xml'
result = self.processor.process_xml_data(file_name)
self.assertTrue(result)
processor1 = XMLProcessor(file_name)
tree1 = ET.parse(processor1.file_name)
processor1.root = tree1.getroot()
self.assertIsNotNone(processor1.root)
lst = processor1.root.findall('item')
self.assertEqual(lst[0].text, 'AAA')
self.assertEqual(lst[1].text, 'BBB')
self.assertEqual(lst[2].text, 'CCC')
os.remove('processed.xml')
os.remove('test.xml')
class XMLProcessorTestFindElement(unittest.TestCase):
def test_find_element_1(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>banana</item>\n <item>orange</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
element_name = 'item'
root = self.processor.read_xml()
elements = self.processor.find_element(element_name)
self.assertEqual(len(elements), 3)
self.assertEqual(elements[0].text, 'apple')
self.assertEqual(elements[1].text, 'banana')
self.assertEqual(elements[2].text, 'orange')
os.remove('test.xml')
def test_find_element_2(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>banana</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
element_name = 'item'
root = self.processor.read_xml()
elements = self.processor.find_element(element_name)
self.assertEqual(len(elements), 2)
self.assertEqual(elements[0].text, 'apple')
self.assertEqual(elements[1].text, 'banana')
os.remove('test.xml')
def test_find_element_3(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
element_name = 'item'
root = self.processor.read_xml()
elements = self.processor.find_element(element_name)
self.assertEqual(len(elements), 1)
self.assertEqual(elements[0].text, 'apple')
os.remove('test.xml')
def test_find_element_4(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>orange</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
element_name = 'item'
root = self.processor.read_xml()
elements = self.processor.find_element(element_name)
self.assertEqual(len(elements), 2)
self.assertEqual(elements[0].text, 'apple')
self.assertEqual(elements[1].text, 'orange')
os.remove('test.xml')
def test_find_element_5(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>aaa</item>\n <item>bbb</item>\n <item>ccc</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
element_name = 'item'
root = self.processor.read_xml()
elements = self.processor.find_element(element_name)
self.assertEqual(len(elements), 3)
self.assertEqual(elements[0].text, 'aaa')
self.assertEqual(elements[1].text, 'bbb')
self.assertEqual(elements[2].text, 'ccc')
os.remove('test.xml')
class XMLProcessorTest(unittest.TestCase):
def test_XMLProcessor(self):
with open('test.xml', 'w') as f:
f.write('<root>\n <item>apple</item>\n <item>banana</item>\n <item>orange</item>\n</root>')
self.xml_file = 'test.xml'
self.processor = XMLProcessor(self.xml_file)
tree = ET.parse(self.processor.file_name)
self.processor.root = tree.getroot()
root = self.processor.read_xml()
self.assertIsNotNone(root)
lst = root.findall('item')
self.assertEqual(lst[0].text, 'apple')
self.assertEqual(lst[1].text, 'banana')
self.assertEqual(lst[2].text, 'orange')
file_name = 'output.xml'
result = self.processor.write_xml(file_name)
self.assertTrue(result)
processor1 = XMLProcessor(file_name)
tree1 = ET.parse(processor1.file_name)
processor1.root = tree1.getroot()
self.assertIsNotNone(processor1.root)
lst = processor1.root.findall('item')
self.assertEqual(lst[0].text, 'apple')
self.assertEqual(lst[1].text, 'banana')
self.assertEqual(lst[2].text, 'orange')
os.remove('output.xml')
file_name = 'processed.xml'
result = self.processor.process_xml_data(file_name)
self.assertTrue(result)
processor1 = XMLProcessor(file_name)
tree1 = ET.parse(processor1.file_name)
processor1.root = tree1.getroot()
self.assertIsNotNone(processor1.root)
lst = processor1.root.findall('item')
self.assertEqual(lst[0].text, 'APPLE')
self.assertEqual(lst[1].text, 'BANANA')
self.assertEqual(lst[2].text, 'ORANGE')
os.remove('processed.xml')
element_name = 'item'
root = self.processor.read_xml()
elements = self.processor.find_element(element_name)
self.assertEqual(len(elements), 3)
self.assertEqual(elements[0].text, 'apple')
self.assertEqual(elements[1].text, 'banana')
self.assertEqual(elements[2].text, 'orange')
os.remove('test.xml') | import xml.etree.ElementTree as ET
class XMLProcessor:
def __init__(self, file_name):
self.file_name = file_name
self.root = None
def read_xml(self):
try:
tree = ET.parse(self.file_name)
self.root = tree.getroot()
return self.root
except:
return None
def write_xml(self, file_name):
try:
tree = ET.ElementTree(self.root)
tree.write(file_name)
return True
except:
return False
def process_xml_data(self, file_name):
for element in self.root.iter('item'):
text = element.text
element.text = text.upper()
return self.write_xml(file_name)
def find_element(self, element_name):
elements = self.root.findall(element_name)
return elements | [
"import xml.etree.ElementTree as ET"
] | """
This is a class as XML files handler, including reading, writing, processing as well as finding elements in a XML file.
"""
| [
{
"method_name": "read_xml",
"method_description": "def read_xml(self):\n \"\"\"\n Reads the XML file and returns the root element.\n :return: Element, the root element of the XML file.\n >>> xml_processor = XMLProcessor('test.xml')\n >>> root_element = xml_processor.read_xml()\n >>> print(root_element)\n <Element 'root' at 0x7f8e3b7eb180>\n \"\"\"",
"test_class": "XMLProcessorTestReadXml",
"test_code": "class XMLProcessorTestReadXml(unittest.TestCase):\n def test_read_xml_1(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n <item>banana</item>\\n <item>orange</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n self.assertEqual(lst[2].text, 'orange')\n\n os.remove('test.xml')\n\n def test_read_xml_2(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>aaa</item>\\n <item>bbb</item>\\n <item>ccc</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'aaa')\n self.assertEqual(lst[1].text, 'bbb')\n self.assertEqual(lst[2].text, 'ccc')\n\n os.remove('test.xml')\n\n def test_read_xml_3(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n\n os.remove('test.xml')\n\n def test_read_xml_4(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n <item>banana</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n\n os.remove('test.xml')\n\n def test_read_xml_5(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n <item>orange</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'orange')\n\n os.remove('test.xml')\n\n def test_read_xml_6(self):\n self.xml_file = ''\n self.processor = XMLProcessor(self.xml_file)\n\n root = self.processor.read_xml()\n self.assertIsNone(root)",
"solution_code": "def read_xml(self):\n try:\n tree = ET.parse(self.file_name)\n self.root = tree.getroot()\n return self.root\n except:\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.file_name",
"self.root"
],
"method_dependencies": []
}
},
{
"method_name": "write_xml",
"method_description": "def write_xml(self, file_name):\n \"\"\"\n Writes the XML data to the specified file.\n :param file_name: string, the name of the file to write the XML data.\n :return: bool, True if the write operation is successful, False otherwise.\n >>> xml_processor = XMLProcessor('test.xml')\n >>> root = xml_processor.read_xml()\n >>> success = xml_processor.write_xml('output.xml')\n >>> print(success)\n True\n \"\"\"",
"test_class": "XMLProcessorTestWriteXml",
"test_code": "class XMLProcessorTestWriteXml(unittest.TestCase):\n def test_write_xml_1(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n <item>banana</item>\\n <item>orange</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n self.assertEqual(lst[2].text, 'orange')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_2(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n <item>banana</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_3(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_4(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>aaa</item>\\n <item>bbb</item>\\n <item>ccc</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'aaa')\n self.assertEqual(lst[1].text, 'bbb')\n self.assertEqual(lst[2].text, 'ccc')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_5(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n <item>orange</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'orange')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_6(self):\n self.xml_file = ''\n self.processor = XMLProcessor(self.xml_file)\n\n result = self.processor.write_xml(\"\")\n self.assertFalse(result)",
"solution_code": "def write_xml(self, file_name):\n try:\n tree = ET.ElementTree(self.root)\n tree.write(file_name)\n return True\n except:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.root"
],
"method_dependencies": []
}
},
{
"method_name": "process_xml_data",
"method_description": "def process_xml_data(self, file_name):\n \"\"\"\n Modifies the data in XML elements and writes the updated XML data to a new file.\n :param file_name: string, the name of the file to write the modified XML data.\n :return: bool, True if the write operation is successful, False otherwise.\n >>> xml_processor = XMLProcessor('test.xml')\n >>> root = xml_processor.read_xml()\n >>> success = xml_processor.process_xml_data('processed.xml')\n >>> print(success)\n True\n \"\"\"",
"test_class": "XMLProcessorTestProcessXmlData",
"test_code": "class XMLProcessorTestProcessXmlData(unittest.TestCase):\n def test_process_xml_data_1(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n <item>banana</item>\\n <item>orange</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'APPLE')\n self.assertEqual(lst[1].text, 'BANANA')\n self.assertEqual(lst[2].text, 'ORANGE')\n\n os.remove('processed.xml')\n os.remove('test.xml')\n\n def test_process_xml_data_2(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n <item>banana</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'APPLE')\n self.assertEqual(lst[1].text, 'BANANA')\n\n os.remove('processed.xml')\n os.remove('test.xml')\n\n def test_process_xml_data_3(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'APPLE')\n\n os.remove('processed.xml')\n os.remove('test.xml')\n\n def test_process_xml_data_4(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n <item>orange</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'APPLE')\n self.assertEqual(lst[1].text, 'ORANGE')\n\n os.remove('processed.xml')\n os.remove('test.xml')\n\n def test_process_xml_data_5(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>aaa</item>\\n <item>bbb</item>\\n <item>ccc</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'AAA')\n self.assertEqual(lst[1].text, 'BBB')\n self.assertEqual(lst[2].text, 'CCC')\n\n os.remove('processed.xml')\n os.remove('test.xml')",
"solution_code": "def process_xml_data(self, file_name):\n for element in self.root.iter('item'):\n text = element.text\n element.text = text.upper()\n return self.write_xml(file_name)",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.root"
],
"method_dependencies": [
"write_xml"
]
}
},
{
"method_name": "find_element",
"method_description": "def find_element(self, element_name):\n \"\"\"\n Finds the XML elements with the specified name.\n :param element_name: string, the name of the elements to find.\n :return: list, a list of found elements with the specified name.\n >>> xml_processor = XMLProcessor('test.xml')\n >>> root = xml_processor.read_xml()\n >>> items = xml_processor.find_element('item')\n >>> for item in items:\n >>> print(item.text)\n apple\n banana\n orange\n \"\"\"",
"test_class": "XMLProcessorTestFindElement",
"test_code": "class XMLProcessorTestFindElement(unittest.TestCase):\n def test_find_element_1(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n <item>banana</item>\\n <item>orange</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 3)\n self.assertEqual(elements[0].text, 'apple')\n self.assertEqual(elements[1].text, 'banana')\n self.assertEqual(elements[2].text, 'orange')\n\n os.remove('test.xml')\n\n def test_find_element_2(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n <item>banana</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 2)\n self.assertEqual(elements[0].text, 'apple')\n self.assertEqual(elements[1].text, 'banana')\n\n os.remove('test.xml')\n\n def test_find_element_3(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 1)\n self.assertEqual(elements[0].text, 'apple')\n\n os.remove('test.xml')\n\n def test_find_element_4(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>apple</item>\\n <item>orange</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 2)\n self.assertEqual(elements[0].text, 'apple')\n self.assertEqual(elements[1].text, 'orange')\n\n os.remove('test.xml')\n\n def test_find_element_5(self):\n with open('test.xml', 'w') as f:\n f.write('<root>\\n <item>aaa</item>\\n <item>bbb</item>\\n <item>ccc</item>\\n</root>')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 3)\n self.assertEqual(elements[0].text, 'aaa')\n self.assertEqual(elements[1].text, 'bbb')\n self.assertEqual(elements[2].text, 'ccc')\n\n os.remove('test.xml')",
"solution_code": "def find_element(self, element_name):\n elements = self.root.findall(element_name)\n return elements",
"dependencies": {
"Standalone": false,
"lib_dependencies": [],
"field_dependencies": [
"self.root"
],
"method_dependencies": []
}
}
] | XMLProcessor | [
"XMLProcessorTestReadXml",
"XMLProcessorTestWriteXml",
"XMLProcessorTestProcessXmlData",
"XMLProcessorTestFindElement",
"XMLProcessorTest"
] | class XMLProcessor:
def __init__(self, file_name):
"""
Initialize the XMLProcessor object with the given file name.
:param file_name:string, the name of the XML file to be processed.
"""
self.file_name = file_name
self.root = None
| [
"self.file_name",
"self.root"
] |
ClassEval_99 | import zipfile
class ZipFileProcessor:
"""
This is a compressed file processing class that provides the ability to read and decompress compressed files
"""
def __init__(self, file_name):
"""
Initialize file name
:param file_name:string
"""
self.file_name = file_name
def read_zip_file(self):
"""
Get open file object
:return:If successful, returns the open file object; otherwise, returns None
>>> zfp = ZipFileProcessor("aaa.zip")
>>> file = zfp.read_zip_file()
"""
def extract_all(self, output_path):
"""
Extract all zip files and place them in the specified path
:param output_path: string, The location of the extracted file
:return: True or False, representing whether the extraction operation was successful
>>> zfp = ZipFileProcessor("aaa.zip")
>>> zfp.extract_all("result/aaa")
"""
def extract_file(self, file_name, output_path):
"""
Extract the file with the specified name from the zip file and place it in the specified path
:param file_name:string, The name of the file to be uncompressed
:param output_path:string, The location of the extracted file
:return: True or False, representing whether the extraction operation was successful
>>> zfp = ZipFileProcessor("aaa.zip")
>>> zfp.extract_file("bbb.txt", "result/aaa")
"""
def create_zip_file(self, files, output_file_name):
"""
Compress the specified file list into a zip file and place it in the specified path
:param files:list of string, List of files to compress
:param output_file_name: string, Specified output path
:return:True or False, representing whether the compression operation was successful
>>> zfp = ZipFileProcessor("aaa.zip")
>>> zfp.create_zip_file(["bbb.txt", "ccc,txt", "ddd.txt"], "output/bcd")
""" | import unittest
import os
class ZipFileProcessorTestReadZipFile(unittest.TestCase):
def test_read_zip_file_1(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example1.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
zip_file = processor.read_zip_file()
self.assertEqual(zip_file.filename, 'example1.zip')
self.assertEqual(zip_file.mode, 'r')
zip_file.close()
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_read_zip_file_2(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example2.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
zip_file = processor.read_zip_file()
self.assertEqual(zip_file.filename, 'example2.zip')
self.assertEqual(zip_file.mode, 'r')
zip_file.close()
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_read_zip_file_3(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example3.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
zip_file = processor.read_zip_file()
self.assertEqual(zip_file.filename, 'example3.zip')
self.assertEqual(zip_file.mode, 'r')
zip_file.close()
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_read_zip_file_4(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example4.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
zip_file = processor.read_zip_file()
self.assertEqual(zip_file.filename, 'example4.zip')
self.assertEqual(zip_file.mode, 'r')
zip_file.close()
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_read_zip_file_5(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example5.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
zip_file = processor.read_zip_file()
self.assertEqual(zip_file.filename, 'example5.zip')
self.assertEqual(zip_file.mode, 'r')
zip_file.close()
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_read_zip_file_6(self):
processor = ZipFileProcessor("")
zip_file = processor.read_zip_file()
self.assertIsNone(zip_file)
class ZipFileProcessorTestExtractAll(unittest.TestCase):
def test_extract_all_1(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example1.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
success = processor.extract_all(output_directory)
self.assertTrue(success)
self.assertTrue(os.path.exists(os.path.join(output_directory, 'example1.txt')))
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_extract_all_2(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example2.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
success = processor.extract_all(output_directory)
self.assertTrue(success)
self.assertTrue(os.path.exists(os.path.join(output_directory, 'example2.txt')))
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_extract_all_3(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example3.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
success = processor.extract_all(output_directory)
self.assertTrue(success)
self.assertTrue(os.path.exists(os.path.join(output_directory, 'example3.txt')))
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_extract_all_4(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example4.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
success = processor.extract_all(output_directory)
self.assertTrue(success)
self.assertTrue(os.path.exists(os.path.join(output_directory, 'example4.txt')))
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_extract_all_5(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example5.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
success = processor.extract_all(output_directory)
self.assertTrue(success)
self.assertTrue(os.path.exists(os.path.join(output_directory, 'example5.txt')))
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_extract_all_6(self):
processor = ZipFileProcessor("")
success = processor.extract_all("")
self.assertFalse(success)
class ZipFileProcessorTestExtractFile(unittest.TestCase):
def test_extract_file_1(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example1.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
success = processor.extract_file('example1.txt', output_directory)
self.assertTrue(success)
self.assertTrue(os.path.exists(os.path.join(output_directory, 'example1.txt')))
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_extract_file_2(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example2.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
success = processor.extract_file('example2.txt', output_directory)
self.assertTrue(success)
self.assertTrue(os.path.exists(os.path.join(output_directory, 'example2.txt')))
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_extract_file_3(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example3.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
success = processor.extract_file('example3.txt', output_directory)
self.assertTrue(success)
self.assertTrue(os.path.exists(os.path.join(output_directory, 'example3.txt')))
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_extract_file_4(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example4.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
success = processor.extract_file('example4.txt', output_directory)
self.assertTrue(success)
self.assertTrue(os.path.exists(os.path.join(output_directory, 'example4.txt')))
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_extract_file_5(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example5.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
success = processor.extract_file('example5.txt', output_directory)
self.assertTrue(success)
self.assertTrue(os.path.exists(os.path.join(output_directory, 'example5.txt')))
os.remove(zip_file_name)
os.remove(example_file_path)
os.rmdir(test_folder)
def test_extract_file_6(self):
processor = ZipFileProcessor("")
success = processor.extract_file("", "")
self.assertFalse(success)
class ZipFileProcessorTestCreateZipFile(unittest.TestCase):
def test_create_zip_file_1(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example1.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
files_to_zip = [example_file_path]
success = processor.create_zip_file(files_to_zip, new_zip_file)
self.assertTrue(success)
self.assertTrue(os.path.exists(new_zip_file))
os.remove(example_file_path)
os.rmdir(test_folder)
def test_create_zip_file_2(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example2.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
files_to_zip = [example_file_path]
success = processor.create_zip_file(files_to_zip, new_zip_file)
self.assertTrue(success)
self.assertTrue(os.path.exists(new_zip_file))
os.remove(example_file_path)
os.rmdir(test_folder)
def test_create_zip_file_3(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example3.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
files_to_zip = [example_file_path]
success = processor.create_zip_file(files_to_zip, new_zip_file)
self.assertTrue(success)
self.assertTrue(os.path.exists(new_zip_file))
os.remove(example_file_path)
os.rmdir(test_folder)
def test_create_zip_file_4(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example4.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
files_to_zip = [example_file_path]
success = processor.create_zip_file(files_to_zip, new_zip_file)
self.assertTrue(success)
self.assertTrue(os.path.exists(new_zip_file))
os.remove(example_file_path)
os.rmdir(test_folder)
def test_create_zip_file_5(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example5.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
new_zip_file = 'new_zip_file.zip'
files_to_zip = [example_file_path]
success = processor.create_zip_file(files_to_zip, new_zip_file)
self.assertTrue(success)
self.assertTrue(os.path.exists(new_zip_file))
os.remove(example_file_path)
os.rmdir(test_folder)
def test_create_zip_file_6(self):
processor = ZipFileProcessor("")
success = processor.create_zip_file("", "")
self.assertFalse(success)
class ZipFileProcessorTest(unittest.TestCase):
def test_ZipFileProcessor(self):
test_folder = 'test_folder'
os.makedirs(test_folder, exist_ok=True)
example_file_path = os.path.join(test_folder, 'example1.txt')
with open(example_file_path, 'w') as file:
file.write('This is an example file.')
zip_file_name = 'example.zip'
with zipfile.ZipFile(zip_file_name, 'w') as zip_file:
zip_file.write(example_file_path, os.path.basename(example_file_path))
processor = ZipFileProcessor(zip_file_name)
output_directory = 'output_directory'
new_zip_file = 'new_zip_file.zip'
zip_file = processor.read_zip_file()
self.assertEqual(zip_file.filename, 'example.zip')
self.assertEqual(zip_file.mode, 'r')
zip_file.close()
success = processor.extract_all(output_directory)
self.assertTrue(success)
self.assertTrue(os.path.exists(os.path.join(output_directory, 'example1.txt')))
files_to_zip = [example_file_path]
success = processor.create_zip_file(files_to_zip, new_zip_file)
self.assertTrue(success)
self.assertTrue(os.path.exists(new_zip_file))
success = processor.extract_file('example1.txt', output_directory)
self.assertTrue(success)
self.assertTrue(os.path.exists(os.path.join(output_directory, 'example1.txt')))
files_to_zip = [example_file_path]
success = processor.create_zip_file(files_to_zip, new_zip_file)
self.assertTrue(success)
self.assertTrue(os.path.exists(new_zip_file))
os.remove(example_file_path)
os.rmdir(test_folder) | import zipfile
class ZipFileProcessor:
def __init__(self, file_name):
self.file_name = file_name
def read_zip_file(self):
try:
zip_file = zipfile.ZipFile(self.file_name, 'r')
return zip_file
except:
return None
def extract_all(self, output_path):
try:
with zipfile.ZipFile(self.file_name, 'r') as zip_file:
zip_file.extractall(output_path)
return True
except:
return False
def extract_file(self, file_name, output_path):
try:
with zipfile.ZipFile(self.file_name, 'r') as zip_file:
zip_file.extract(file_name, output_path)
return True
except:
return False
def create_zip_file(self, files, output_file_name):
try:
with zipfile.ZipFile(output_file_name, 'w') as zip_file:
for file in files:
zip_file.write(file)
return True
except:
return False | [
"import zipfile"
] | """
This is a compressed file processing class that provides the ability to read and decompress compressed files
"""
| [
{
"method_name": "read_zip_file",
"method_description": "def read_zip_file(self):\n \"\"\"\n Get open file object\n :return:If successful, returns the open file object; otherwise, returns None\n >>> zfp = ZipFileProcessor(\"aaa.zip\")\n >>> file = zfp.read_zip_file()\n \"\"\"",
"test_class": "ZipFileProcessorTestReadZipFile",
"test_code": "class ZipFileProcessorTestReadZipFile(unittest.TestCase):\n def test_read_zip_file_1(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example1.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example1.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_2(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example2.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example2.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_3(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example3.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example3.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_4(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example4.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example4.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_5(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example5.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example5.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_6(self):\n processor = ZipFileProcessor(\"\")\n\n zip_file = processor.read_zip_file()\n self.assertIsNone(zip_file)",
"solution_code": "def read_zip_file(self):\n try:\n zip_file = zipfile.ZipFile(self.file_name, 'r')\n return zip_file\n except:\n return None",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"zipfile"
],
"field_dependencies": [
"self.file_name"
],
"method_dependencies": []
}
},
{
"method_name": "extract_all",
"method_description": "def extract_all(self, output_path):\n \"\"\"\n Extract all zip files and place them in the specified path\n :param output_path: string, The location of the extracted file\n :return: True or False, representing whether the extraction operation was successful\n >>> zfp = ZipFileProcessor(\"aaa.zip\")\n >>> zfp.extract_all(\"result/aaa\")\n \"\"\"",
"test_class": "ZipFileProcessorTestExtractAll",
"test_code": "class ZipFileProcessorTestExtractAll(unittest.TestCase):\n def test_extract_all_1(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example1.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example1.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_2(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example2.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example2.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_3(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example3.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example3.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_4(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example4.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example4.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_5(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example5.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example5.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_6(self):\n processor = ZipFileProcessor(\"\")\n\n success = processor.extract_all(\"\")\n self.assertFalse(success)",
"solution_code": "def extract_all(self, output_path):\n try:\n with zipfile.ZipFile(self.file_name, 'r') as zip_file:\n zip_file.extractall(output_path)\n return True\n except:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"zipfile"
],
"field_dependencies": [
"self.file_name"
],
"method_dependencies": []
}
},
{
"method_name": "extract_file",
"method_description": "def extract_file(self, file_name, output_path):\n \"\"\"\n Extract the file with the specified name from the zip file and place it in the specified path\n :param file_name:string, The name of the file to be uncompressed\n :param output_path:string, The location of the extracted file\n :return: True or False, representing whether the extraction operation was successful\n >>> zfp = ZipFileProcessor(\"aaa.zip\")\n >>> zfp.extract_file(\"bbb.txt\", \"result/aaa\")\n \"\"\"",
"test_class": "ZipFileProcessorTestExtractFile",
"test_code": "class ZipFileProcessorTestExtractFile(unittest.TestCase):\n def test_extract_file_1(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example1.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_file('example1.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example1.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_2(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example2.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_file('example2.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example2.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_3(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example3.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_file('example3.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example3.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_4(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example4.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_file('example4.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example4.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_5(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example5.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n\n success = processor.extract_file('example5.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example5.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_6(self):\n processor = ZipFileProcessor(\"\")\n\n success = processor.extract_file(\"\", \"\")\n self.assertFalse(success)",
"solution_code": "def extract_file(self, file_name, output_path):\n try:\n with zipfile.ZipFile(self.file_name, 'r') as zip_file:\n zip_file.extract(file_name, output_path)\n return True\n except:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"zipfile"
],
"field_dependencies": [
"self.file_name"
],
"method_dependencies": []
}
},
{
"method_name": "create_zip_file",
"method_description": "def create_zip_file(self, files, output_file_name):\n \"\"\"\n Compress the specified file list into a zip file and place it in the specified path\n :param files:list of string, List of files to compress\n :param output_file_name: string, Specified output path\n :return:True or False, representing whether the compression operation was successful\n >>> zfp = ZipFileProcessor(\"aaa.zip\")\n >>> zfp.create_zip_file([\"bbb.txt\", \"ccc,txt\", \"ddd.txt\"], \"output/bcd\")\n \"\"\"",
"test_class": "ZipFileProcessorTestCreateZipFile",
"test_code": "class ZipFileProcessorTestCreateZipFile(unittest.TestCase):\n def test_create_zip_file_1(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example1.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_2(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example2.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_3(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example3.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_4(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example4.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_5(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example5.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_6(self):\n processor = ZipFileProcessor(\"\")\n\n success = processor.create_zip_file(\"\", \"\")\n self.assertFalse(success)",
"solution_code": "def create_zip_file(self, files, output_file_name):\n try:\n with zipfile.ZipFile(output_file_name, 'w') as zip_file:\n for file in files:\n zip_file.write(file)\n return True\n except:\n return False",
"dependencies": {
"Standalone": false,
"lib_dependencies": [
"zipfile"
],
"field_dependencies": [],
"method_dependencies": []
}
}
] | ZipFileProcessor | [
"ZipFileProcessorTestReadZipFile",
"ZipFileProcessorTestExtractAll",
"ZipFileProcessorTestExtractFile",
"ZipFileProcessorTestCreateZipFile",
"ZipFileProcessorTest"
] | class ZipFileProcessor:
def __init__(self, file_name):
"""
Initialize file name
:param file_name:string
"""
self.file_name = file_name
| [
"self.file_name"
] |