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.
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card