class_id
stringlengths
15
16
class_code
stringlengths
519
6.03k
skeleton
stringlengths
561
4.56k
method_code
stringlengths
44
1.82k
method_summary
stringlengths
15
540
ClassEval_0_sum
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 is_start_with(self, request_uri): """ Check if the request URI starts with certain prefixes. :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 """ start_with = ["/api", '/login'] for s in start_with: if request_uri.startswith(s): return True return False 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'} """ 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): """ 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) """ host = user['address'] logging.log(msg=user['name'] + host + str(datetime.datetime.now()), level=1)
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 is_start_with(self, request_uri): """ Check if the request URI starts with certain prefixes. :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) """
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
Filter the incoming request based on certain rules and conditions.
ClassEval_0_sum
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 """ 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 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'} """ 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): """ 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) """ host = user['address'] logging.log(msg=user['name'] + host + str(datetime.datetime.now()), level=1)
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 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) """
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
Check if the request URI starts with certain prefixes.
ClassEval_0_sum
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 """ 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): """ Check if the request URI starts with certain prefixes. :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 """ start_with = ["/api", '/login'] for s in start_with: if request_uri.startswith(s): return True return False 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) """ host = user['address'] logging.log(msg=user['name'] + host + str(datetime.datetime.now()), level=1)
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. :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 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) """
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
Get the user information from the JWT token in the request.
ClassEval_0_sum
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 """ 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): """ Check if the request URI starts with certain prefixes. :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 """ start_with = ["/api", '/login'] for s in start_with: if request_uri.startswith(s): return True return False 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'} """ 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 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. :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) """
def set_current_user_info_and_log(self, user): host = user['address'] logging.log(msg=user['name'] + host + str(datetime.datetime.now()), level=1)
Set the current user information and log the access.
ClassEval_1_sum
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): self.radius = radius 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 """ return 4 * math.pi * self.radius ** 2 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 """ return 2 * math.pi * self.radius * (self.radius + height) 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 """ return self.radius ** 2 * angle / 2 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 """ return math.pi * (outer_radius ** 2 - inner_radius ** 2)
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_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 """
def calculate_circle_area(self): return math.pi * self.radius ** 2
calculate the area of circle based on self.radius
ClassEval_1_sum
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): 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 """ return math.pi * self.radius ** 2 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 """ return 2 * math.pi * self.radius * (self.radius + height) 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 """ return self.radius ** 2 * angle / 2 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 """ return math.pi * (outer_radius ** 2 - inner_radius ** 2)
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_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 """
def calculate_sphere_area(self): return 4 * math.pi * self.radius ** 2
calculate the area of sphere based on self.radius
ClassEval_1_sum
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): 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 """ return math.pi * self.radius ** 2 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 """ return 4 * math.pi * self.radius ** 2 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 """ return self.radius ** 2 * angle / 2 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 """ return math.pi * (outer_radius ** 2 - inner_radius ** 2)
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_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 """
def calculate_cylinder_area(self, height): return 2 * math.pi * self.radius * (self.radius + height)
calculate the area of cylinder based on self.radius and height
ClassEval_1_sum
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): 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 """ return math.pi * self.radius ** 2 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 """ return 4 * math.pi * self.radius ** 2 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 """ return 2 * math.pi * self.radius * (self.radius + height) 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 """ return math.pi * (outer_radius ** 2 - inner_radius ** 2)
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_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 """
def calculate_sector_area(self, angle): return self.radius ** 2 * angle / 2
calculate the area of sector based on self.radius and angle
ClassEval_1_sum
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): 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 """ return math.pi * self.radius ** 2 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 """ return 4 * math.pi * self.radius ** 2 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 """ return 2 * math.pi * self.radius * (self.radius + height) 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 """ 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 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 """
def calculate_annulus_area(self, inner_radius, outer_radius): return math.pi * (outer_radius ** 2 - inner_radius ** 2)
calculate the area of annulus based on inner_radius and out_radius
ClassEval_2_sum
class ArgumentParser: """ This is a class for parsing command line arguments to a dictionary. """ def __init__(self): self.arguments = {} self.required = set() self.types = {} 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' """ return self.arguments.get(key) 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'} """ if required: self.required.add(arg) self.types[arg] = arg_type 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 """ try: return self.types[arg](value) except (ValueError, KeyError): return value
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 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 """
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
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.
ClassEval_2_sum
class ArgumentParser: """ This is a class for parsing command line arguments to a dictionary. """ def __init__(self): 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} """ 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 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'} """ if required: self.required.add(arg) self.types[arg] = arg_type 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 """ try: return self.types[arg](value) except (ValueError, KeyError): return value
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 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 """
def get_argument(self, key): return self.arguments.get(key)
Retrieves the value of the specified argument from the arguments dictionary and returns it.
ClassEval_2_sum
class ArgumentParser: """ This is a class for parsing command line arguments to a dictionary. """ def __init__(self): 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} """ 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): """ 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' """ return self.arguments.get(key) 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 """ try: return self.types[arg](value) except (ValueError, KeyError): return value
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 _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 """
def add_argument(self, arg, required=False, arg_type=str): if required: self.required.add(arg) self.types[arg] = arg_type
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.
ClassEval_2_sum
class ArgumentParser: """ This is a class for parsing command line arguments to a dictionary. """ def __init__(self): 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} """ 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): """ 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' """ return self.arguments.get(key) 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'} """ 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
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 """
def _convert_type(self, arg, value): try: return self.types[arg](value) except (ValueError, KeyError): return value
Try to convert the type of input value by searching in self.types.
ClassEval_3_sum
import itertools class ArrangementCalculator: """ The Arrangement class provides permutation calculations and selection operations for a given set of data elements. """ def __init__(self, datas): self.datas = datas @staticmethod @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 """ total = 0 for i in range(1, n + 1): total += ArrangementCalculator.count(n, i) return total 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]] """ 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): """ 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]] """ result = [] for i in range(1, len(self.datas) + 1): result.extend(self.select(i)) return result @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 """ result = 1 for i in range(2, n + 1): result *= i return result
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 @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 """
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)
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).
ClassEval_3_sum
import itertools class ArrangementCalculator: """ The Arrangement class provides permutation calculations and selection operations for a given set of data elements. """ def __init__(self, datas): 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 """ if m is None or n == m: return ArrangementCalculator.factorial(n) else: return ArrangementCalculator.factorial(n) // ArrangementCalculator.factorial(n - m) 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]] """ 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): """ 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]] """ result = [] for i in range(1, len(self.datas) + 1): result.extend(self.select(i)) return result @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 """ result = 1 for i in range(2, n + 1): result *= i return result
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 """ 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 """
@staticmethod def count_all(n): total = 0 for i in range(1, n + 1): total += ArrangementCalculator.count(n, i) return total
Counts the total number of all possible arrangements by choosing at least 1 item and at most n items from n items.
ClassEval_3_sum
import itertools class ArrangementCalculator: """ The Arrangement class provides permutation calculations and selection operations for a given set of data elements. """ def __init__(self, datas): 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 """ 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): """ 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 """ total = 0 for i in range(1, n + 1): total += ArrangementCalculator.count(n, i) return total 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]] """ result = [] for i in range(1, len(self.datas) + 1): result.extend(self.select(i)) return result @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 """ result = 1 for i in range(2, n + 1): result *= i return result
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_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 """
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
Generates a list of arrangements by selecting m items from the internal datas. If m is not provided, selects all items.
ClassEval_3_sum
import itertools class ArrangementCalculator: """ The Arrangement class provides permutation calculations and selection operations for a given set of data elements. """ def __init__(self, datas): 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 """ 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): """ 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 """ total = 0 for i in range(1, n + 1): total += ArrangementCalculator.count(n, i) return total 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]] """ if m is None: m = len(self.datas) result = [] for permutation in itertools.permutations(self.datas, m): result.append(list(permutation)) return result @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 """ result = 1 for i in range(2, n + 1): result *= i return result
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]] """ @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 """
def select_all(self): result = [] for i in range(1, len(self.datas) + 1): result.extend(self.select(i)) return result
Generates a list of all arrangements by selecting at least 1 item and at most the number of internal datas.
ClassEval_3_sum
import itertools class ArrangementCalculator: """ The Arrangement class provides permutation calculations and selection operations for a given set of data elements. """ def __init__(self, datas): 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 """ 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): """ 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 """ total = 0 for i in range(1, n + 1): total += ArrangementCalculator.count(n, i) return total 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]] """ 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): """ 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]] """ 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 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 """
@staticmethod def factorial(n): result = 1 for i in range(2, n + 1): result *= i return result
Calculates the factorial of a given number.
ClassEval_4_sum
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): self.students = {} 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}}} """ if name in self.students: self.students[name]['courses'][course] = score 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 """ 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): """ 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'] """ 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): """ 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. """ 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): """ 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' """ 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
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_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' """
def add_student(self, name, grade, major): self.students[name] = {'name': name, 'grade': grade, 'major': major, 'courses': {}}
Add a new student into self.students dict
ClassEval_4_sum
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): 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': {}}} """ self.students[name] = {'name': name, 'grade': grade, 'major': major, 'courses': {}} 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 """ 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): """ 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'] """ 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): """ 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. """ 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): """ 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' """ 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
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 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' """
def add_course_score(self, name, course, score): if name in self.students: self.students[name]['courses'][course] = score
Add score of specific course for student in self.students
ClassEval_4_sum
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): 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': {}}} """ self.students[name] = {'name': name, 'grade': grade, 'major': major, '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}}} """ if name in self.students: self.students[name]['courses'][course] = score 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'] """ 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): """ 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. """ 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): """ 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' """ 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
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_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' """
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
Get average grade of one student.
ClassEval_4_sum
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): 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': {}}} """ self.students[name] = {'name': name, 'grade': grade, 'major': major, '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}}} """ if name in self.students: self.students[name]['courses'][course] = score 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 """ 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_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. """ 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): """ 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' """ 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
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_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' """
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
Get all students who have any score blow 60
ClassEval_4_sum
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): 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': {}}} """ self.students[name] = {'name': name, 'grade': grade, 'major': major, '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}}} """ if name in self.students: self.students[name]['courses'][course] = score 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 """ 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): """ 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'] """ 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_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' """ 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
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_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' """
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
Get the average score of a specific course.
ClassEval_4_sum
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): 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': {}}} """ self.students[name] = {'name': name, 'grade': grade, 'major': major, '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}}} """ if name in self.students: self.students[name]['courses'][course] = score 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 """ 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): """ 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'] """ 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): """ 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. """ 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
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' """
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
Calculate every student's gpa with get_gpa method, and find the student with highest gpa
ClassEval_5_sum
class AutomaticGuitarSimulator: """ This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music. """ def __init__(self, text) -> None: self.play_text = text 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 """ return "Normal Guitar Playing -- Chord: %s, Play Tune: %s" % (key, value)
class AutomaticGuitarSimulator: """ This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music. """ def __init__(self, text) -> None: """ Initialize the score to be played :param text:str, score to be played """ self.play_text = text 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 """
def interpret(self, display=False): if len(self.play_text) == 0: 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
Interpret the music score to be played
ClassEval_5_sum
class AutomaticGuitarSimulator: """ This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music. """ def __init__(self, text) -> None: 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, Chore and Tune, which are letters and numbers, respectively >>> 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'}] """ if len(self.play_text) == 0: 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)
class AutomaticGuitarSimulator: """ This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music. """ 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, Chore and Tune, which are letters and numbers, respectively >>> 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 """
def display(self, key, value): return "Normal Guitar Playing -- Chord: %s, Play Tune: %s" % (key, value)
Print out chord and play tune with following format: Normal Guitar Playing -- Chord: %s, Play Tune: %s
ClassEval_6_sum
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): self.lst = lst self.limit = limit 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] """ size, remainder = self.setNum() start = index * size + min(index, remainder) end = start + size if index + 1 <= remainder: end += 1 return self.lst[start:end]
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 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] """
def setNum(self): size = len(self.lst) // self.limit remainder = len(self.lst) % self.limit return size, remainder
Calculate the size of each block and the remainder of the division.
ClassEval_6_sum
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): 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) """ 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]
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] """
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]
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.
ClassEval_7_sum
class BalancedBrackets: """ This is a class that checks for bracket matching """ def __init__(self, expr): self.stack = [] self.left_brackets = ["(", "{", "["] self.right_brackets = [")", "}", "]"] self.expr = 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 """ 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
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 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 """
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))
Clears the expression of all characters that are not brackets.
ClassEval_7_sum
class BalancedBrackets: """ This is a class that checks for bracket matching """ def __init__(self, expr): 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 '()' """ 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
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 """
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
Checks if the expression has balanced brackets.
ClassEval_8_sum
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): self.balance = balance 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 """ 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 the account balance. """ return self.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 """ self.withdraw(amount) other_account.deposit(amount)
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 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 """
def deposit(self, amount): if amount < 0: raise ValueError("Invalid amount") self.balance += amount return self.balance
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").
ClassEval_8_sum
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): 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 """ if amount < 0: raise ValueError("Invalid amount") self.balance += amount return self.balance def view_balance(self): """ Return the account balance. """ return self.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 """ self.withdraw(amount) other_account.deposit(amount)
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 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 """
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
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.").
ClassEval_8_sum
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): 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 """ if amount < 0: raise ValueError("Invalid amount") self.balance += amount return self.balance 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 """ if amount < 0: raise ValueError("Invalid amount") if amount > self.balance: raise ValueError("Insufficient balance.") self.balance -= amount return self.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 """ self.withdraw(amount) other_account.deposit(amount)
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 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 """
def view_balance(self): return self.balance
Return the account balance.
ClassEval_8_sum
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): 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 """ if amount < 0: raise ValueError("Invalid amount") self.balance += amount return self.balance 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 """ 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 the account balance. """ return self.balance def transfer(self, other_account, amount): self.withdraw(amount) other_account.deposit(amount)
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 """
def transfer(self, other_account, amount): self.withdraw(amount) other_account.deposit(amount)
Transfers a certain amount from the current account to another account.
ClassEval_9_sum
class BigNumCalculator: """ This is a class that implements big number calculations, including adding, subtracting and multiplying. """ @staticmethod @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' """ 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): """ 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' """ 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:]))
class BigNumCalculator: """ This is a class that implements big number calculations, including adding, subtracting and multiplying. """ @staticmethod @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' """
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)
Adds two big numbers.
ClassEval_9_sum
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' """ 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 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' """ 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:]))
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 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' """
@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)
Subtracts two big numbers.
ClassEval_9_sum
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' """ 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): """ 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' """ 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:]))
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' """
@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:]))
Multiplies two big numbers.
ClassEval_10_sum
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): self.binary_string = binary_string self.clean_non_binary_chars() 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} """ 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): """ Convert the binary string to ascii string. >>> bdp = BinaryDataProcessor("0110100001100101011011000110110001101111") >>> bdp.convert_to_ascii() 'hello' """ 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): """ Convert the binary string to utf-8 string. >>> bdp = BinaryDataProcessor("0110100001100101011011000110110001101111") >>> bdp.convert_to_utf8() 'hello' """ 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')
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 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' """
def clean_non_binary_chars(self): self.binary_string = ''.join(filter(lambda x: x in '01', self.binary_string))
Clean the binary string by removing all non 0 or 1 characters.
ClassEval_10_sum
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): 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' """ self.binary_string = ''.join(filter(lambda x: x in '01', self.binary_string)) def convert_to_ascii(self): """ Convert the binary string to ascii string. >>> bdp = BinaryDataProcessor("0110100001100101011011000110110001101111") >>> bdp.convert_to_ascii() 'hello' """ 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): """ Convert the binary string to utf-8 string. >>> bdp = BinaryDataProcessor("0110100001100101011011000110110001101111") >>> bdp.convert_to_utf8() 'hello' """ 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')
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 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' """
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 }
Calculate the binary string information, including the percentage of 0 and 1, and the total length of the binary string.
ClassEval_10_sum
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): 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' """ self.binary_string = ''.join(filter(lambda x: x in '01', self.binary_string)) 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} """ 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_utf8(self): """ Convert the binary string to utf-8 string. >>> bdp = BinaryDataProcessor("0110100001100101011011000110110001101111") >>> bdp.convert_to_utf8() 'hello' """ 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')
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_utf8(self): """ Convert the binary string to utf-8 string. >>> bdp = BinaryDataProcessor("0110100001100101011011000110110001101111") >>> bdp.convert_to_utf8() 'hello' """
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')
Convert the binary string to ascii string.
ClassEval_10_sum
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): 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' """ self.binary_string = ''.join(filter(lambda x: x in '01', self.binary_string)) 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} """ 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): """ Convert the binary string to ascii string. >>> bdp = BinaryDataProcessor("0110100001100101011011000110110001101111") >>> bdp.convert_to_ascii() 'hello' """ 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')
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' """
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')
Convert the binary string to utf-8 string.
ClassEval_11_sum
class BitStatusUtil: """ This is a utility class that provides methods for manipulating and checking status using bitwise operations. """ @staticmethod @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 """ BitStatusUtil.check([states, stat]) return (states & stat) == stat @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 """ BitStatusUtil.check([states, stat]) if BitStatusUtil.has(states, stat): return states ^ stat return states @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 """ 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")
class BitStatusUtil: """ This is a utility class that provides methods for manipulating and checking status using bitwise operations. """ @staticmethod @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 """
def add(states, stat): BitStatusUtil.check([states, stat]) return states | stat
Add a status to the current status,and check the parameters wheather they are legal.
ClassEval_11_sum
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 """ BitStatusUtil.check([states, stat]) return states | stat @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 """ BitStatusUtil.check([states, stat]) if BitStatusUtil.has(states, stat): return states ^ stat return states @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 """ 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")
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 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 """
@staticmethod def has(states, stat): BitStatusUtil.check([states, stat]) return (states & stat) == stat
Check if the current status contains the specified status,and check the parameters wheather they are legal.
ClassEval_11_sum
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 """ BitStatusUtil.check([states, stat]) return states | stat @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 """ BitStatusUtil.check([states, stat]) return (states & stat) == stat @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 """ 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")
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 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 """
@staticmethod def remove(states, stat): BitStatusUtil.check([states, stat]) if BitStatusUtil.has(states, stat): return states ^ stat return states
Remove the specified status from the current status,and check the parameters wheather they are legal.
ClassEval_11_sum
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 """ BitStatusUtil.check([states, stat]) return states | stat @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 """ BitStatusUtil.check([states, stat]) return (states & stat) == stat @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 """ 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")
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 """
@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")
Check if the parameters are legal, args must be greater than or equal to 0 and must be even,if not,raise ValueError.
ClassEval_12_sum
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): self.deck = self.create_deck() self.player_hand = [] self.dealer_hand = [] 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 """ 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): """ 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' """ 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 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 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' """
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
Create a deck of 52 cards, which stores 52 rondom order poker with the Jokers removed.
ClassEval_12_sum
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): 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'] """ 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 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' """ 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 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 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' """
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
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.
ClassEval_12_sum
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): 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'] """ 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): """ 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 """ 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 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' """
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'
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.
ClassEval_13_sum
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): self.inventory = {} 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 """ 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): """ 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} """ return self.inventory 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 """ if title not in self.inventory: return 0 return self.inventory[title]
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 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 """
def add_book(self, title, quantity=1): if title in self.inventory: self.inventory[title] += quantity else: self.inventory[title] = quantity
Add one or several books to inventory which is sorted by book title.
ClassEval_13_sum
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): 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. """ if title in self.inventory: self.inventory[title] += quantity else: self.inventory[title] = quantity 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} """ return self.inventory 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 """ if title not in self.inventory: return 0 return self.inventory[title]
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 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 """
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])
Remove one or several books from inventory which is sorted by book title. Raise false while get invalid input.
ClassEval_13_sum
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): 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. """ if title in self.inventory: self.inventory[title] += quantity else: self.inventory[title] = quantity 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 """ 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_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 """ if title not in self.inventory: return 0 return self.inventory[title]
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_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 """
def view_inventory(self): return self.inventory
Get the inventory of the Book Management.
ClassEval_13_sum
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): 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. """ if title in self.inventory: self.inventory[title] += quantity else: self.inventory[title] = quantity 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 """ 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): """ 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} """ return self.inventory def view_book_quantity(self, title): if title not in self.inventory: return 0 return self.inventory[title]
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 """
def view_book_quantity(self, title): if title not in self.inventory: return 0 return self.inventory[title]
Get the quantity of a book.
ClassEval_14_sum
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): self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() self.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') """ self.cursor.execute(''' INSERT INTO books (title, author, available) VALUES (?, ?, 1) ''', (title, author)) self.connection.commit() 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) """ self.cursor.execute(''' DELETE FROM books WHERE id = ? ''', (book_id,)) self.connection.commit() 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) """ self.cursor.execute(''' UPDATE books SET available = 0 WHERE id = ? ''', (book_id,)) self.connection.commit() 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) """ self.cursor.execute(''' UPDATE books SET available = 1 WHERE id = ? ''', (book_id,)) self.connection.commit() 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)] """ self.cursor.execute(''' SELECT * FROM books ''') books = self.cursor.fetchall() return books
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 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)] """
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()
Creates the book table in the database if it does not already exist.
ClassEval_14_sum
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): 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() """ self.cursor.execute(''' CREATE TABLE IF NOT EXISTS books ( id INTEGER PRIMARY KEY, title TEXT, author TEXT, available INTEGER ) ''') self.connection.commit() 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) """ self.cursor.execute(''' DELETE FROM books WHERE id = ? ''', (book_id,)) self.connection.commit() 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) """ self.cursor.execute(''' UPDATE books SET available = 0 WHERE id = ? ''', (book_id,)) self.connection.commit() 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) """ self.cursor.execute(''' UPDATE books SET available = 1 WHERE id = ? ''', (book_id,)) self.connection.commit() 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)] """ self.cursor.execute(''' SELECT * FROM books ''') books = self.cursor.fetchall() return books
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 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)] """
def add_book(self, title, author): self.cursor.execute(''' INSERT INTO books (title, author, available) VALUES (?, ?, 1) ''', (title, author)) self.connection.commit()
Adds a book to the database with the specified title and author, setting its availability to 1 as free to borrow.
ClassEval_14_sum
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): 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() """ 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): """ 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') """ self.cursor.execute(''' INSERT INTO books (title, author, available) VALUES (?, ?, 1) ''', (title, author)) self.connection.commit() 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) """ self.cursor.execute(''' UPDATE books SET available = 0 WHERE id = ? ''', (book_id,)) self.connection.commit() 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) """ self.cursor.execute(''' UPDATE books SET available = 1 WHERE id = ? ''', (book_id,)) self.connection.commit() 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)] """ self.cursor.execute(''' SELECT * FROM books ''') books = self.cursor.fetchall() return books
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 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)] """
def remove_book(self, book_id): self.cursor.execute(''' DELETE FROM books WHERE id = ? ''', (book_id,)) self.connection.commit()
Removes a book from the database based on the given book ID.
ClassEval_14_sum
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): 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() """ 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): """ 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') """ self.cursor.execute(''' INSERT INTO books (title, author, available) VALUES (?, ?, 1) ''', (title, author)) self.connection.commit() 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) """ self.cursor.execute(''' DELETE FROM books WHERE id = ? ''', (book_id,)) self.connection.commit() 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) """ self.cursor.execute(''' UPDATE books SET available = 1 WHERE id = ? ''', (book_id,)) self.connection.commit() 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)] """ self.cursor.execute(''' SELECT * FROM books ''') books = self.cursor.fetchall() return books
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 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)] """
def borrow_book(self, book_id): self.cursor.execute(''' UPDATE books SET available = 0 WHERE id = ? ''', (book_id,)) self.connection.commit()
Marks a book as borrowed in the database based on the given book ID.
ClassEval_14_sum
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): 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() """ 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): """ 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') """ self.cursor.execute(''' INSERT INTO books (title, author, available) VALUES (?, ?, 1) ''', (title, author)) self.connection.commit() 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) """ self.cursor.execute(''' DELETE FROM books WHERE id = ? ''', (book_id,)) self.connection.commit() 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) """ self.cursor.execute(''' UPDATE books SET available = 0 WHERE id = ? ''', (book_id,)) self.connection.commit() 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)] """ self.cursor.execute(''' SELECT * FROM books ''') books = self.cursor.fetchall() return books
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 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)] """
def return_book(self, book_id): self.cursor.execute(''' UPDATE books SET available = 1 WHERE id = ? ''', (book_id,)) self.connection.commit()
Marks a book as returned in the database based on the given book ID.
ClassEval_14_sum
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): 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() """ 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): """ 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') """ self.cursor.execute(''' INSERT INTO books (title, author, available) VALUES (?, ?, 1) ''', (title, author)) self.connection.commit() 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) """ self.cursor.execute(''' DELETE FROM books WHERE id = ? ''', (book_id,)) self.connection.commit() 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) """ self.cursor.execute(''' UPDATE books SET available = 0 WHERE id = ? ''', (book_id,)) self.connection.commit() 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) """ 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 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)] """
def search_books(self): self.cursor.execute(''' SELECT * FROM books ''') books = self.cursor.fetchall() return books
Retrieves all books from the database and returns their information.
ClassEval_15_sum
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): self.text, self.pattern = text, pattern self.textLen, self.patLen = len(text), len(pattern) 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 """ 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): """ 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] """ 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
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 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] """
def match_in_pattern(self, char): for i in range(self.patLen - 1, -1, -1): if char == self.pattern[i]: return i return -1
Finds the rightmost occurrence of a character in the pattern.
ClassEval_15_sum
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): 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 """ for i in range(self.patLen - 1, -1, -1): if char == self.pattern[i]: return i return -1 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] """ 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
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 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] """
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
Determines the position of the first dismatch between the pattern and the text.
ClassEval_15_sum
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): 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 """ for i in range(self.patLen - 1, -1, -1): if char == self.pattern[i]: return i return -1 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 """ 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
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] """
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
Finds all occurrences of the pattern in the text.
ClassEval_16_sum
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): 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 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 """ precedences = { '+': 1, '-': 1, '*': 2, '/': 2, '^': 3 } return precedences.get(operator, 0) 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], ['-']) """ 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
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 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], ['-']) """
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
Calculate the value of a given expression
ClassEval_16_sum
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): 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 """ 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 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], ['-']) """ 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
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 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], ['-']) """
def precedence(self, operator): precedences = { '+': 1, '-': 1, '*': 2, '/': 2, '^': 3 } return precedences.get(operator, 0)
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 '-'
ClassEval_16_sum
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): 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 """ 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): """ 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 """ 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
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], ['-']) """
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
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
ClassEval_17_sum
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): self.events = [] 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 [] """ if event in self.events: self.events.remove(event) 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'}] """ 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): """ 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 """ 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): """ 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))] """ 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): """ 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'}] """ 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 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 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'}] """
def add_event(self, event): self.events.append(event)
Add an event to the calendar.
ClassEval_17_sum
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): 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'}] """ self.events.append(event) 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'}] """ 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): """ 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 """ 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): """ 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))] """ 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): """ 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'}] """ 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 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 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'}] """
def remove_event(self, event): if event in self.events: self.events.remove(event)
Remove an event from the calendar.
ClassEval_17_sum
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): 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'}] """ self.events.append(event) 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 [] """ if event in self.events: self.events.remove(event) 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 """ 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): """ 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))] """ 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): """ 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'}] """ 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 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 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'}] """
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
Get all events on a given date.
ClassEval_17_sum
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): 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'}] """ self.events.append(event) 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 [] """ if event in self.events: self.events.remove(event) 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'}] """ events_on_date = [] for event in self.events: if event['date'].date() == date.date(): events_on_date.append(event) return events_on_date 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))] """ 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): """ 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'}] """ 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 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 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'}] """
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
Check if the calendar is available for a given time slot.
ClassEval_17_sum
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): 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'}] """ self.events.append(event) 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 [] """ if event in self.events: self.events.remove(event) 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'}] """ 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): """ 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 """ for event in self.events: if start_time < event['end_time'] and end_time > event['start_time']: return False return True 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'}] """ 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 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_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'}] """
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
Get all available time slots on a given date.
ClassEval_17_sum
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): 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'}] """ self.events.append(event) 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 [] """ if event in self.events: self.events.remove(event) 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'}] """ 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): """ 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 """ 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): """ 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))] """ 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 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'}] """
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
Get the next n upcoming events from a given date.
ClassEval_18_sum
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): self._data = {} 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' """ self._data[self._convert_key(key)] = value 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 """ del self._data[self._convert_key(key)] 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> """ return iter(self._data) 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 """ return len(self._data) 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' """ if isinstance(key, str): return self._to_camel_case(key) return key @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' """ parts = key.split('_') return parts[0] + ''.join(part.title() for part in parts[1:])
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 __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' """
def __getitem__(self, key): return self._data[self._convert_key(key)]
Return the value corresponding to the key
ClassEval_18_sum
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): 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' """ return self._data[self._convert_key(key)] 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 """ del self._data[self._convert_key(key)] 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> """ return iter(self._data) 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 """ return len(self._data) 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' """ if isinstance(key, str): return self._to_camel_case(key) return key @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' """ parts = key.split('_') return parts[0] + ''.join(part.title() for part in parts[1:])
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 __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' """
def __setitem__(self, key, value): self._data[self._convert_key(key)] = value
Set the value corresponding to the key to the specified value
ClassEval_18_sum
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): 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' """ return self._data[self._convert_key(key)] 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' """ self._data[self._convert_key(key)] = value 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> """ return iter(self._data) 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 """ return len(self._data) 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' """ if isinstance(key, str): return self._to_camel_case(key) return key @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' """ parts = key.split('_') return parts[0] + ''.join(part.title() for part in parts[1:])
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 __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' """
def __delitem__(self, key): del self._data[self._convert_key(key)]
Delete the value corresponding to the key
ClassEval_18_sum
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): 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' """ return self._data[self._convert_key(key)] 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' """ self._data[self._convert_key(key)] = value 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 """ del self._data[self._convert_key(key)] 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 """ return len(self._data) 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' """ if isinstance(key, str): return self._to_camel_case(key) return key @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' """ parts = key.split('_') return parts[0] + ''.join(part.title() for part in parts[1:])
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 __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' """
def __iter__(self): return iter(self._data)
Returning Iterateable Objects with Own Data
ClassEval_18_sum
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): 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' """ return self._data[self._convert_key(key)] 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' """ self._data[self._convert_key(key)] = value 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 """ del self._data[self._convert_key(key)] 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> """ return iter(self._data) 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' """ if isinstance(key, str): return self._to_camel_case(key) return key @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' """ parts = key.split('_') return parts[0] + ''.join(part.title() for part in parts[1:])
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 _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' """
def __len__(self): return len(self._data)
Returns the length of the own data
ClassEval_18_sum
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): 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' """ return self._data[self._convert_key(key)] 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' """ self._data[self._convert_key(key)] = value 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 """ del self._data[self._convert_key(key)] 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> """ return iter(self._data) 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 """ return len(self._data) @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' """ parts = key.split('_') return parts[0] + ''.join(part.title() for part in parts[1:])
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 """ @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' """
def _convert_key(self, key): if isinstance(key, str): return self._to_camel_case(key) return key
convert key string into camel case
ClassEval_18_sum
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): 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' """ return self._data[self._convert_key(key)] 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' """ self._data[self._convert_key(key)] = value 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 """ del self._data[self._convert_key(key)] 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> """ return iter(self._data) 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 """ return len(self._data) 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' """ 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:])
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' """
@staticmethod def _to_camel_case(key): parts = key.split('_') return parts[0] + ''.join(part.title() for part in parts[1:])
convert key string into camel case
ClassEval_19_sum
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): self.n = n self.primes = self.generate_primes() 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] """ return self.primes
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 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] """
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
Generate prime numbers up to the specified limit using the Chandrasekhar sieve algorithm.
ClassEval_19_sum
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): 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] """ 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
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] """
def get_primes(self): return self.primes
Get the list of generated prime numbers.
ClassEval_20_sum
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): self.users = {} 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 """ if username in self.users: del self.users[username] return True else: return 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 """ 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): """ 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') [] """ if username not in self.users: return [] return self.users[username]
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 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') [] """
def add_user(self, username): if username in self.users: return False else: self.users[username] = [] return True
Add a new user to the Chat.
ClassEval_20_sum
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): 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 """ if username in self.users: return False else: self.users[username] = [] return True 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 """ 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): """ 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') [] """ if username not in self.users: return [] return self.users[username]
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 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') [] """
def remove_user(self, username): if username in self.users: del self.users[username] return True else: return False
Remove a user from the Chat.
ClassEval_20_sum
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): 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 """ if username in self.users: return False else: self.users[username] = [] return True 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 """ if username in self.users: del self.users[username] return True else: return 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') [] """ if username not in self.users: return [] return self.users[username]
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 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') [] """
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
Send a message from a user to another user.
ClassEval_20_sum
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): 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 """ if username in self.users: return False else: self.users[username] = [] return True 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 """ if username in self.users: del self.users[username] return True else: return 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 """ 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 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') [] """
def get_messages(self, username): if username not in self.users: return [] return self.users[username]
Get all the messages of a user from the Chat.
ClassEval_21_sum
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): self.id = id self.courses = [] 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'}) """ if course in self.courses: self.courses.remove(course) 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 """ 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): """ 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 """ 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 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 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 """
def add_course(self, course): if course not in self.courses: self.courses.append(course)
Add course to self.courses list if the course wasn't in it.
ClassEval_21_sum
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): 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'}) """ if course not in self.courses: self.courses.append(course) 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 """ 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): """ 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 """ 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 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 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 """
def remove_course(self, course): if course in self.courses: self.courses.remove(course)
Remove course from self.courses list if the course was in it.
ClassEval_21_sum
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): 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'}) """ if course not in self.courses: self.courses.append(course) 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'}) """ if course in self.courses: self.courses.remove(course) 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 """ 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 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 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 """
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
change the time format as '%H:%M' and check the time is free or not in the classroom.
ClassEval_21_sum
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): 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'}) """ if course not in self.courses: self.courses.append(course) 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'}) """ if course in self.courses: self.courses.remove(course) 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 """ 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 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 """
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
Before adding a new course, check if the new course time conflicts with any other course.
ClassEval_22_sum
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): self.students = [] self.students_registration_classes = {} 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"] 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): """ 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"] """ student_list = [] for student in self.students: if student["major"] == major: student_list.append(student["name"]) return student_list 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"] """ 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): """ 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" """ 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
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_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" """
def register_student(self, student): if student in self.students: return 0 else: self.students.append(student) return 1
register a student to the system, add the student to the students list, if the student is already registered, return 0, else return 1
ClassEval_22_sum
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): 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 """ if student in self.students: return 0 else: self.students.append(student) return 1 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"] """ student_list = [] for student in self.students: if student["major"] == major: student_list.append(student["name"]) return student_list 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"] """ 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): """ 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" """ 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
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 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" """
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]
register a class to the student.
ClassEval_22_sum
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): 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 """ if student in self.students: return 0 else: self.students.append(student) 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"] 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_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"] """ 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): """ 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" """ 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
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_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" """
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
get all students in the major
ClassEval_22_sum
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): 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 """ if student in self.students: return 0 else: self.students.append(student) 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"] 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): """ 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"] """ student_list = [] for student in self.students: if student["major"] == major: student_list.append(student["name"]) return student_list 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" """ 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
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_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" """
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
get all majors in the system
ClassEval_22_sum
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): 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 """ if student in self.students: return 0 else: self.students.append(student) 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"] 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): """ 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"] """ student_list = [] for student in self.students: if student["major"] == major: student_list.append(student["name"]) return student_list 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"] """ 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
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" """
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
get the class with the highest enrollment in the major.
ClassEval_23_sum
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]): self.datas = datas @staticmethod @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 """ 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]]: """ 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']] """ int) -> List[List[str]]: result = [] self._select(0, [None] * m, 0, result) return result 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']] """ 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]]): """ 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']] """ 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 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 @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']] """
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))
Calculate the number of combinations for a specific count.
ClassEval_23_sum
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]): 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 """ int, m: int) -> int: if m == 0 or n == m: return 1 return math.factorial(n) // (math.factorial(n - m) * math.factorial(m)) 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']] """ int) -> List[List[str]]: result = [] self._select(0, [None] * m, 0, result) return result 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']] """ 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]]): """ 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']] """ 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 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 """ 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']] """
@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")
Calculate the number of all possible combinations.
ClassEval_23_sum
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]): 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 """ 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: """ 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 """ int) -> int: if n < 0 or n > 63: return False return (1 << n) - 1 if n != 63 else float("inf") 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']] """ 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]]): """ 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']] """ 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 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_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']] """
def select(self, m: int) -> List[List[str]]: result = [] self._select(0, [None] * m, 0, result) return result
Generate combinations with a specified number of elements.
ClassEval_23_sum
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]): 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 """ 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: """ 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 """ 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]]: """ 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']] """ int) -> List[List[str]]: result = [] self._select(0, [None] * m, 0, result) return result 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']] """ 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 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(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']] """
def select_all(self) -> List[List[str]]: result = [] for i in range(1, len(self.datas) + 1): result.extend(self.select(i)) return result
Generate all possible combinations of selecting elements from the given data list,and it uses the select method.
ClassEval_23_sum
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]): 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 """ 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: """ 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 """ 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]]: """ 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']] """ int) -> List[List[str]]: result = [] self._select(0, [None] * m, 0, result) return result 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']] """ 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 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']] """
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)
Generate combinations with a specified number of elements by recursion.
ClassEval_24_sum
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): real = c1.real + c2.real imaginary = c1.imag + c2.imag answer = complex(real, imaginary) return answer @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) """ real = c1.real - c2.real imaginary = c1.imag - c2.imag return complex(real, imaginary) @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) """ 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): """ 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) """ 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)
class ComplexCalculator: """ This is a class that implements addition, subtraction, multiplication, and division operations for complex numbers. """ def __init__(self): pass @staticmethod @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) """
def add(c1, c2): real = c1.real + c2.real imaginary = c1.imag + c2.imag answer = complex(real, imaginary) return answer
Adds two complex numbers.
ClassEval_24_sum
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) """ 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): """ 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) """ 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): """ 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) """ 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)
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 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) """
@staticmethod def subtract(c1, c2): real = c1.real - c2.real imaginary = c1.imag - c2.imag return complex(real, imaginary)
Subtracts two complex numbers.
ClassEval_24_sum
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) """ real = c1.real + c2.real imaginary = c1.imag + c2.imag answer = complex(real, imaginary) return answer @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) """ 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): """ 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) """ 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)
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 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) """
@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)
Multiplies two complex numbers.