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_76_sum
class SignInSystem: """ This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users. """ def __init__(self): self.users = {} def add_user(self, username): """ Add a user to the sign-in system if the user wasn't in the self.users. And the initial state is False. :param username: str, the username to be added. :return: bool, True if the user is added successfully, False if the user already exists. >>> signInSystem.add_user("mike") True >>> signInSystem.add_user("mike") False """ if username in self.users: return False else: self.users[username] = False return True def check_sign_in(self, username): """ Check if a user is signed in. :param username: str, the username to be checked. :return: bool, True if the user is signed in, False if the user does not exist or is not signed in. >>> signInSystem.check_sign_in("jack") False >>> signInSystem.add_user("jack") >>> signInSystem.check_sign_in("jack") >>> signInSystem.sign_in("jack") >>> signInSystem.check_sign_in("jack") True """ if username not in self.users: return False else: if self.users[username]: return True else: return False def all_signed_in(self): """ Check if all users are signed in. :return: bool, True if all users are signed in, False otherwise. >>> signInSystem.add_user("jack") True >>> signInSystem.sign_in("jack") >>> signInSystem.all_signed_in() True """ if all(self.users.values()): return True else: return False def all_not_signed_in(self): """ Get a list of usernames that are not signed in. :return: list[str], a list of usernames that are not signed in. >>> signInSystem = SignInSystem() >>> signInSystem.add_user("a") True >>> signInSystem.add_user("b") True >>> signInSystem.all_not_signed_in() ['a', 'b'] """ not_signed_in_users = [] for username, signed_in in self.users.items(): if not signed_in: not_signed_in_users.append(username) return not_signed_in_users
class SignInSystem: """ This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users. """ def __init__(self): """ Initialize the sign-in system. """ self.users = {} def add_user(self, username): """ Add a user to the sign-in system if the user wasn't in the self.users. And the initial state is False. :param username: str, the username to be added. :return: bool, True if the user is added successfully, False if the user already exists. >>> signInSystem.add_user("mike") True >>> signInSystem.add_user("mike") False """ def check_sign_in(self, username): """ Check if a user is signed in. :param username: str, the username to be checked. :return: bool, True if the user is signed in, False if the user does not exist or is not signed in. >>> signInSystem.check_sign_in("jack") False >>> signInSystem.add_user("jack") >>> signInSystem.check_sign_in("jack") >>> signInSystem.sign_in("jack") >>> signInSystem.check_sign_in("jack") True """ def all_signed_in(self): """ Check if all users are signed in. :return: bool, True if all users are signed in, False otherwise. >>> signInSystem.add_user("jack") True >>> signInSystem.sign_in("jack") >>> signInSystem.all_signed_in() True """ def all_not_signed_in(self): """ Get a list of usernames that are not signed in. :return: list[str], a list of usernames that are not signed in. >>> signInSystem = SignInSystem() >>> signInSystem.add_user("a") True >>> signInSystem.add_user("b") True >>> signInSystem.all_not_signed_in() ['a', 'b'] """
def sign_in(self, username): if username not in self.users: return False else: self.users[username] = True return True
Sign in a user if the user was in the self.users and change the state to True.
ClassEval_76_sum
class SignInSystem: """ This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users. """ def __init__(self): self.users = {} def add_user(self, username): """ Add a user to the sign-in system if the user wasn't in the self.users. And the initial state is False. :param username: str, the username to be added. :return: bool, True if the user is added successfully, False if the user already exists. >>> signInSystem.add_user("mike") True >>> signInSystem.add_user("mike") False """ if username in self.users: return False else: self.users[username] = False return True def sign_in(self, username): """ Sign in a user if the user was in the self.users and change the state to True. :param username: str, the username to be signed in. :return: bool, True if the user is signed in successfully, False if the user does not exist. >>> signInSystem.sign_in("mike") True >>> signInSystem.sign_in("mik") False """ if username not in self.users: return False else: self.users[username] = True return True def all_signed_in(self): """ Check if all users are signed in. :return: bool, True if all users are signed in, False otherwise. >>> signInSystem.add_user("jack") True >>> signInSystem.sign_in("jack") >>> signInSystem.all_signed_in() True """ if all(self.users.values()): return True else: return False def all_not_signed_in(self): """ Get a list of usernames that are not signed in. :return: list[str], a list of usernames that are not signed in. >>> signInSystem = SignInSystem() >>> signInSystem.add_user("a") True >>> signInSystem.add_user("b") True >>> signInSystem.all_not_signed_in() ['a', 'b'] """ not_signed_in_users = [] for username, signed_in in self.users.items(): if not signed_in: not_signed_in_users.append(username) return not_signed_in_users
class SignInSystem: """ This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users. """ def __init__(self): """ Initialize the sign-in system. """ self.users = {} def add_user(self, username): """ Add a user to the sign-in system if the user wasn't in the self.users. And the initial state is False. :param username: str, the username to be added. :return: bool, True if the user is added successfully, False if the user already exists. >>> signInSystem.add_user("mike") True >>> signInSystem.add_user("mike") False """ def sign_in(self, username): """ Sign in a user if the user was in the self.users and change the state to True. :param username: str, the username to be signed in. :return: bool, True if the user is signed in successfully, False if the user does not exist. >>> signInSystem.sign_in("mike") True >>> signInSystem.sign_in("mik") False """ def all_signed_in(self): """ Check if all users are signed in. :return: bool, True if all users are signed in, False otherwise. >>> signInSystem.add_user("jack") True >>> signInSystem.sign_in("jack") >>> signInSystem.all_signed_in() True """ def all_not_signed_in(self): """ Get a list of usernames that are not signed in. :return: list[str], a list of usernames that are not signed in. >>> signInSystem = SignInSystem() >>> signInSystem.add_user("a") True >>> signInSystem.add_user("b") True >>> signInSystem.all_not_signed_in() ['a', 'b'] """
def check_sign_in(self, username): if username not in self.users: return False else: if self.users[username]: return True else: return False
Check if a user is signed in.
ClassEval_76_sum
class SignInSystem: """ This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users. """ def __init__(self): self.users = {} def add_user(self, username): """ Add a user to the sign-in system if the user wasn't in the self.users. And the initial state is False. :param username: str, the username to be added. :return: bool, True if the user is added successfully, False if the user already exists. >>> signInSystem.add_user("mike") True >>> signInSystem.add_user("mike") False """ if username in self.users: return False else: self.users[username] = False return True def sign_in(self, username): """ Sign in a user if the user was in the self.users and change the state to True. :param username: str, the username to be signed in. :return: bool, True if the user is signed in successfully, False if the user does not exist. >>> signInSystem.sign_in("mike") True >>> signInSystem.sign_in("mik") False """ if username not in self.users: return False else: self.users[username] = True return True def check_sign_in(self, username): """ Check if a user is signed in. :param username: str, the username to be checked. :return: bool, True if the user is signed in, False if the user does not exist or is not signed in. >>> signInSystem.check_sign_in("jack") False >>> signInSystem.add_user("jack") >>> signInSystem.check_sign_in("jack") >>> signInSystem.sign_in("jack") >>> signInSystem.check_sign_in("jack") True """ if username not in self.users: return False else: if self.users[username]: return True else: return False def all_not_signed_in(self): """ Get a list of usernames that are not signed in. :return: list[str], a list of usernames that are not signed in. >>> signInSystem = SignInSystem() >>> signInSystem.add_user("a") True >>> signInSystem.add_user("b") True >>> signInSystem.all_not_signed_in() ['a', 'b'] """ not_signed_in_users = [] for username, signed_in in self.users.items(): if not signed_in: not_signed_in_users.append(username) return not_signed_in_users
class SignInSystem: """ This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users. """ def __init__(self): """ Initialize the sign-in system. """ self.users = {} def add_user(self, username): """ Add a user to the sign-in system if the user wasn't in the self.users. And the initial state is False. :param username: str, the username to be added. :return: bool, True if the user is added successfully, False if the user already exists. >>> signInSystem.add_user("mike") True >>> signInSystem.add_user("mike") False """ def sign_in(self, username): """ Sign in a user if the user was in the self.users and change the state to True. :param username: str, the username to be signed in. :return: bool, True if the user is signed in successfully, False if the user does not exist. >>> signInSystem.sign_in("mike") True >>> signInSystem.sign_in("mik") False """ def check_sign_in(self, username): """ Check if a user is signed in. :param username: str, the username to be checked. :return: bool, True if the user is signed in, False if the user does not exist or is not signed in. >>> signInSystem.check_sign_in("jack") False >>> signInSystem.add_user("jack") >>> signInSystem.check_sign_in("jack") >>> signInSystem.sign_in("jack") >>> signInSystem.check_sign_in("jack") True """ def all_not_signed_in(self): """ Get a list of usernames that are not signed in. :return: list[str], a list of usernames that are not signed in. >>> signInSystem = SignInSystem() >>> signInSystem.add_user("a") True >>> signInSystem.add_user("b") True >>> signInSystem.all_not_signed_in() ['a', 'b'] """
def all_signed_in(self): if all(self.users.values()): return True else: return False
Check if all users are signed in.
ClassEval_76_sum
class SignInSystem: """ This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users. """ def __init__(self): self.users = {} def add_user(self, username): """ Add a user to the sign-in system if the user wasn't in the self.users. And the initial state is False. :param username: str, the username to be added. :return: bool, True if the user is added successfully, False if the user already exists. >>> signInSystem.add_user("mike") True >>> signInSystem.add_user("mike") False """ if username in self.users: return False else: self.users[username] = False return True def sign_in(self, username): """ Sign in a user if the user was in the self.users and change the state to True. :param username: str, the username to be signed in. :return: bool, True if the user is signed in successfully, False if the user does not exist. >>> signInSystem.sign_in("mike") True >>> signInSystem.sign_in("mik") False """ if username not in self.users: return False else: self.users[username] = True return True def check_sign_in(self, username): """ Check if a user is signed in. :param username: str, the username to be checked. :return: bool, True if the user is signed in, False if the user does not exist or is not signed in. >>> signInSystem.check_sign_in("jack") False >>> signInSystem.add_user("jack") >>> signInSystem.check_sign_in("jack") >>> signInSystem.sign_in("jack") >>> signInSystem.check_sign_in("jack") True """ if username not in self.users: return False else: if self.users[username]: return True else: return False def all_signed_in(self): """ Check if all users are signed in. :return: bool, True if all users are signed in, False otherwise. >>> signInSystem.add_user("jack") True >>> signInSystem.sign_in("jack") >>> signInSystem.all_signed_in() True """ if all(self.users.values()): return True else: return False def all_not_signed_in(self): not_signed_in_users = [] for username, signed_in in self.users.items(): if not signed_in: not_signed_in_users.append(username) return not_signed_in_users
class SignInSystem: """ This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users. """ def __init__(self): """ Initialize the sign-in system. """ self.users = {} def add_user(self, username): """ Add a user to the sign-in system if the user wasn't in the self.users. And the initial state is False. :param username: str, the username to be added. :return: bool, True if the user is added successfully, False if the user already exists. >>> signInSystem.add_user("mike") True >>> signInSystem.add_user("mike") False """ def sign_in(self, username): """ Sign in a user if the user was in the self.users and change the state to True. :param username: str, the username to be signed in. :return: bool, True if the user is signed in successfully, False if the user does not exist. >>> signInSystem.sign_in("mike") True >>> signInSystem.sign_in("mik") False """ def check_sign_in(self, username): """ Check if a user is signed in. :param username: str, the username to be checked. :return: bool, True if the user is signed in, False if the user does not exist or is not signed in. >>> signInSystem.check_sign_in("jack") False >>> signInSystem.add_user("jack") >>> signInSystem.check_sign_in("jack") >>> signInSystem.sign_in("jack") >>> signInSystem.check_sign_in("jack") True """ def all_signed_in(self): """ Check if all users are signed in. :return: bool, True if all users are signed in, False otherwise. >>> signInSystem.add_user("jack") True >>> signInSystem.sign_in("jack") >>> signInSystem.all_signed_in() True """ def all_not_signed_in(self): """ Get a list of usernames that are not signed in. :return: list[str], a list of usernames that are not signed in. >>> signInSystem = SignInSystem() >>> signInSystem.add_user("a") True >>> signInSystem.add_user("b") True >>> signInSystem.all_not_signed_in() ['a', 'b'] """
def all_not_signed_in(self): not_signed_in_users = [] for username, signed_in in self.users.items(): if not signed_in: not_signed_in_users.append(username) return not_signed_in_users
Get a list of usernames that are not signed in.
ClassEval_77_sum
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): self.length = 1 self.SCREEN_WIDTH = SCREEN_WIDTH self.SCREEN_HEIGHT = SCREEN_HEIGHT self.BLOCK_SIZE = BLOCK_SIZE self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))] self.score = 0 self.food_position = food_position def random_food_position(self): """ Randomly generate a new food position, but don't place it on the snake. :return: None, Change the food position """ while self.food_position in self.positions: self.food_position = (random.randint(0, self.SCREEN_WIDTH // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE, random.randint(0, self.SCREEN_HEIGHT // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE) def reset(self): """ Reset the snake to its initial state. Set the length to 1, the snake head position to ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2)), the score to 0, and randomly generate new food position. :return: None >>> snake = Snake(100, 100, 1, (51, 51)) >>> snake.reset() self.length = 1 self.positions = [(50, 50)] self.score = 0 self.random_food_position() """ self.length = 1 self.positions = [((self.SCREEN_WIDTH / 2), (self.SCREEN_HEIGHT / 2))] self.score = 0 self.random_food_position() def eat_food(self): """ Increase the length of the snake by 1 and increase the score by 100. Randomly generate a new food position, but don't place it on the snake. :return: None >>> snake = Snake(100, 100, 1, (51, 51)) >>> snake.move((1,1)) >>> snake.eat_food() self.length = 2 self.score = 10 """ self.length += 1 self.score += 100 self.random_food_position()
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): """ Initialize the length of the snake, screen width, screen height, block size, snake head position, score, and food position. :param SCREEN_WIDTH: int :param SCREEN_HEIGHT: int :param BLOCK_SIZE: int, Size of moving units :param food_position: tuple, representing the position(x, y) of food. """ self.length = 1 self.SCREEN_WIDTH = SCREEN_WIDTH self.SCREEN_HEIGHT = SCREEN_HEIGHT self.BLOCK_SIZE = BLOCK_SIZE self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))] self.score = 0 self.food_position = food_position def random_food_position(self): """ Randomly generate a new food position, but don't place it on the snake. :return: None, Change the food position """ def reset(self): """ Reset the snake to its initial state. Set the length to 1, the snake head position to ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2)), the score to 0, and randomly generate new food position. :return: None >>> snake = Snake(100, 100, 1, (51, 51)) >>> snake.reset() self.length = 1 self.positions = [(50, 50)] self.score = 0 self.random_food_position() """ def eat_food(self): """ Increase the length of the snake by 1 and increase the score by 100. Randomly generate a new food position, but don't place it on the snake. :return: None >>> snake = Snake(100, 100, 1, (51, 51)) >>> snake.move((1,1)) >>> snake.eat_food() self.length = 2 self.score = 10 """
def move(self, direction): cur = self.positions[0] x, y = direction new = ( ((cur[0] + (x * self.BLOCK_SIZE)) % self.SCREEN_WIDTH), (cur[1] + (y * self.BLOCK_SIZE)) % self.SCREEN_HEIGHT, ) if new == self.food_position: self.eat_food() if len(self.positions) > 2 and new in self.positions[2:]: self.reset() else: self.positions.insert(0, new) if len(self.positions) > self.length: self.positions.pop()
Move the snake in the specified direction. If the new position of the snake's head is equal to the position of the food, then eat the food; If the position of the snake's head is equal to the position of its body, then start over, otherwise its own length plus one.
ClassEval_77_sum
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): self.length = 1 self.SCREEN_WIDTH = SCREEN_WIDTH self.SCREEN_HEIGHT = SCREEN_HEIGHT self.BLOCK_SIZE = BLOCK_SIZE self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))] self.score = 0 self.food_position = food_position def move(self, direction): """ Move the snake in the specified direction. If the new position of the snake's head is equal to the position of the food, then eat the food; If the position of the snake's head is equal to the position of its body, then start over, otherwise its own length plus one. :param direction: tuple, representing the direction of movement (x, y). :return: None >>> snake.move((1,1)) self.length = 1 self.positions = [(51, 51), (50, 50)] self.score = 10 """ cur = self.positions[0] x, y = direction new = ( ((cur[0] + (x * self.BLOCK_SIZE)) % self.SCREEN_WIDTH), (cur[1] + (y * self.BLOCK_SIZE)) % self.SCREEN_HEIGHT, ) if new == self.food_position: self.eat_food() if len(self.positions) > 2 and new in self.positions[2:]: self.reset() else: self.positions.insert(0, new) if len(self.positions) > self.length: self.positions.pop() def reset(self): """ Reset the snake to its initial state. Set the length to 1, the snake head position to ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2)), the score to 0, and randomly generate new food position. :return: None >>> snake = Snake(100, 100, 1, (51, 51)) >>> snake.reset() self.length = 1 self.positions = [(50, 50)] self.score = 0 self.random_food_position() """ self.length = 1 self.positions = [((self.SCREEN_WIDTH / 2), (self.SCREEN_HEIGHT / 2))] self.score = 0 self.random_food_position() def eat_food(self): """ Increase the length of the snake by 1 and increase the score by 100. Randomly generate a new food position, but don't place it on the snake. :return: None >>> snake = Snake(100, 100, 1, (51, 51)) >>> snake.move((1,1)) >>> snake.eat_food() self.length = 2 self.score = 10 """ self.length += 1 self.score += 100 self.random_food_position()
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): """ Initialize the length of the snake, screen width, screen height, block size, snake head position, score, and food position. :param SCREEN_WIDTH: int :param SCREEN_HEIGHT: int :param BLOCK_SIZE: int, Size of moving units :param food_position: tuple, representing the position(x, y) of food. """ self.length = 1 self.SCREEN_WIDTH = SCREEN_WIDTH self.SCREEN_HEIGHT = SCREEN_HEIGHT self.BLOCK_SIZE = BLOCK_SIZE self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))] self.score = 0 self.food_position = food_position def move(self, direction): """ Move the snake in the specified direction. If the new position of the snake's head is equal to the position of the food, then eat the food; If the position of the snake's head is equal to the position of its body, then start over, otherwise its own length plus one. :param direction: tuple, representing the direction of movement (x, y). :return: None >>> snake.move((1,1)) self.length = 1 self.positions = [(51, 51), (50, 50)] self.score = 10 """ def reset(self): """ Reset the snake to its initial state. Set the length to 1, the snake head position to ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2)), the score to 0, and randomly generate new food position. :return: None >>> snake = Snake(100, 100, 1, (51, 51)) >>> snake.reset() self.length = 1 self.positions = [(50, 50)] self.score = 0 self.random_food_position() """ def eat_food(self): """ Increase the length of the snake by 1 and increase the score by 100. Randomly generate a new food position, but don't place it on the snake. :return: None >>> snake = Snake(100, 100, 1, (51, 51)) >>> snake.move((1,1)) >>> snake.eat_food() self.length = 2 self.score = 10 """
def random_food_position(self): while self.food_position in self.positions: self.food_position = (random.randint(0, self.SCREEN_WIDTH // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE, random.randint(0, self.SCREEN_HEIGHT // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE)
Randomly generate a new food position, but don't place it on the snake.
ClassEval_77_sum
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): self.length = 1 self.SCREEN_WIDTH = SCREEN_WIDTH self.SCREEN_HEIGHT = SCREEN_HEIGHT self.BLOCK_SIZE = BLOCK_SIZE self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))] self.score = 0 self.food_position = food_position def move(self, direction): """ Move the snake in the specified direction. If the new position of the snake's head is equal to the position of the food, then eat the food; If the position of the snake's head is equal to the position of its body, then start over, otherwise its own length plus one. :param direction: tuple, representing the direction of movement (x, y). :return: None >>> snake.move((1,1)) self.length = 1 self.positions = [(51, 51), (50, 50)] self.score = 10 """ cur = self.positions[0] x, y = direction new = ( ((cur[0] + (x * self.BLOCK_SIZE)) % self.SCREEN_WIDTH), (cur[1] + (y * self.BLOCK_SIZE)) % self.SCREEN_HEIGHT, ) if new == self.food_position: self.eat_food() if len(self.positions) > 2 and new in self.positions[2:]: self.reset() else: self.positions.insert(0, new) if len(self.positions) > self.length: self.positions.pop() def random_food_position(self): """ Randomly generate a new food position, but don't place it on the snake. :return: None, Change the food position """ while self.food_position in self.positions: self.food_position = (random.randint(0, self.SCREEN_WIDTH // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE, random.randint(0, self.SCREEN_HEIGHT // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE) def eat_food(self): """ Increase the length of the snake by 1 and increase the score by 100. Randomly generate a new food position, but don't place it on the snake. :return: None >>> snake = Snake(100, 100, 1, (51, 51)) >>> snake.move((1,1)) >>> snake.eat_food() self.length = 2 self.score = 10 """ self.length += 1 self.score += 100 self.random_food_position()
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): """ Initialize the length of the snake, screen width, screen height, block size, snake head position, score, and food position. :param SCREEN_WIDTH: int :param SCREEN_HEIGHT: int :param BLOCK_SIZE: int, Size of moving units :param food_position: tuple, representing the position(x, y) of food. """ self.length = 1 self.SCREEN_WIDTH = SCREEN_WIDTH self.SCREEN_HEIGHT = SCREEN_HEIGHT self.BLOCK_SIZE = BLOCK_SIZE self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))] self.score = 0 self.food_position = food_position def move(self, direction): """ Move the snake in the specified direction. If the new position of the snake's head is equal to the position of the food, then eat the food; If the position of the snake's head is equal to the position of its body, then start over, otherwise its own length plus one. :param direction: tuple, representing the direction of movement (x, y). :return: None >>> snake.move((1,1)) self.length = 1 self.positions = [(51, 51), (50, 50)] self.score = 10 """ def random_food_position(self): """ Randomly generate a new food position, but don't place it on the snake. :return: None, Change the food position """ def eat_food(self): """ Increase the length of the snake by 1 and increase the score by 100. Randomly generate a new food position, but don't place it on the snake. :return: None >>> snake = Snake(100, 100, 1, (51, 51)) >>> snake.move((1,1)) >>> snake.eat_food() self.length = 2 self.score = 10 """
def reset(self): self.length = 1 self.positions = [((self.SCREEN_WIDTH / 2), (self.SCREEN_HEIGHT / 2))] self.score = 0 self.random_food_position()
Reset the snake to its initial state. Set the length to 1, the snake head position to ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2)), the score to 0, and randomly generate new food position.
ClassEval_77_sum
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): self.length = 1 self.SCREEN_WIDTH = SCREEN_WIDTH self.SCREEN_HEIGHT = SCREEN_HEIGHT self.BLOCK_SIZE = BLOCK_SIZE self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))] self.score = 0 self.food_position = food_position def move(self, direction): """ Move the snake in the specified direction. If the new position of the snake's head is equal to the position of the food, then eat the food; If the position of the snake's head is equal to the position of its body, then start over, otherwise its own length plus one. :param direction: tuple, representing the direction of movement (x, y). :return: None >>> snake.move((1,1)) self.length = 1 self.positions = [(51, 51), (50, 50)] self.score = 10 """ cur = self.positions[0] x, y = direction new = ( ((cur[0] + (x * self.BLOCK_SIZE)) % self.SCREEN_WIDTH), (cur[1] + (y * self.BLOCK_SIZE)) % self.SCREEN_HEIGHT, ) if new == self.food_position: self.eat_food() if len(self.positions) > 2 and new in self.positions[2:]: self.reset() else: self.positions.insert(0, new) if len(self.positions) > self.length: self.positions.pop() def random_food_position(self): """ Randomly generate a new food position, but don't place it on the snake. :return: None, Change the food position """ while self.food_position in self.positions: self.food_position = (random.randint(0, self.SCREEN_WIDTH // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE, random.randint(0, self.SCREEN_HEIGHT // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE) def reset(self): """ Reset the snake to its initial state. Set the length to 1, the snake head position to ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2)), the score to 0, and randomly generate new food position. :return: None >>> snake = Snake(100, 100, 1, (51, 51)) >>> snake.reset() self.length = 1 self.positions = [(50, 50)] self.score = 0 self.random_food_position() """ self.length = 1 self.positions = [((self.SCREEN_WIDTH / 2), (self.SCREEN_HEIGHT / 2))] self.score = 0 self.random_food_position() def eat_food(self): self.length += 1 self.score += 100 self.random_food_position()
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): """ Initialize the length of the snake, screen width, screen height, block size, snake head position, score, and food position. :param SCREEN_WIDTH: int :param SCREEN_HEIGHT: int :param BLOCK_SIZE: int, Size of moving units :param food_position: tuple, representing the position(x, y) of food. """ self.length = 1 self.SCREEN_WIDTH = SCREEN_WIDTH self.SCREEN_HEIGHT = SCREEN_HEIGHT self.BLOCK_SIZE = BLOCK_SIZE self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))] self.score = 0 self.food_position = food_position def move(self, direction): """ Move the snake in the specified direction. If the new position of the snake's head is equal to the position of the food, then eat the food; If the position of the snake's head is equal to the position of its body, then start over, otherwise its own length plus one. :param direction: tuple, representing the direction of movement (x, y). :return: None >>> snake.move((1,1)) self.length = 1 self.positions = [(51, 51), (50, 50)] self.score = 10 """ def random_food_position(self): """ Randomly generate a new food position, but don't place it on the snake. :return: None, Change the food position """ def reset(self): """ Reset the snake to its initial state. Set the length to 1, the snake head position to ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2)), the score to 0, and randomly generate new food position. :return: None >>> snake = Snake(100, 100, 1, (51, 51)) >>> snake.reset() self.length = 1 self.positions = [(50, 50)] self.score = 0 self.random_food_position() """ def eat_food(self): """ Increase the length of the snake by 1 and increase the score by 100. Randomly generate a new food position, but don't place it on the snake. :return: None >>> snake = Snake(100, 100, 1, (51, 51)) >>> snake.move((1,1)) >>> snake.eat_food() self.length = 2 self.score = 10 """
def eat_food(self): self.length += 1 self.score += 100 self.random_food_position()
Increase the length of the snake by 1 and increase the score by 100. Randomly generate a new food position, but don't place it on the snake.
ClassEval_78_sum
import re class SplitSentence: """ The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count. """ def count_words(self, sentence): """ Count the number of words in a sentence. Note that words are separated by spaces and that punctuation marks and numbers are not counted as words. :param sentence:string, sentence to be counted, where words are separated by spaces :return:int, number of words in the sentence >>> ss.count_words("abc def") 2 """ sentence = re.sub(r'[^a-zA-Z\s]', '', sentence) words = sentence.split() return len(words) def process_text_file(self, sentences_string): """ Given a text, return the number of words in the longest sentence :param sentences_string: string, undivided long sentence :return:int, the number of words in the longest sentence >>> ss.process_text_file("aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?") 4 """ sentences = self.split_sentences(sentences_string) max_count = 0 for sentence in sentences: count = self.count_words(sentence) if count > max_count: max_count = count return max_count
import re class SplitSentence: """ The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count. """ def count_words(self, sentence): """ Count the number of words in a sentence. Note that words are separated by spaces and that punctuation marks and numbers are not counted as words. :param sentence:string, sentence to be counted, where words are separated by spaces :return:int, number of words in the sentence >>> ss.count_words("abc def") 2 """ def process_text_file(self, sentences_string): """ Given a text, return the number of words in the longest sentence :param sentences_string: string, undivided long sentence :return:int, the number of words in the longest sentence >>> ss.process_text_file("aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?") 4 """
def split_sentences(self, sentences_string): sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', sentences_string) return sentences
Split a string into a list of sentences. Sentences end with . or ? and with a space after that. Please note that Mr. also end with . but are not sentences.
ClassEval_78_sum
import re class SplitSentence: """ The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count. """ def split_sentences(self, sentences_string): """ Split a string into a list of sentences. Sentences end with . or ? and with a space after that. Please note that Mr. also end with . but are not sentences. :param sentences_string: string, string to split :return:list, split sentence list >>> ss = SplitSentence() >>> ss.split_sentences("aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?") ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?'] """ sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', sentences_string) return sentences def process_text_file(self, sentences_string): """ Given a text, return the number of words in the longest sentence :param sentences_string: string, undivided long sentence :return:int, the number of words in the longest sentence >>> ss.process_text_file("aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?") 4 """ sentences = self.split_sentences(sentences_string) max_count = 0 for sentence in sentences: count = self.count_words(sentence) if count > max_count: max_count = count return max_count
import re class SplitSentence: """ The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count. """ def split_sentences(self, sentences_string): """ Split a string into a list of sentences. Sentences end with . or ? and with a space after that. Please note that Mr. also end with . but are not sentences. :param sentences_string: string, string to split :return:list, split sentence list >>> ss = SplitSentence() >>> ss.split_sentences("aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?") ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?'] """ def process_text_file(self, sentences_string): """ Given a text, return the number of words in the longest sentence :param sentences_string: string, undivided long sentence :return:int, the number of words in the longest sentence >>> ss.process_text_file("aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?") 4 """
def count_words(self, sentence): sentence = re.sub(r'[^a-zA-Z\s]', '', sentence) words = sentence.split() return len(words)
Count the number of words in a sentence. Note that words are separated by spaces and that punctuation marks and numbers are not counted as words.
ClassEval_78_sum
import re class SplitSentence: """ The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count. """ def split_sentences(self, sentences_string): """ Split a string into a list of sentences. Sentences end with . or ? and with a space after that. Please note that Mr. also end with . but are not sentences. :param sentences_string: string, string to split :return:list, split sentence list >>> ss = SplitSentence() >>> ss.split_sentences("aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?") ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?'] """ sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', sentences_string) return sentences def count_words(self, sentence): """ Count the number of words in a sentence. Note that words are separated by spaces and that punctuation marks and numbers are not counted as words. :param sentence:string, sentence to be counted, where words are separated by spaces :return:int, number of words in the sentence >>> ss.count_words("abc def") 2 """ sentence = re.sub(r'[^a-zA-Z\s]', '', sentence) words = sentence.split() return len(words) def process_text_file(self, sentences_string): sentences = self.split_sentences(sentences_string) max_count = 0 for sentence in sentences: count = self.count_words(sentence) if count > max_count: max_count = count return max_count
import re class SplitSentence: """ The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count. """ def split_sentences(self, sentences_string): """ Split a string into a list of sentences. Sentences end with . or ? and with a space after that. Please note that Mr. also end with . but are not sentences. :param sentences_string: string, string to split :return:list, split sentence list >>> ss = SplitSentence() >>> ss.split_sentences("aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?") ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?'] """ def count_words(self, sentence): """ Count the number of words in a sentence. Note that words are separated by spaces and that punctuation marks and numbers are not counted as words. :param sentence:string, sentence to be counted, where words are separated by spaces :return:int, number of words in the sentence >>> ss.count_words("abc def") 2 """ def process_text_file(self, sentences_string): """ Given a text, return the number of words in the longest sentence :param sentences_string: string, undivided long sentence :return:int, the number of words in the longest sentence >>> ss.process_text_file("aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?") 4 """
def process_text_file(self, sentences_string): sentences = self.split_sentences(sentences_string) max_count = 0 for sentence in sentences: count = self.count_words(sentence) if count > max_count: max_count = count return max_count
Given a text, return the number of words in the longest sentence
ClassEval_79_sum
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): self.table_name = table_name def insert(self, data): """ Generates an INSERT SQL statement based on the given data. :param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values. :return: str. The generated SQL statement. >>> sql.insert({'key1': 'value1', 'key2': 'value2'}) "INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');" """ fields = ", ".join(data.keys()) values = ", ".join([f"'{value}'" for value in data.values()]) sql = f"INSERT INTO {self.table_name} ({fields}) VALUES ({values})" return sql + ";" def update(self, data, condition): """ Generates an UPDATE SQL statement based on the given data and condition. :param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values. :param condition: str. The condition expression for the update. :return: str. The generated SQL statement. >>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, "field3 = value1") "UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;" """ set_clause = ", ".join([f"{field} = '{value}'" for field, value in data.items()]) sql = f"UPDATE {self.table_name} SET {set_clause} WHERE {condition}" return sql + ";" def delete(self, condition): """ Generates a DELETE SQL statement based on the given condition. :param condition: str. The condition expression for the delete. :return: str. The generated SQL statement. >>> sql.delete("field1 = value1") 'DELETE FROM table1 WHERE field1 = value1;' """ sql = f"DELETE FROM {self.table_name} WHERE {condition}" return sql + ";" def select_female_under_age(self, age): """ Generates a SQL statement to select females under a specified age. :param age: int. The specified age. :return: str. The generated SQL statement. >>> sql.select_female_under_age(30) "SELECT * FROM table1 WHERE age < 30 AND gender = 'female';" """ condition = f"age < {age} AND gender = 'female'" return self.select(condition=condition) def select_by_age_range(self, min_age, max_age): """ Generates a SQL statement to select records within a specified age range. :param min_age: int. The minimum age. :param max_age: int. The maximum age. :return: str. The generated SQL statement. >>> sql.select_by_age_range(20, 30) 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;' """ condition = f"age BETWEEN {min_age} AND {max_age}" return self.select(condition=condition)
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): """ Initialize the table name. :param table_name: str """ self.table_name = table_name def insert(self, data): """ Generates an INSERT SQL statement based on the given data. :param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values. :return: str. The generated SQL statement. >>> sql.insert({'key1': 'value1', 'key2': 'value2'}) "INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');" """ def update(self, data, condition): """ Generates an UPDATE SQL statement based on the given data and condition. :param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values. :param condition: str. The condition expression for the update. :return: str. The generated SQL statement. >>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, "field3 = value1") "UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;" """ def delete(self, condition): """ Generates a DELETE SQL statement based on the given condition. :param condition: str. The condition expression for the delete. :return: str. The generated SQL statement. >>> sql.delete("field1 = value1") 'DELETE FROM table1 WHERE field1 = value1;' """ def select_female_under_age(self, age): """ Generates a SQL statement to select females under a specified age. :param age: int. The specified age. :return: str. The generated SQL statement. >>> sql.select_female_under_age(30) "SELECT * FROM table1 WHERE age < 30 AND gender = 'female';" """ def select_by_age_range(self, min_age, max_age): """ Generates a SQL statement to select records within a specified age range. :param min_age: int. The minimum age. :param max_age: int. The maximum age. :return: str. The generated SQL statement. >>> sql.select_by_age_range(20, 30) 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;' """
def select(self, fields=None, condition=None): if fields is None: fields = "*" else: fields = ", ".join(fields) sql = f"SELECT {fields} FROM {self.table_name}" if condition is not None: sql += f" WHERE {condition}" return sql + ";"
Generates a SELECT SQL statement based on the specified fields and conditions.
ClassEval_79_sum
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQL statement based on the specified fields and conditions. :param fields: list, optional. Default is None. The list of fields to be queried. :param condition: str, optional. Default is None. The condition expression for the query. :return: str. The generated SQL statement. >>> sql = SQLGenerator('table1') >>> sql.select(['field1', 'field2'], 'filed3 = value1') 'SELECT field1, field2 FROM table1 WHERE filed3 = value1;' """ if fields is None: fields = "*" else: fields = ", ".join(fields) sql = f"SELECT {fields} FROM {self.table_name}" if condition is not None: sql += f" WHERE {condition}" return sql + ";" def update(self, data, condition): """ Generates an UPDATE SQL statement based on the given data and condition. :param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values. :param condition: str. The condition expression for the update. :return: str. The generated SQL statement. >>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, "field3 = value1") "UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;" """ set_clause = ", ".join([f"{field} = '{value}'" for field, value in data.items()]) sql = f"UPDATE {self.table_name} SET {set_clause} WHERE {condition}" return sql + ";" def delete(self, condition): """ Generates a DELETE SQL statement based on the given condition. :param condition: str. The condition expression for the delete. :return: str. The generated SQL statement. >>> sql.delete("field1 = value1") 'DELETE FROM table1 WHERE field1 = value1;' """ sql = f"DELETE FROM {self.table_name} WHERE {condition}" return sql + ";" def select_female_under_age(self, age): """ Generates a SQL statement to select females under a specified age. :param age: int. The specified age. :return: str. The generated SQL statement. >>> sql.select_female_under_age(30) "SELECT * FROM table1 WHERE age < 30 AND gender = 'female';" """ condition = f"age < {age} AND gender = 'female'" return self.select(condition=condition) def select_by_age_range(self, min_age, max_age): """ Generates a SQL statement to select records within a specified age range. :param min_age: int. The minimum age. :param max_age: int. The maximum age. :return: str. The generated SQL statement. >>> sql.select_by_age_range(20, 30) 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;' """ condition = f"age BETWEEN {min_age} AND {max_age}" return self.select(condition=condition)
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): """ Initialize the table name. :param table_name: str """ self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQL statement based on the specified fields and conditions. :param fields: list, optional. Default is None. The list of fields to be queried. :param condition: str, optional. Default is None. The condition expression for the query. :return: str. The generated SQL statement. >>> sql = SQLGenerator('table1') >>> sql.select(['field1', 'field2'], 'filed3 = value1') 'SELECT field1, field2 FROM table1 WHERE filed3 = value1;' """ def update(self, data, condition): """ Generates an UPDATE SQL statement based on the given data and condition. :param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values. :param condition: str. The condition expression for the update. :return: str. The generated SQL statement. >>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, "field3 = value1") "UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;" """ def delete(self, condition): """ Generates a DELETE SQL statement based on the given condition. :param condition: str. The condition expression for the delete. :return: str. The generated SQL statement. >>> sql.delete("field1 = value1") 'DELETE FROM table1 WHERE field1 = value1;' """ def select_female_under_age(self, age): """ Generates a SQL statement to select females under a specified age. :param age: int. The specified age. :return: str. The generated SQL statement. >>> sql.select_female_under_age(30) "SELECT * FROM table1 WHERE age < 30 AND gender = 'female';" """ def select_by_age_range(self, min_age, max_age): """ Generates a SQL statement to select records within a specified age range. :param min_age: int. The minimum age. :param max_age: int. The maximum age. :return: str. The generated SQL statement. >>> sql.select_by_age_range(20, 30) 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;' """
def insert(self, data): fields = ", ".join(data.keys()) values = ", ".join([f"'{value}'" for value in data.values()]) sql = f"INSERT INTO {self.table_name} ({fields}) VALUES ({values})" return sql + ";"
Generates an INSERT SQL statement based on the given data.
ClassEval_79_sum
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQL statement based on the specified fields and conditions. :param fields: list, optional. Default is None. The list of fields to be queried. :param condition: str, optional. Default is None. The condition expression for the query. :return: str. The generated SQL statement. >>> sql = SQLGenerator('table1') >>> sql.select(['field1', 'field2'], 'filed3 = value1') 'SELECT field1, field2 FROM table1 WHERE filed3 = value1;' """ if fields is None: fields = "*" else: fields = ", ".join(fields) sql = f"SELECT {fields} FROM {self.table_name}" if condition is not None: sql += f" WHERE {condition}" return sql + ";" def insert(self, data): """ Generates an INSERT SQL statement based on the given data. :param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values. :return: str. The generated SQL statement. >>> sql.insert({'key1': 'value1', 'key2': 'value2'}) "INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');" """ fields = ", ".join(data.keys()) values = ", ".join([f"'{value}'" for value in data.values()]) sql = f"INSERT INTO {self.table_name} ({fields}) VALUES ({values})" return sql + ";" def delete(self, condition): """ Generates a DELETE SQL statement based on the given condition. :param condition: str. The condition expression for the delete. :return: str. The generated SQL statement. >>> sql.delete("field1 = value1") 'DELETE FROM table1 WHERE field1 = value1;' """ sql = f"DELETE FROM {self.table_name} WHERE {condition}" return sql + ";" def select_female_under_age(self, age): """ Generates a SQL statement to select females under a specified age. :param age: int. The specified age. :return: str. The generated SQL statement. >>> sql.select_female_under_age(30) "SELECT * FROM table1 WHERE age < 30 AND gender = 'female';" """ condition = f"age < {age} AND gender = 'female'" return self.select(condition=condition) def select_by_age_range(self, min_age, max_age): """ Generates a SQL statement to select records within a specified age range. :param min_age: int. The minimum age. :param max_age: int. The maximum age. :return: str. The generated SQL statement. >>> sql.select_by_age_range(20, 30) 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;' """ condition = f"age BETWEEN {min_age} AND {max_age}" return self.select(condition=condition)
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): """ Initialize the table name. :param table_name: str """ self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQL statement based on the specified fields and conditions. :param fields: list, optional. Default is None. The list of fields to be queried. :param condition: str, optional. Default is None. The condition expression for the query. :return: str. The generated SQL statement. >>> sql = SQLGenerator('table1') >>> sql.select(['field1', 'field2'], 'filed3 = value1') 'SELECT field1, field2 FROM table1 WHERE filed3 = value1;' """ def insert(self, data): """ Generates an INSERT SQL statement based on the given data. :param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values. :return: str. The generated SQL statement. >>> sql.insert({'key1': 'value1', 'key2': 'value2'}) "INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');" """ def delete(self, condition): """ Generates a DELETE SQL statement based on the given condition. :param condition: str. The condition expression for the delete. :return: str. The generated SQL statement. >>> sql.delete("field1 = value1") 'DELETE FROM table1 WHERE field1 = value1;' """ def select_female_under_age(self, age): """ Generates a SQL statement to select females under a specified age. :param age: int. The specified age. :return: str. The generated SQL statement. >>> sql.select_female_under_age(30) "SELECT * FROM table1 WHERE age < 30 AND gender = 'female';" """ def select_by_age_range(self, min_age, max_age): """ Generates a SQL statement to select records within a specified age range. :param min_age: int. The minimum age. :param max_age: int. The maximum age. :return: str. The generated SQL statement. >>> sql.select_by_age_range(20, 30) 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;' """
def update(self, data, condition): set_clause = ", ".join([f"{field} = '{value}'" for field, value in data.items()]) sql = f"UPDATE {self.table_name} SET {set_clause} WHERE {condition}" return sql + ";"
Generates an UPDATE SQL statement based on the given data and condition.
ClassEval_79_sum
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQL statement based on the specified fields and conditions. :param fields: list, optional. Default is None. The list of fields to be queried. :param condition: str, optional. Default is None. The condition expression for the query. :return: str. The generated SQL statement. >>> sql = SQLGenerator('table1') >>> sql.select(['field1', 'field2'], 'filed3 = value1') 'SELECT field1, field2 FROM table1 WHERE filed3 = value1;' """ if fields is None: fields = "*" else: fields = ", ".join(fields) sql = f"SELECT {fields} FROM {self.table_name}" if condition is not None: sql += f" WHERE {condition}" return sql + ";" def insert(self, data): """ Generates an INSERT SQL statement based on the given data. :param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values. :return: str. The generated SQL statement. >>> sql.insert({'key1': 'value1', 'key2': 'value2'}) "INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');" """ fields = ", ".join(data.keys()) values = ", ".join([f"'{value}'" for value in data.values()]) sql = f"INSERT INTO {self.table_name} ({fields}) VALUES ({values})" return sql + ";" def update(self, data, condition): """ Generates an UPDATE SQL statement based on the given data and condition. :param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values. :param condition: str. The condition expression for the update. :return: str. The generated SQL statement. >>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, "field3 = value1") "UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;" """ set_clause = ", ".join([f"{field} = '{value}'" for field, value in data.items()]) sql = f"UPDATE {self.table_name} SET {set_clause} WHERE {condition}" return sql + ";" def select_female_under_age(self, age): """ Generates a SQL statement to select females under a specified age. :param age: int. The specified age. :return: str. The generated SQL statement. >>> sql.select_female_under_age(30) "SELECT * FROM table1 WHERE age < 30 AND gender = 'female';" """ condition = f"age < {age} AND gender = 'female'" return self.select(condition=condition) def select_by_age_range(self, min_age, max_age): """ Generates a SQL statement to select records within a specified age range. :param min_age: int. The minimum age. :param max_age: int. The maximum age. :return: str. The generated SQL statement. >>> sql.select_by_age_range(20, 30) 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;' """ condition = f"age BETWEEN {min_age} AND {max_age}" return self.select(condition=condition)
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): """ Initialize the table name. :param table_name: str """ self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQL statement based on the specified fields and conditions. :param fields: list, optional. Default is None. The list of fields to be queried. :param condition: str, optional. Default is None. The condition expression for the query. :return: str. The generated SQL statement. >>> sql = SQLGenerator('table1') >>> sql.select(['field1', 'field2'], 'filed3 = value1') 'SELECT field1, field2 FROM table1 WHERE filed3 = value1;' """ def insert(self, data): """ Generates an INSERT SQL statement based on the given data. :param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values. :return: str. The generated SQL statement. >>> sql.insert({'key1': 'value1', 'key2': 'value2'}) "INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');" """ def update(self, data, condition): """ Generates an UPDATE SQL statement based on the given data and condition. :param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values. :param condition: str. The condition expression for the update. :return: str. The generated SQL statement. >>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, "field3 = value1") "UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;" """ def select_female_under_age(self, age): """ Generates a SQL statement to select females under a specified age. :param age: int. The specified age. :return: str. The generated SQL statement. >>> sql.select_female_under_age(30) "SELECT * FROM table1 WHERE age < 30 AND gender = 'female';" """ def select_by_age_range(self, min_age, max_age): """ Generates a SQL statement to select records within a specified age range. :param min_age: int. The minimum age. :param max_age: int. The maximum age. :return: str. The generated SQL statement. >>> sql.select_by_age_range(20, 30) 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;' """
def delete(self, condition): sql = f"DELETE FROM {self.table_name} WHERE {condition}" return sql + ";"
Generates a DELETE SQL statement based on the given condition.
ClassEval_79_sum
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQL statement based on the specified fields and conditions. :param fields: list, optional. Default is None. The list of fields to be queried. :param condition: str, optional. Default is None. The condition expression for the query. :return: str. The generated SQL statement. >>> sql = SQLGenerator('table1') >>> sql.select(['field1', 'field2'], 'filed3 = value1') 'SELECT field1, field2 FROM table1 WHERE filed3 = value1;' """ if fields is None: fields = "*" else: fields = ", ".join(fields) sql = f"SELECT {fields} FROM {self.table_name}" if condition is not None: sql += f" WHERE {condition}" return sql + ";" def insert(self, data): """ Generates an INSERT SQL statement based on the given data. :param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values. :return: str. The generated SQL statement. >>> sql.insert({'key1': 'value1', 'key2': 'value2'}) "INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');" """ fields = ", ".join(data.keys()) values = ", ".join([f"'{value}'" for value in data.values()]) sql = f"INSERT INTO {self.table_name} ({fields}) VALUES ({values})" return sql + ";" def update(self, data, condition): """ Generates an UPDATE SQL statement based on the given data and condition. :param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values. :param condition: str. The condition expression for the update. :return: str. The generated SQL statement. >>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, "field3 = value1") "UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;" """ set_clause = ", ".join([f"{field} = '{value}'" for field, value in data.items()]) sql = f"UPDATE {self.table_name} SET {set_clause} WHERE {condition}" return sql + ";" def delete(self, condition): """ Generates a DELETE SQL statement based on the given condition. :param condition: str. The condition expression for the delete. :return: str. The generated SQL statement. >>> sql.delete("field1 = value1") 'DELETE FROM table1 WHERE field1 = value1;' """ sql = f"DELETE FROM {self.table_name} WHERE {condition}" return sql + ";" def select_by_age_range(self, min_age, max_age): """ Generates a SQL statement to select records within a specified age range. :param min_age: int. The minimum age. :param max_age: int. The maximum age. :return: str. The generated SQL statement. >>> sql.select_by_age_range(20, 30) 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;' """ condition = f"age BETWEEN {min_age} AND {max_age}" return self.select(condition=condition)
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): """ Initialize the table name. :param table_name: str """ self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQL statement based on the specified fields and conditions. :param fields: list, optional. Default is None. The list of fields to be queried. :param condition: str, optional. Default is None. The condition expression for the query. :return: str. The generated SQL statement. >>> sql = SQLGenerator('table1') >>> sql.select(['field1', 'field2'], 'filed3 = value1') 'SELECT field1, field2 FROM table1 WHERE filed3 = value1;' """ def insert(self, data): """ Generates an INSERT SQL statement based on the given data. :param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values. :return: str. The generated SQL statement. >>> sql.insert({'key1': 'value1', 'key2': 'value2'}) "INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');" """ def update(self, data, condition): """ Generates an UPDATE SQL statement based on the given data and condition. :param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values. :param condition: str. The condition expression for the update. :return: str. The generated SQL statement. >>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, "field3 = value1") "UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;" """ def delete(self, condition): """ Generates a DELETE SQL statement based on the given condition. :param condition: str. The condition expression for the delete. :return: str. The generated SQL statement. >>> sql.delete("field1 = value1") 'DELETE FROM table1 WHERE field1 = value1;' """ def select_by_age_range(self, min_age, max_age): """ Generates a SQL statement to select records within a specified age range. :param min_age: int. The minimum age. :param max_age: int. The maximum age. :return: str. The generated SQL statement. >>> sql.select_by_age_range(20, 30) 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;' """
def select_female_under_age(self, age): condition = f"age < {age} AND gender = 'female'" return self.select(condition=condition)
Generates a SQL statement to select females under a specified age.
ClassEval_79_sum
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQL statement based on the specified fields and conditions. :param fields: list, optional. Default is None. The list of fields to be queried. :param condition: str, optional. Default is None. The condition expression for the query. :return: str. The generated SQL statement. >>> sql = SQLGenerator('table1') >>> sql.select(['field1', 'field2'], 'filed3 = value1') 'SELECT field1, field2 FROM table1 WHERE filed3 = value1;' """ if fields is None: fields = "*" else: fields = ", ".join(fields) sql = f"SELECT {fields} FROM {self.table_name}" if condition is not None: sql += f" WHERE {condition}" return sql + ";" def insert(self, data): """ Generates an INSERT SQL statement based on the given data. :param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values. :return: str. The generated SQL statement. >>> sql.insert({'key1': 'value1', 'key2': 'value2'}) "INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');" """ fields = ", ".join(data.keys()) values = ", ".join([f"'{value}'" for value in data.values()]) sql = f"INSERT INTO {self.table_name} ({fields}) VALUES ({values})" return sql + ";" def update(self, data, condition): """ Generates an UPDATE SQL statement based on the given data and condition. :param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values. :param condition: str. The condition expression for the update. :return: str. The generated SQL statement. >>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, "field3 = value1") "UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;" """ set_clause = ", ".join([f"{field} = '{value}'" for field, value in data.items()]) sql = f"UPDATE {self.table_name} SET {set_clause} WHERE {condition}" return sql + ";" def delete(self, condition): """ Generates a DELETE SQL statement based on the given condition. :param condition: str. The condition expression for the delete. :return: str. The generated SQL statement. >>> sql.delete("field1 = value1") 'DELETE FROM table1 WHERE field1 = value1;' """ sql = f"DELETE FROM {self.table_name} WHERE {condition}" return sql + ";" def select_female_under_age(self, age): """ Generates a SQL statement to select females under a specified age. :param age: int. The specified age. :return: str. The generated SQL statement. >>> sql.select_female_under_age(30) "SELECT * FROM table1 WHERE age < 30 AND gender = 'female';" """ condition = f"age < {age} AND gender = 'female'" return self.select(condition=condition) def select_by_age_range(self, min_age, max_age): condition = f"age BETWEEN {min_age} AND {max_age}" return self.select(condition=condition)
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): """ Initialize the table name. :param table_name: str """ self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQL statement based on the specified fields and conditions. :param fields: list, optional. Default is None. The list of fields to be queried. :param condition: str, optional. Default is None. The condition expression for the query. :return: str. The generated SQL statement. >>> sql = SQLGenerator('table1') >>> sql.select(['field1', 'field2'], 'filed3 = value1') 'SELECT field1, field2 FROM table1 WHERE filed3 = value1;' """ def insert(self, data): """ Generates an INSERT SQL statement based on the given data. :param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values. :return: str. The generated SQL statement. >>> sql.insert({'key1': 'value1', 'key2': 'value2'}) "INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');" """ def update(self, data, condition): """ Generates an UPDATE SQL statement based on the given data and condition. :param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values. :param condition: str. The condition expression for the update. :return: str. The generated SQL statement. >>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, "field3 = value1") "UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;" """ def delete(self, condition): """ Generates a DELETE SQL statement based on the given condition. :param condition: str. The condition expression for the delete. :return: str. The generated SQL statement. >>> sql.delete("field1 = value1") 'DELETE FROM table1 WHERE field1 = value1;' """ def select_female_under_age(self, age): """ Generates a SQL statement to select females under a specified age. :param age: int. The specified age. :return: str. The generated SQL statement. >>> sql.select_female_under_age(30) "SELECT * FROM table1 WHERE age < 30 AND gender = 'female';" """ def select_by_age_range(self, min_age, max_age): """ Generates a SQL statement to select records within a specified age range. :param min_age: int. The minimum age. :param max_age: int. The maximum age. :return: str. The generated SQL statement. >>> sql.select_by_age_range(20, 30) 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;' """
def select_by_age_range(self, min_age, max_age): condition = f"age BETWEEN {min_age} AND {max_age}" return self.select(condition=condition)
Generates a SQL statement to select records within a specified age range.
ClassEval_80_sum
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod @staticmethod def insert(table, data): """ Generate the INSERT SQL statement from the given parameters. :param table: str, the table to be inserted in database. :param data: dict, the key and value in SQL insert statement :return query: str, the SQL insert statement. >>> SQLQueryBuilder.insert('table1', {'name': 'Test', 'age': 14}) "INSERT INTO table1 (name, age) VALUES ('Test', '14')" """ keys = ', '.join(data.keys()) values = ', '.join(f"'{v}'" for v in data.values()) return f"INSERT INTO {table} ({keys}) VALUES ({values})" @staticmethod def delete(table, where=None): """ Generate the DELETE SQL statement from the given parameters. :param table: str, the table that will be excuted with DELETE operation in database :param where: dict, {key1: value1, key2: value2 ...}. The query condition. :return query: str, the SQL delete statement. >>> SQLQueryBuilder.delete('table1', {'name': 'Test', 'age': 14}) "DELETE FROM table1 WHERE name='Test' AND age='14'" """ query = f"DELETE FROM {table}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query @staticmethod def update(table, data, where=None): """ Generate the UPDATE SQL statement from the given parameters. :param table: str, the table that will be excuted with UPDATE operation in database :param data: dict, the key and value in SQL update statement :param where: dict, {key1: value1, key2: value2 ...}. The query condition. >>> SQLQueryBuilder.update('table1', {'name': 'Test2', 'age': 15}, where = {'name':'Test'}) "UPDATE table1 SET name='Test2', age='15' WHERE name='Test'" """ update_str = ', '.join(f"{k}='{v}'" for k, v in data.items()) query = f"UPDATE {table} SET {update_str}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod @staticmethod def insert(table, data): """ Generate the INSERT SQL statement from the given parameters. :param table: str, the table to be inserted in database. :param data: dict, the key and value in SQL insert statement :return query: str, the SQL insert statement. >>> SQLQueryBuilder.insert('table1', {'name': 'Test', 'age': 14}) "INSERT INTO table1 (name, age) VALUES ('Test', '14')" """ @staticmethod def delete(table, where=None): """ Generate the DELETE SQL statement from the given parameters. :param table: str, the table that will be excuted with DELETE operation in database :param where: dict, {key1: value1, key2: value2 ...}. The query condition. :return query: str, the SQL delete statement. >>> SQLQueryBuilder.delete('table1', {'name': 'Test', 'age': 14}) "DELETE FROM table1 WHERE name='Test' AND age='14'" """ @staticmethod def update(table, data, where=None): """ Generate the UPDATE SQL statement from the given parameters. :param table: str, the table that will be excuted with UPDATE operation in database :param data: dict, the key and value in SQL update statement :param where: dict, {key1: value1, key2: value2 ...}. The query condition. >>> SQLQueryBuilder.update('table1', {'name': 'Test2', 'age': 15}, where = {'name':'Test'}) "UPDATE table1 SET name='Test2', age='15' WHERE name='Test'" """
def select(table, columns='*', where=None): if columns != '*': columns = ', '.join(columns) query = f"SELECT {columns} FROM {table}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query
Generate the SELECT SQL statement from the given parameters.
ClassEval_80_sum
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod def select(table, columns='*', where=None): """ Generate the SELECT SQL statement from the given parameters. :param table: str, the query table in database. :param columns: list of str, ['col1', 'col2']. :param where: dict, {key1: value1, key2: value2 ...}. The query condition. return query: str, the SQL query statement. >>> SQLQueryBuilder.select('table1', columns = ["col1","col2"], where = {"age": 15}) "SELECT col1, col2 FROM table1 WHERE age='15'" """ if columns != '*': columns = ', '.join(columns) query = f"SELECT {columns} FROM {table}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query @staticmethod def delete(table, where=None): """ Generate the DELETE SQL statement from the given parameters. :param table: str, the table that will be excuted with DELETE operation in database :param where: dict, {key1: value1, key2: value2 ...}. The query condition. :return query: str, the SQL delete statement. >>> SQLQueryBuilder.delete('table1', {'name': 'Test', 'age': 14}) "DELETE FROM table1 WHERE name='Test' AND age='14'" """ query = f"DELETE FROM {table}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query @staticmethod def update(table, data, where=None): """ Generate the UPDATE SQL statement from the given parameters. :param table: str, the table that will be excuted with UPDATE operation in database :param data: dict, the key and value in SQL update statement :param where: dict, {key1: value1, key2: value2 ...}. The query condition. >>> SQLQueryBuilder.update('table1', {'name': 'Test2', 'age': 15}, where = {'name':'Test'}) "UPDATE table1 SET name='Test2', age='15' WHERE name='Test'" """ update_str = ', '.join(f"{k}='{v}'" for k, v in data.items()) query = f"UPDATE {table} SET {update_str}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod def select(table, columns='*', where=None): """ Generate the SELECT SQL statement from the given parameters. :param table: str, the query table in database. :param columns: list of str, ['col1', 'col2']. :param where: dict, {key1: value1, key2: value2 ...}. The query condition. return query: str, the SQL query statement. >>> SQLQueryBuilder.select('table1', columns = ["col1","col2"], where = {"age": 15}) "SELECT col1, col2 FROM table1 WHERE age='15'" """ @staticmethod def delete(table, where=None): """ Generate the DELETE SQL statement from the given parameters. :param table: str, the table that will be excuted with DELETE operation in database :param where: dict, {key1: value1, key2: value2 ...}. The query condition. :return query: str, the SQL delete statement. >>> SQLQueryBuilder.delete('table1', {'name': 'Test', 'age': 14}) "DELETE FROM table1 WHERE name='Test' AND age='14'" """ @staticmethod def update(table, data, where=None): """ Generate the UPDATE SQL statement from the given parameters. :param table: str, the table that will be excuted with UPDATE operation in database :param data: dict, the key and value in SQL update statement :param where: dict, {key1: value1, key2: value2 ...}. The query condition. >>> SQLQueryBuilder.update('table1', {'name': 'Test2', 'age': 15}, where = {'name':'Test'}) "UPDATE table1 SET name='Test2', age='15' WHERE name='Test'" """
@staticmethod def insert(table, data): keys = ', '.join(data.keys()) values = ', '.join(f"'{v}'" for v in data.values()) return f"INSERT INTO {table} ({keys}) VALUES ({values})"
Generate the INSERT SQL statement from the given parameters.
ClassEval_80_sum
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod def select(table, columns='*', where=None): """ Generate the SELECT SQL statement from the given parameters. :param table: str, the query table in database. :param columns: list of str, ['col1', 'col2']. :param where: dict, {key1: value1, key2: value2 ...}. The query condition. return query: str, the SQL query statement. >>> SQLQueryBuilder.select('table1', columns = ["col1","col2"], where = {"age": 15}) "SELECT col1, col2 FROM table1 WHERE age='15'" """ if columns != '*': columns = ', '.join(columns) query = f"SELECT {columns} FROM {table}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query @staticmethod def insert(table, data): """ Generate the INSERT SQL statement from the given parameters. :param table: str, the table to be inserted in database. :param data: dict, the key and value in SQL insert statement :return query: str, the SQL insert statement. >>> SQLQueryBuilder.insert('table1', {'name': 'Test', 'age': 14}) "INSERT INTO table1 (name, age) VALUES ('Test', '14')" """ keys = ', '.join(data.keys()) values = ', '.join(f"'{v}'" for v in data.values()) return f"INSERT INTO {table} ({keys}) VALUES ({values})" @staticmethod def update(table, data, where=None): """ Generate the UPDATE SQL statement from the given parameters. :param table: str, the table that will be excuted with UPDATE operation in database :param data: dict, the key and value in SQL update statement :param where: dict, {key1: value1, key2: value2 ...}. The query condition. >>> SQLQueryBuilder.update('table1', {'name': 'Test2', 'age': 15}, where = {'name':'Test'}) "UPDATE table1 SET name='Test2', age='15' WHERE name='Test'" """ update_str = ', '.join(f"{k}='{v}'" for k, v in data.items()) query = f"UPDATE {table} SET {update_str}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod def select(table, columns='*', where=None): """ Generate the SELECT SQL statement from the given parameters. :param table: str, the query table in database. :param columns: list of str, ['col1', 'col2']. :param where: dict, {key1: value1, key2: value2 ...}. The query condition. return query: str, the SQL query statement. >>> SQLQueryBuilder.select('table1', columns = ["col1","col2"], where = {"age": 15}) "SELECT col1, col2 FROM table1 WHERE age='15'" """ @staticmethod def insert(table, data): """ Generate the INSERT SQL statement from the given parameters. :param table: str, the table to be inserted in database. :param data: dict, the key and value in SQL insert statement :return query: str, the SQL insert statement. >>> SQLQueryBuilder.insert('table1', {'name': 'Test', 'age': 14}) "INSERT INTO table1 (name, age) VALUES ('Test', '14')" """ @staticmethod def update(table, data, where=None): """ Generate the UPDATE SQL statement from the given parameters. :param table: str, the table that will be excuted with UPDATE operation in database :param data: dict, the key and value in SQL update statement :param where: dict, {key1: value1, key2: value2 ...}. The query condition. >>> SQLQueryBuilder.update('table1', {'name': 'Test2', 'age': 15}, where = {'name':'Test'}) "UPDATE table1 SET name='Test2', age='15' WHERE name='Test'" """
@staticmethod def delete(table, where=None): query = f"DELETE FROM {table}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query
Generate the DELETE SQL statement from the given parameters.
ClassEval_80_sum
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod def select(table, columns='*', where=None): """ Generate the SELECT SQL statement from the given parameters. :param table: str, the query table in database. :param columns: list of str, ['col1', 'col2']. :param where: dict, {key1: value1, key2: value2 ...}. The query condition. return query: str, the SQL query statement. >>> SQLQueryBuilder.select('table1', columns = ["col1","col2"], where = {"age": 15}) "SELECT col1, col2 FROM table1 WHERE age='15'" """ if columns != '*': columns = ', '.join(columns) query = f"SELECT {columns} FROM {table}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query @staticmethod def insert(table, data): """ Generate the INSERT SQL statement from the given parameters. :param table: str, the table to be inserted in database. :param data: dict, the key and value in SQL insert statement :return query: str, the SQL insert statement. >>> SQLQueryBuilder.insert('table1', {'name': 'Test', 'age': 14}) "INSERT INTO table1 (name, age) VALUES ('Test', '14')" """ keys = ', '.join(data.keys()) values = ', '.join(f"'{v}'" for v in data.values()) return f"INSERT INTO {table} ({keys}) VALUES ({values})" @staticmethod def delete(table, where=None): """ Generate the DELETE SQL statement from the given parameters. :param table: str, the table that will be excuted with DELETE operation in database :param where: dict, {key1: value1, key2: value2 ...}. The query condition. :return query: str, the SQL delete statement. >>> SQLQueryBuilder.delete('table1', {'name': 'Test', 'age': 14}) "DELETE FROM table1 WHERE name='Test' AND age='14'" """ query = f"DELETE FROM {table}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query @staticmethod def update(table, data, where=None): update_str = ', '.join(f"{k}='{v}'" for k, v in data.items()) query = f"UPDATE {table} SET {update_str}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod def select(table, columns='*', where=None): """ Generate the SELECT SQL statement from the given parameters. :param table: str, the query table in database. :param columns: list of str, ['col1', 'col2']. :param where: dict, {key1: value1, key2: value2 ...}. The query condition. return query: str, the SQL query statement. >>> SQLQueryBuilder.select('table1', columns = ["col1","col2"], where = {"age": 15}) "SELECT col1, col2 FROM table1 WHERE age='15'" """ @staticmethod def insert(table, data): """ Generate the INSERT SQL statement from the given parameters. :param table: str, the table to be inserted in database. :param data: dict, the key and value in SQL insert statement :return query: str, the SQL insert statement. >>> SQLQueryBuilder.insert('table1', {'name': 'Test', 'age': 14}) "INSERT INTO table1 (name, age) VALUES ('Test', '14')" """ @staticmethod def delete(table, where=None): """ Generate the DELETE SQL statement from the given parameters. :param table: str, the table that will be excuted with DELETE operation in database :param where: dict, {key1: value1, key2: value2 ...}. The query condition. :return query: str, the SQL delete statement. >>> SQLQueryBuilder.delete('table1', {'name': 'Test', 'age': 14}) "DELETE FROM table1 WHERE name='Test' AND age='14'" """ @staticmethod def update(table, data, where=None): """ Generate the UPDATE SQL statement from the given parameters. :param table: str, the table that will be excuted with UPDATE operation in database :param data: dict, the key and value in SQL update statement :param where: dict, {key1: value1, key2: value2 ...}. The query condition. >>> SQLQueryBuilder.update('table1', {'name': 'Test2', 'age': 15}, where = {'name':'Test'}) "UPDATE table1 SET name='Test2', age='15' WHERE name='Test'" """
@staticmethod def update(table, data, where=None): update_str = ', '.join(f"{k}='{v}'" for k, v in data.items()) query = f"UPDATE {table} SET {update_str}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query
Generate the UPDATE SQL statement from the given parameters.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod @staticmethod def mode(data): """ calculates the mode of the given list. :param data: the given list, list. :return: the mode of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.mode([1, 2, 3, 3]) [3] """ counts = {} for value in data: counts[value] = counts.get(value, 0) + 1 max_count = max(counts.values()) mode_values = [value for value, count in counts.items() if count == max_count] return mode_values @staticmethod def correlation(x, y): """ calculates the correlation of the given list. :param x: the given list, list. :param y: the given list, list. :return: the correlation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.correlation([1, 2, 3], [4, 5, 6]) 1.0 """ n = len(x) mean_x = sum(x) / n mean_y = sum(y) / n numerator = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y)) denominator = math.sqrt(sum((xi - mean_x) ** 2 for xi in x) * sum((yi - mean_y) ** 2 for yi in y)) if denominator == 0: return None return numerator / denominator @staticmethod def mean(data): """ calculates the mean of the given list. :param data: the given list, list. :return: the mean of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.mean([1, 2, 3]) 2.0 """ if len(data) == 0: return None return sum(data) / len(data) @staticmethod def correlation_matrix(data): """ calculates the correlation matrix of the given list. :param data: the given list, list. :return: the correlation matrix of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] """ matrix = [] for i in range(len(data[0])): row = [] for j in range(len(data[0])): column1 = [row[i] for row in data] column2 = [row[j] for row in data] correlation = Statistics3.correlation(column1, column2) row.append(correlation) matrix.append(row) return matrix @staticmethod def standard_deviation(data): """ calculates the standard deviation of the given list. :param data: the given list, list. :return: the standard deviation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.standard_deviation([1, 2, 3]) 1.0 """ n = len(data) if n < 2: return None mean_value = Statistics3.mean(data) variance = sum((x - mean_value) ** 2 for x in data) / (n - 1) return math.sqrt(variance) @staticmethod def z_score(data): """ calculates the z-score of the given list. :param data: the given list, list. :return: the z-score of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.z_score([1, 2, 3, 4]) [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225] """ mean = Statistics3.mean(data) std_deviation = Statistics3.standard_deviation(data) if std_deviation is None or std_deviation == 0: return None return [(x - mean) / std_deviation for x in data]
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod @staticmethod def mode(data): """ calculates the mode of the given list. :param data: the given list, list. :return: the mode of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.mode([1, 2, 3, 3]) [3] """ @staticmethod def correlation(x, y): """ calculates the correlation of the given list. :param x: the given list, list. :param y: the given list, list. :return: the correlation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.correlation([1, 2, 3], [4, 5, 6]) 1.0 """ @staticmethod def mean(data): """ calculates the mean of the given list. :param data: the given list, list. :return: the mean of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.mean([1, 2, 3]) 2.0 """ @staticmethod def correlation_matrix(data): """ calculates the correlation matrix of the given list. :param data: the given list, list. :return: the correlation matrix of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] """ @staticmethod def standard_deviation(data): """ calculates the standard deviation of the given list. :param data: the given list, list. :return: the standard deviation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.standard_deviation([1, 2, 3]) 1.0 """ @staticmethod def z_score(data): """ calculates the z-score of the given list. :param data: the given list, list. :return: the z-score of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.z_score([1, 2, 3, 4]) [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225] """
def median(data): sorted_data = sorted(data) n = len(sorted_data) if n % 2 == 1: return sorted_data[n // 2] else: return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2
calculates the median of the given list.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given list, list. :return: the median of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.median([1, 2, 3, 4]) 2.5 """ sorted_data = sorted(data) n = len(sorted_data) if n % 2 == 1: return sorted_data[n // 2] else: return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2 @staticmethod def correlation(x, y): """ calculates the correlation of the given list. :param x: the given list, list. :param y: the given list, list. :return: the correlation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.correlation([1, 2, 3], [4, 5, 6]) 1.0 """ n = len(x) mean_x = sum(x) / n mean_y = sum(y) / n numerator = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y)) denominator = math.sqrt(sum((xi - mean_x) ** 2 for xi in x) * sum((yi - mean_y) ** 2 for yi in y)) if denominator == 0: return None return numerator / denominator @staticmethod def mean(data): """ calculates the mean of the given list. :param data: the given list, list. :return: the mean of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.mean([1, 2, 3]) 2.0 """ if len(data) == 0: return None return sum(data) / len(data) @staticmethod def correlation_matrix(data): """ calculates the correlation matrix of the given list. :param data: the given list, list. :return: the correlation matrix of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] """ matrix = [] for i in range(len(data[0])): row = [] for j in range(len(data[0])): column1 = [row[i] for row in data] column2 = [row[j] for row in data] correlation = Statistics3.correlation(column1, column2) row.append(correlation) matrix.append(row) return matrix @staticmethod def standard_deviation(data): """ calculates the standard deviation of the given list. :param data: the given list, list. :return: the standard deviation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.standard_deviation([1, 2, 3]) 1.0 """ n = len(data) if n < 2: return None mean_value = Statistics3.mean(data) variance = sum((x - mean_value) ** 2 for x in data) / (n - 1) return math.sqrt(variance) @staticmethod def z_score(data): """ calculates the z-score of the given list. :param data: the given list, list. :return: the z-score of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.z_score([1, 2, 3, 4]) [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225] """ mean = Statistics3.mean(data) std_deviation = Statistics3.standard_deviation(data) if std_deviation is None or std_deviation == 0: return None return [(x - mean) / std_deviation for x in data]
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given list, list. :return: the median of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.median([1, 2, 3, 4]) 2.5 """ @staticmethod def correlation(x, y): """ calculates the correlation of the given list. :param x: the given list, list. :param y: the given list, list. :return: the correlation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.correlation([1, 2, 3], [4, 5, 6]) 1.0 """ @staticmethod def mean(data): """ calculates the mean of the given list. :param data: the given list, list. :return: the mean of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.mean([1, 2, 3]) 2.0 """ @staticmethod def correlation_matrix(data): """ calculates the correlation matrix of the given list. :param data: the given list, list. :return: the correlation matrix of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] """ @staticmethod def standard_deviation(data): """ calculates the standard deviation of the given list. :param data: the given list, list. :return: the standard deviation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.standard_deviation([1, 2, 3]) 1.0 """ @staticmethod def z_score(data): """ calculates the z-score of the given list. :param data: the given list, list. :return: the z-score of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.z_score([1, 2, 3, 4]) [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225] """
@staticmethod def mode(data): counts = {} for value in data: counts[value] = counts.get(value, 0) + 1 max_count = max(counts.values()) mode_values = [value for value, count in counts.items() if count == max_count] return mode_values
calculates the mode of the given list.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given list, list. :return: the median of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.median([1, 2, 3, 4]) 2.5 """ sorted_data = sorted(data) n = len(sorted_data) if n % 2 == 1: return sorted_data[n // 2] else: return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2 @staticmethod def mode(data): """ calculates the mode of the given list. :param data: the given list, list. :return: the mode of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.mode([1, 2, 3, 3]) [3] """ counts = {} for value in data: counts[value] = counts.get(value, 0) + 1 max_count = max(counts.values()) mode_values = [value for value, count in counts.items() if count == max_count] return mode_values @staticmethod def mean(data): """ calculates the mean of the given list. :param data: the given list, list. :return: the mean of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.mean([1, 2, 3]) 2.0 """ if len(data) == 0: return None return sum(data) / len(data) @staticmethod def correlation_matrix(data): """ calculates the correlation matrix of the given list. :param data: the given list, list. :return: the correlation matrix of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] """ matrix = [] for i in range(len(data[0])): row = [] for j in range(len(data[0])): column1 = [row[i] for row in data] column2 = [row[j] for row in data] correlation = Statistics3.correlation(column1, column2) row.append(correlation) matrix.append(row) return matrix @staticmethod def standard_deviation(data): """ calculates the standard deviation of the given list. :param data: the given list, list. :return: the standard deviation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.standard_deviation([1, 2, 3]) 1.0 """ n = len(data) if n < 2: return None mean_value = Statistics3.mean(data) variance = sum((x - mean_value) ** 2 for x in data) / (n - 1) return math.sqrt(variance) @staticmethod def z_score(data): """ calculates the z-score of the given list. :param data: the given list, list. :return: the z-score of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.z_score([1, 2, 3, 4]) [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225] """ mean = Statistics3.mean(data) std_deviation = Statistics3.standard_deviation(data) if std_deviation is None or std_deviation == 0: return None return [(x - mean) / std_deviation for x in data]
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given list, list. :return: the median of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.median([1, 2, 3, 4]) 2.5 """ @staticmethod def mode(data): """ calculates the mode of the given list. :param data: the given list, list. :return: the mode of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.mode([1, 2, 3, 3]) [3] """ @staticmethod def mean(data): """ calculates the mean of the given list. :param data: the given list, list. :return: the mean of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.mean([1, 2, 3]) 2.0 """ @staticmethod def correlation_matrix(data): """ calculates the correlation matrix of the given list. :param data: the given list, list. :return: the correlation matrix of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] """ @staticmethod def standard_deviation(data): """ calculates the standard deviation of the given list. :param data: the given list, list. :return: the standard deviation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.standard_deviation([1, 2, 3]) 1.0 """ @staticmethod def z_score(data): """ calculates the z-score of the given list. :param data: the given list, list. :return: the z-score of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.z_score([1, 2, 3, 4]) [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225] """
@staticmethod def correlation(x, y): n = len(x) mean_x = sum(x) / n mean_y = sum(y) / n numerator = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y)) denominator = math.sqrt(sum((xi - mean_x) ** 2 for xi in x) * sum((yi - mean_y) ** 2 for yi in y)) if denominator == 0: return None return numerator / denominator
calculates the correlation of the given list.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given list, list. :return: the median of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.median([1, 2, 3, 4]) 2.5 """ sorted_data = sorted(data) n = len(sorted_data) if n % 2 == 1: return sorted_data[n // 2] else: return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2 @staticmethod def mode(data): """ calculates the mode of the given list. :param data: the given list, list. :return: the mode of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.mode([1, 2, 3, 3]) [3] """ counts = {} for value in data: counts[value] = counts.get(value, 0) + 1 max_count = max(counts.values()) mode_values = [value for value, count in counts.items() if count == max_count] return mode_values @staticmethod def correlation(x, y): """ calculates the correlation of the given list. :param x: the given list, list. :param y: the given list, list. :return: the correlation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.correlation([1, 2, 3], [4, 5, 6]) 1.0 """ n = len(x) mean_x = sum(x) / n mean_y = sum(y) / n numerator = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y)) denominator = math.sqrt(sum((xi - mean_x) ** 2 for xi in x) * sum((yi - mean_y) ** 2 for yi in y)) if denominator == 0: return None return numerator / denominator @staticmethod def correlation_matrix(data): """ calculates the correlation matrix of the given list. :param data: the given list, list. :return: the correlation matrix of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] """ matrix = [] for i in range(len(data[0])): row = [] for j in range(len(data[0])): column1 = [row[i] for row in data] column2 = [row[j] for row in data] correlation = Statistics3.correlation(column1, column2) row.append(correlation) matrix.append(row) return matrix @staticmethod def standard_deviation(data): """ calculates the standard deviation of the given list. :param data: the given list, list. :return: the standard deviation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.standard_deviation([1, 2, 3]) 1.0 """ n = len(data) if n < 2: return None mean_value = Statistics3.mean(data) variance = sum((x - mean_value) ** 2 for x in data) / (n - 1) return math.sqrt(variance) @staticmethod def z_score(data): """ calculates the z-score of the given list. :param data: the given list, list. :return: the z-score of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.z_score([1, 2, 3, 4]) [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225] """ mean = Statistics3.mean(data) std_deviation = Statistics3.standard_deviation(data) if std_deviation is None or std_deviation == 0: return None return [(x - mean) / std_deviation for x in data]
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given list, list. :return: the median of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.median([1, 2, 3, 4]) 2.5 """ @staticmethod def mode(data): """ calculates the mode of the given list. :param data: the given list, list. :return: the mode of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.mode([1, 2, 3, 3]) [3] """ @staticmethod def correlation(x, y): """ calculates the correlation of the given list. :param x: the given list, list. :param y: the given list, list. :return: the correlation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.correlation([1, 2, 3], [4, 5, 6]) 1.0 """ @staticmethod def correlation_matrix(data): """ calculates the correlation matrix of the given list. :param data: the given list, list. :return: the correlation matrix of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] """ @staticmethod def standard_deviation(data): """ calculates the standard deviation of the given list. :param data: the given list, list. :return: the standard deviation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.standard_deviation([1, 2, 3]) 1.0 """ @staticmethod def z_score(data): """ calculates the z-score of the given list. :param data: the given list, list. :return: the z-score of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.z_score([1, 2, 3, 4]) [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225] """
@staticmethod def mean(data): if len(data) == 0: return None return sum(data) / len(data)
calculates the mean of the given list.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given list, list. :return: the median of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.median([1, 2, 3, 4]) 2.5 """ sorted_data = sorted(data) n = len(sorted_data) if n % 2 == 1: return sorted_data[n // 2] else: return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2 @staticmethod def mode(data): """ calculates the mode of the given list. :param data: the given list, list. :return: the mode of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.mode([1, 2, 3, 3]) [3] """ counts = {} for value in data: counts[value] = counts.get(value, 0) + 1 max_count = max(counts.values()) mode_values = [value for value, count in counts.items() if count == max_count] return mode_values @staticmethod def correlation(x, y): """ calculates the correlation of the given list. :param x: the given list, list. :param y: the given list, list. :return: the correlation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.correlation([1, 2, 3], [4, 5, 6]) 1.0 """ n = len(x) mean_x = sum(x) / n mean_y = sum(y) / n numerator = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y)) denominator = math.sqrt(sum((xi - mean_x) ** 2 for xi in x) * sum((yi - mean_y) ** 2 for yi in y)) if denominator == 0: return None return numerator / denominator @staticmethod def mean(data): """ calculates the mean of the given list. :param data: the given list, list. :return: the mean of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.mean([1, 2, 3]) 2.0 """ if len(data) == 0: return None return sum(data) / len(data) @staticmethod def standard_deviation(data): """ calculates the standard deviation of the given list. :param data: the given list, list. :return: the standard deviation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.standard_deviation([1, 2, 3]) 1.0 """ n = len(data) if n < 2: return None mean_value = Statistics3.mean(data) variance = sum((x - mean_value) ** 2 for x in data) / (n - 1) return math.sqrt(variance) @staticmethod def z_score(data): """ calculates the z-score of the given list. :param data: the given list, list. :return: the z-score of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.z_score([1, 2, 3, 4]) [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225] """ mean = Statistics3.mean(data) std_deviation = Statistics3.standard_deviation(data) if std_deviation is None or std_deviation == 0: return None return [(x - mean) / std_deviation for x in data]
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given list, list. :return: the median of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.median([1, 2, 3, 4]) 2.5 """ @staticmethod def mode(data): """ calculates the mode of the given list. :param data: the given list, list. :return: the mode of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.mode([1, 2, 3, 3]) [3] """ @staticmethod def correlation(x, y): """ calculates the correlation of the given list. :param x: the given list, list. :param y: the given list, list. :return: the correlation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.correlation([1, 2, 3], [4, 5, 6]) 1.0 """ @staticmethod def mean(data): """ calculates the mean of the given list. :param data: the given list, list. :return: the mean of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.mean([1, 2, 3]) 2.0 """ @staticmethod def standard_deviation(data): """ calculates the standard deviation of the given list. :param data: the given list, list. :return: the standard deviation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.standard_deviation([1, 2, 3]) 1.0 """ @staticmethod def z_score(data): """ calculates the z-score of the given list. :param data: the given list, list. :return: the z-score of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.z_score([1, 2, 3, 4]) [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225] """
@staticmethod def correlation_matrix(data): matrix = [] for i in range(len(data[0])): row = [] for j in range(len(data[0])): column1 = [row[i] for row in data] column2 = [row[j] for row in data] correlation = Statistics3.correlation(column1, column2) row.append(correlation) matrix.append(row) return matrix
calculates the correlation matrix of the given list.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given list, list. :return: the median of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.median([1, 2, 3, 4]) 2.5 """ sorted_data = sorted(data) n = len(sorted_data) if n % 2 == 1: return sorted_data[n // 2] else: return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2 @staticmethod def mode(data): """ calculates the mode of the given list. :param data: the given list, list. :return: the mode of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.mode([1, 2, 3, 3]) [3] """ counts = {} for value in data: counts[value] = counts.get(value, 0) + 1 max_count = max(counts.values()) mode_values = [value for value, count in counts.items() if count == max_count] return mode_values @staticmethod def correlation(x, y): """ calculates the correlation of the given list. :param x: the given list, list. :param y: the given list, list. :return: the correlation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.correlation([1, 2, 3], [4, 5, 6]) 1.0 """ n = len(x) mean_x = sum(x) / n mean_y = sum(y) / n numerator = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y)) denominator = math.sqrt(sum((xi - mean_x) ** 2 for xi in x) * sum((yi - mean_y) ** 2 for yi in y)) if denominator == 0: return None return numerator / denominator @staticmethod def mean(data): """ calculates the mean of the given list. :param data: the given list, list. :return: the mean of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.mean([1, 2, 3]) 2.0 """ if len(data) == 0: return None return sum(data) / len(data) @staticmethod def correlation_matrix(data): """ calculates the correlation matrix of the given list. :param data: the given list, list. :return: the correlation matrix of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] """ matrix = [] for i in range(len(data[0])): row = [] for j in range(len(data[0])): column1 = [row[i] for row in data] column2 = [row[j] for row in data] correlation = Statistics3.correlation(column1, column2) row.append(correlation) matrix.append(row) return matrix @staticmethod def z_score(data): """ calculates the z-score of the given list. :param data: the given list, list. :return: the z-score of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.z_score([1, 2, 3, 4]) [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225] """ mean = Statistics3.mean(data) std_deviation = Statistics3.standard_deviation(data) if std_deviation is None or std_deviation == 0: return None return [(x - mean) / std_deviation for x in data]
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given list, list. :return: the median of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.median([1, 2, 3, 4]) 2.5 """ @staticmethod def mode(data): """ calculates the mode of the given list. :param data: the given list, list. :return: the mode of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.mode([1, 2, 3, 3]) [3] """ @staticmethod def correlation(x, y): """ calculates the correlation of the given list. :param x: the given list, list. :param y: the given list, list. :return: the correlation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.correlation([1, 2, 3], [4, 5, 6]) 1.0 """ @staticmethod def mean(data): """ calculates the mean of the given list. :param data: the given list, list. :return: the mean of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.mean([1, 2, 3]) 2.0 """ @staticmethod def correlation_matrix(data): """ calculates the correlation matrix of the given list. :param data: the given list, list. :return: the correlation matrix of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] """ @staticmethod def z_score(data): """ calculates the z-score of the given list. :param data: the given list, list. :return: the z-score of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.z_score([1, 2, 3, 4]) [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225] """
@staticmethod def standard_deviation(data): n = len(data) if n < 2: return None mean_value = Statistics3.mean(data) variance = sum((x - mean_value) ** 2 for x in data) / (n - 1) return math.sqrt(variance)
calculates the standard deviation of the given list.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given list, list. :return: the median of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.median([1, 2, 3, 4]) 2.5 """ sorted_data = sorted(data) n = len(sorted_data) if n % 2 == 1: return sorted_data[n // 2] else: return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2 @staticmethod def mode(data): """ calculates the mode of the given list. :param data: the given list, list. :return: the mode of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.mode([1, 2, 3, 3]) [3] """ counts = {} for value in data: counts[value] = counts.get(value, 0) + 1 max_count = max(counts.values()) mode_values = [value for value, count in counts.items() if count == max_count] return mode_values @staticmethod def correlation(x, y): """ calculates the correlation of the given list. :param x: the given list, list. :param y: the given list, list. :return: the correlation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.correlation([1, 2, 3], [4, 5, 6]) 1.0 """ n = len(x) mean_x = sum(x) / n mean_y = sum(y) / n numerator = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y)) denominator = math.sqrt(sum((xi - mean_x) ** 2 for xi in x) * sum((yi - mean_y) ** 2 for yi in y)) if denominator == 0: return None return numerator / denominator @staticmethod def mean(data): """ calculates the mean of the given list. :param data: the given list, list. :return: the mean of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.mean([1, 2, 3]) 2.0 """ if len(data) == 0: return None return sum(data) / len(data) @staticmethod def correlation_matrix(data): """ calculates the correlation matrix of the given list. :param data: the given list, list. :return: the correlation matrix of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] """ matrix = [] for i in range(len(data[0])): row = [] for j in range(len(data[0])): column1 = [row[i] for row in data] column2 = [row[j] for row in data] correlation = Statistics3.correlation(column1, column2) row.append(correlation) matrix.append(row) return matrix @staticmethod def standard_deviation(data): """ calculates the standard deviation of the given list. :param data: the given list, list. :return: the standard deviation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.standard_deviation([1, 2, 3]) 1.0 """ n = len(data) if n < 2: return None mean_value = Statistics3.mean(data) variance = sum((x - mean_value) ** 2 for x in data) / (n - 1) return math.sqrt(variance) @staticmethod def z_score(data): mean = Statistics3.mean(data) std_deviation = Statistics3.standard_deviation(data) if std_deviation is None or std_deviation == 0: return None return [(x - mean) / std_deviation for x in data]
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given list, list. :return: the median of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.median([1, 2, 3, 4]) 2.5 """ @staticmethod def mode(data): """ calculates the mode of the given list. :param data: the given list, list. :return: the mode of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.mode([1, 2, 3, 3]) [3] """ @staticmethod def correlation(x, y): """ calculates the correlation of the given list. :param x: the given list, list. :param y: the given list, list. :return: the correlation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.correlation([1, 2, 3], [4, 5, 6]) 1.0 """ @staticmethod def mean(data): """ calculates the mean of the given list. :param data: the given list, list. :return: the mean of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.mean([1, 2, 3]) 2.0 """ @staticmethod def correlation_matrix(data): """ calculates the correlation matrix of the given list. :param data: the given list, list. :return: the correlation matrix of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] """ @staticmethod def standard_deviation(data): """ calculates the standard deviation of the given list. :param data: the given list, list. :return: the standard deviation of the given list, float. >>> statistics3 = Statistics3() >>> statistics3.standard_deviation([1, 2, 3]) 1.0 """ @staticmethod def z_score(data): """ calculates the z-score of the given list. :param data: the given list, list. :return: the z-score of the given list, list. >>> statistics3 = Statistics3() >>> statistics3.z_score([1, 2, 3, 4]) [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225] """
@staticmethod def z_score(data): mean = Statistics3.mean(data) std_deviation = Statistics3.standard_deviation(data) if std_deviation is None or std_deviation == 0: return None return [(x - mean) / std_deviation for x in data]
calculates the z-score of the given list.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.cash_balance = cash_balance def remove_stock(self, stock): """ Remove a stock from the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ for pf in self.portfolio: if pf['name'] == stock['name'] and pf['quantity'] >= stock['quantity']: pf['quantity'] -= stock['quantity'] if pf['quantity'] == 0: self.portfolio.remove(pf) return True return False def buy_stock(self, stock): """ Buy a stock and add it to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to buy,int. :return: True if the stock was bought successfully, False if the cash balance is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ if stock['price'] * stock['quantity'] > self.cash_balance: return False else: self.add_stock(stock) self.cash_balance -= stock['price'] * stock['quantity'] return True def sell_stock(self, stock): """ Sell a stock and remove it from the portfolio and add the cash to the cash balance. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to sell,int. :return: True if the stock was sold successfully, False if the quantity of the stock is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ if self.remove_stock(stock) == False: return False self.cash_balance += stock['price'] * stock['quantity'] return True def calculate_portfolio_value(self): """ Calculate the total value of the portfolio. :return: the total value of the portfolio, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.calculate_portfolio_value() 11500.0 """ total_value = self.cash_balance for stock in self.portfolio: total_value += stock['price'] * stock['quantity'] return total_value def get_portfolio_summary(self): """ Get a summary of the portfolio. :return: a tuple of the total value of the portfolio and a list of dictionaries with keys "name" and "value" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.get_portfolio_summary() (11500.0, [{'name': 'AAPL', 'value': 1500.0}]) """ summary = [] for stock in self.portfolio: value = self.get_stock_value(stock) summary.append({"name": stock["name"], "value": value}) portfolio_value = self.calculate_portfolio_value() return portfolio_value, summary def get_stock_value(self, stock): """ Get the value of a stock. :param stock: a dictionary with keys "name", "price", and "quantity" :return: the value of the stock, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}) 1500.0 """ return stock['price'] * stock['quantity']
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockPortfolioTracker class with a cash balance and an empty portfolio. """ self.portfolio = [] self.cash_balance = cash_balance def remove_stock(self, stock): """ Remove a stock from the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ def buy_stock(self, stock): """ Buy a stock and add it to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to buy,int. :return: True if the stock was bought successfully, False if the cash balance is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ def sell_stock(self, stock): """ Sell a stock and remove it from the portfolio and add the cash to the cash balance. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to sell,int. :return: True if the stock was sold successfully, False if the quantity of the stock is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ def calculate_portfolio_value(self): """ Calculate the total value of the portfolio. :return: the total value of the portfolio, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.calculate_portfolio_value() 11500.0 """ def get_portfolio_summary(self): """ Get a summary of the portfolio. :return: a tuple of the total value of the portfolio and a list of dictionaries with keys "name" and "value" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.get_portfolio_summary() (11500.0, [{'name': 'AAPL', 'value': 1500.0}]) """ def get_stock_value(self, stock): """ Get the value of a stock. :param stock: a dictionary with keys "name", "price", and "quantity" :return: the value of the stock, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}) 1500.0 """
def add_stock(self, stock): for pf in self.portfolio: if pf['name'] == stock['name']: pf['quantity'] += stock['quantity'] return self.portfolio.append(stock)
Add a stock to the portfolio.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.cash_balance = cash_balance def add_stock(self, stock): """ Add a stock to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ for pf in self.portfolio: if pf['name'] == stock['name']: pf['quantity'] += stock['quantity'] return self.portfolio.append(stock) def buy_stock(self, stock): """ Buy a stock and add it to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to buy,int. :return: True if the stock was bought successfully, False if the cash balance is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ if stock['price'] * stock['quantity'] > self.cash_balance: return False else: self.add_stock(stock) self.cash_balance -= stock['price'] * stock['quantity'] return True def sell_stock(self, stock): """ Sell a stock and remove it from the portfolio and add the cash to the cash balance. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to sell,int. :return: True if the stock was sold successfully, False if the quantity of the stock is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ if self.remove_stock(stock) == False: return False self.cash_balance += stock['price'] * stock['quantity'] return True def calculate_portfolio_value(self): """ Calculate the total value of the portfolio. :return: the total value of the portfolio, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.calculate_portfolio_value() 11500.0 """ total_value = self.cash_balance for stock in self.portfolio: total_value += stock['price'] * stock['quantity'] return total_value def get_portfolio_summary(self): """ Get a summary of the portfolio. :return: a tuple of the total value of the portfolio and a list of dictionaries with keys "name" and "value" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.get_portfolio_summary() (11500.0, [{'name': 'AAPL', 'value': 1500.0}]) """ summary = [] for stock in self.portfolio: value = self.get_stock_value(stock) summary.append({"name": stock["name"], "value": value}) portfolio_value = self.calculate_portfolio_value() return portfolio_value, summary def get_stock_value(self, stock): """ Get the value of a stock. :param stock: a dictionary with keys "name", "price", and "quantity" :return: the value of the stock, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}) 1500.0 """ return stock['price'] * stock['quantity']
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockPortfolioTracker class with a cash balance and an empty portfolio. """ self.portfolio = [] self.cash_balance = cash_balance def add_stock(self, stock): """ Add a stock to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ def buy_stock(self, stock): """ Buy a stock and add it to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to buy,int. :return: True if the stock was bought successfully, False if the cash balance is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ def sell_stock(self, stock): """ Sell a stock and remove it from the portfolio and add the cash to the cash balance. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to sell,int. :return: True if the stock was sold successfully, False if the quantity of the stock is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ def calculate_portfolio_value(self): """ Calculate the total value of the portfolio. :return: the total value of the portfolio, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.calculate_portfolio_value() 11500.0 """ def get_portfolio_summary(self): """ Get a summary of the portfolio. :return: a tuple of the total value of the portfolio and a list of dictionaries with keys "name" and "value" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.get_portfolio_summary() (11500.0, [{'name': 'AAPL', 'value': 1500.0}]) """ def get_stock_value(self, stock): """ Get the value of a stock. :param stock: a dictionary with keys "name", "price", and "quantity" :return: the value of the stock, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}) 1500.0 """
def remove_stock(self, stock): for pf in self.portfolio: if pf['name'] == stock['name'] and pf['quantity'] >= stock['quantity']: pf['quantity'] -= stock['quantity'] if pf['quantity'] == 0: self.portfolio.remove(pf) return True return False
Remove a stock from the portfolio.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.cash_balance = cash_balance def add_stock(self, stock): """ Add a stock to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ for pf in self.portfolio: if pf['name'] == stock['name']: pf['quantity'] += stock['quantity'] return self.portfolio.append(stock) def remove_stock(self, stock): """ Remove a stock from the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ for pf in self.portfolio: if pf['name'] == stock['name'] and pf['quantity'] >= stock['quantity']: pf['quantity'] -= stock['quantity'] if pf['quantity'] == 0: self.portfolio.remove(pf) return True return False def sell_stock(self, stock): """ Sell a stock and remove it from the portfolio and add the cash to the cash balance. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to sell,int. :return: True if the stock was sold successfully, False if the quantity of the stock is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ if self.remove_stock(stock) == False: return False self.cash_balance += stock['price'] * stock['quantity'] return True def calculate_portfolio_value(self): """ Calculate the total value of the portfolio. :return: the total value of the portfolio, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.calculate_portfolio_value() 11500.0 """ total_value = self.cash_balance for stock in self.portfolio: total_value += stock['price'] * stock['quantity'] return total_value def get_portfolio_summary(self): """ Get a summary of the portfolio. :return: a tuple of the total value of the portfolio and a list of dictionaries with keys "name" and "value" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.get_portfolio_summary() (11500.0, [{'name': 'AAPL', 'value': 1500.0}]) """ summary = [] for stock in self.portfolio: value = self.get_stock_value(stock) summary.append({"name": stock["name"], "value": value}) portfolio_value = self.calculate_portfolio_value() return portfolio_value, summary def get_stock_value(self, stock): """ Get the value of a stock. :param stock: a dictionary with keys "name", "price", and "quantity" :return: the value of the stock, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}) 1500.0 """ return stock['price'] * stock['quantity']
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockPortfolioTracker class with a cash balance and an empty portfolio. """ self.portfolio = [] self.cash_balance = cash_balance def add_stock(self, stock): """ Add a stock to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ def remove_stock(self, stock): """ Remove a stock from the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ def sell_stock(self, stock): """ Sell a stock and remove it from the portfolio and add the cash to the cash balance. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to sell,int. :return: True if the stock was sold successfully, False if the quantity of the stock is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ def calculate_portfolio_value(self): """ Calculate the total value of the portfolio. :return: the total value of the portfolio, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.calculate_portfolio_value() 11500.0 """ def get_portfolio_summary(self): """ Get a summary of the portfolio. :return: a tuple of the total value of the portfolio and a list of dictionaries with keys "name" and "value" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.get_portfolio_summary() (11500.0, [{'name': 'AAPL', 'value': 1500.0}]) """ def get_stock_value(self, stock): """ Get the value of a stock. :param stock: a dictionary with keys "name", "price", and "quantity" :return: the value of the stock, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}) 1500.0 """
def buy_stock(self, stock): if stock['price'] * stock['quantity'] > self.cash_balance: return False else: self.add_stock(stock) self.cash_balance -= stock['price'] * stock['quantity'] return True
Buy a stock and add it to the portfolio.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.cash_balance = cash_balance def add_stock(self, stock): """ Add a stock to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ for pf in self.portfolio: if pf['name'] == stock['name']: pf['quantity'] += stock['quantity'] return self.portfolio.append(stock) def remove_stock(self, stock): """ Remove a stock from the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ for pf in self.portfolio: if pf['name'] == stock['name'] and pf['quantity'] >= stock['quantity']: pf['quantity'] -= stock['quantity'] if pf['quantity'] == 0: self.portfolio.remove(pf) return True return False def buy_stock(self, stock): """ Buy a stock and add it to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to buy,int. :return: True if the stock was bought successfully, False if the cash balance is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ if stock['price'] * stock['quantity'] > self.cash_balance: return False else: self.add_stock(stock) self.cash_balance -= stock['price'] * stock['quantity'] return True def calculate_portfolio_value(self): """ Calculate the total value of the portfolio. :return: the total value of the portfolio, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.calculate_portfolio_value() 11500.0 """ total_value = self.cash_balance for stock in self.portfolio: total_value += stock['price'] * stock['quantity'] return total_value def get_portfolio_summary(self): """ Get a summary of the portfolio. :return: a tuple of the total value of the portfolio and a list of dictionaries with keys "name" and "value" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.get_portfolio_summary() (11500.0, [{'name': 'AAPL', 'value': 1500.0}]) """ summary = [] for stock in self.portfolio: value = self.get_stock_value(stock) summary.append({"name": stock["name"], "value": value}) portfolio_value = self.calculate_portfolio_value() return portfolio_value, summary def get_stock_value(self, stock): """ Get the value of a stock. :param stock: a dictionary with keys "name", "price", and "quantity" :return: the value of the stock, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}) 1500.0 """ return stock['price'] * stock['quantity']
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockPortfolioTracker class with a cash balance and an empty portfolio. """ self.portfolio = [] self.cash_balance = cash_balance def add_stock(self, stock): """ Add a stock to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ def remove_stock(self, stock): """ Remove a stock from the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ def buy_stock(self, stock): """ Buy a stock and add it to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to buy,int. :return: True if the stock was bought successfully, False if the cash balance is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ def calculate_portfolio_value(self): """ Calculate the total value of the portfolio. :return: the total value of the portfolio, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.calculate_portfolio_value() 11500.0 """ def get_portfolio_summary(self): """ Get a summary of the portfolio. :return: a tuple of the total value of the portfolio and a list of dictionaries with keys "name" and "value" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.get_portfolio_summary() (11500.0, [{'name': 'AAPL', 'value': 1500.0}]) """ def get_stock_value(self, stock): """ Get the value of a stock. :param stock: a dictionary with keys "name", "price", and "quantity" :return: the value of the stock, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}) 1500.0 """
def sell_stock(self, stock): if self.remove_stock(stock) == False: return False self.cash_balance += stock['price'] * stock['quantity'] return True
Sell a stock and remove it from the portfolio and add the cash to the cash balance.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.cash_balance = cash_balance def add_stock(self, stock): """ Add a stock to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ for pf in self.portfolio: if pf['name'] == stock['name']: pf['quantity'] += stock['quantity'] return self.portfolio.append(stock) def remove_stock(self, stock): """ Remove a stock from the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ for pf in self.portfolio: if pf['name'] == stock['name'] and pf['quantity'] >= stock['quantity']: pf['quantity'] -= stock['quantity'] if pf['quantity'] == 0: self.portfolio.remove(pf) return True return False def buy_stock(self, stock): """ Buy a stock and add it to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to buy,int. :return: True if the stock was bought successfully, False if the cash balance is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ if stock['price'] * stock['quantity'] > self.cash_balance: return False else: self.add_stock(stock) self.cash_balance -= stock['price'] * stock['quantity'] return True def sell_stock(self, stock): """ Sell a stock and remove it from the portfolio and add the cash to the cash balance. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to sell,int. :return: True if the stock was sold successfully, False if the quantity of the stock is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ if self.remove_stock(stock) == False: return False self.cash_balance += stock['price'] * stock['quantity'] return True def get_portfolio_summary(self): """ Get a summary of the portfolio. :return: a tuple of the total value of the portfolio and a list of dictionaries with keys "name" and "value" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.get_portfolio_summary() (11500.0, [{'name': 'AAPL', 'value': 1500.0}]) """ summary = [] for stock in self.portfolio: value = self.get_stock_value(stock) summary.append({"name": stock["name"], "value": value}) portfolio_value = self.calculate_portfolio_value() return portfolio_value, summary def get_stock_value(self, stock): """ Get the value of a stock. :param stock: a dictionary with keys "name", "price", and "quantity" :return: the value of the stock, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}) 1500.0 """ return stock['price'] * stock['quantity']
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockPortfolioTracker class with a cash balance and an empty portfolio. """ self.portfolio = [] self.cash_balance = cash_balance def add_stock(self, stock): """ Add a stock to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ def remove_stock(self, stock): """ Remove a stock from the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ def buy_stock(self, stock): """ Buy a stock and add it to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to buy,int. :return: True if the stock was bought successfully, False if the cash balance is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ def sell_stock(self, stock): """ Sell a stock and remove it from the portfolio and add the cash to the cash balance. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to sell,int. :return: True if the stock was sold successfully, False if the quantity of the stock is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ def get_portfolio_summary(self): """ Get a summary of the portfolio. :return: a tuple of the total value of the portfolio and a list of dictionaries with keys "name" and "value" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.get_portfolio_summary() (11500.0, [{'name': 'AAPL', 'value': 1500.0}]) """ def get_stock_value(self, stock): """ Get the value of a stock. :param stock: a dictionary with keys "name", "price", and "quantity" :return: the value of the stock, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}) 1500.0 """
def calculate_portfolio_value(self): total_value = self.cash_balance for stock in self.portfolio: total_value += stock['price'] * stock['quantity'] return total_value
Calculate the total value of the portfolio.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.cash_balance = cash_balance def add_stock(self, stock): """ Add a stock to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ for pf in self.portfolio: if pf['name'] == stock['name']: pf['quantity'] += stock['quantity'] return self.portfolio.append(stock) def remove_stock(self, stock): """ Remove a stock from the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ for pf in self.portfolio: if pf['name'] == stock['name'] and pf['quantity'] >= stock['quantity']: pf['quantity'] -= stock['quantity'] if pf['quantity'] == 0: self.portfolio.remove(pf) return True return False def buy_stock(self, stock): """ Buy a stock and add it to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to buy,int. :return: True if the stock was bought successfully, False if the cash balance is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ if stock['price'] * stock['quantity'] > self.cash_balance: return False else: self.add_stock(stock) self.cash_balance -= stock['price'] * stock['quantity'] return True def sell_stock(self, stock): """ Sell a stock and remove it from the portfolio and add the cash to the cash balance. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to sell,int. :return: True if the stock was sold successfully, False if the quantity of the stock is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ if self.remove_stock(stock) == False: return False self.cash_balance += stock['price'] * stock['quantity'] return True def calculate_portfolio_value(self): """ Calculate the total value of the portfolio. :return: the total value of the portfolio, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.calculate_portfolio_value() 11500.0 """ total_value = self.cash_balance for stock in self.portfolio: total_value += stock['price'] * stock['quantity'] return total_value def get_stock_value(self, stock): """ Get the value of a stock. :param stock: a dictionary with keys "name", "price", and "quantity" :return: the value of the stock, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}) 1500.0 """ return stock['price'] * stock['quantity']
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockPortfolioTracker class with a cash balance and an empty portfolio. """ self.portfolio = [] self.cash_balance = cash_balance def add_stock(self, stock): """ Add a stock to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ def remove_stock(self, stock): """ Remove a stock from the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ def buy_stock(self, stock): """ Buy a stock and add it to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to buy,int. :return: True if the stock was bought successfully, False if the cash balance is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ def sell_stock(self, stock): """ Sell a stock and remove it from the portfolio and add the cash to the cash balance. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to sell,int. :return: True if the stock was sold successfully, False if the quantity of the stock is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ def calculate_portfolio_value(self): """ Calculate the total value of the portfolio. :return: the total value of the portfolio, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.calculate_portfolio_value() 11500.0 """ def get_stock_value(self, stock): """ Get the value of a stock. :param stock: a dictionary with keys "name", "price", and "quantity" :return: the value of the stock, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}) 1500.0 """
def get_portfolio_summary(self): summary = [] for stock in self.portfolio: value = self.get_stock_value(stock) summary.append({"name": stock["name"], "value": value}) portfolio_value = self.calculate_portfolio_value() return portfolio_value, summary
Get a summary of the portfolio.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.cash_balance = cash_balance def add_stock(self, stock): """ Add a stock to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ for pf in self.portfolio: if pf['name'] == stock['name']: pf['quantity'] += stock['quantity'] return self.portfolio.append(stock) def remove_stock(self, stock): """ Remove a stock from the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ for pf in self.portfolio: if pf['name'] == stock['name'] and pf['quantity'] >= stock['quantity']: pf['quantity'] -= stock['quantity'] if pf['quantity'] == 0: self.portfolio.remove(pf) return True return False def buy_stock(self, stock): """ Buy a stock and add it to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to buy,int. :return: True if the stock was bought successfully, False if the cash balance is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ if stock['price'] * stock['quantity'] > self.cash_balance: return False else: self.add_stock(stock) self.cash_balance -= stock['price'] * stock['quantity'] return True def sell_stock(self, stock): """ Sell a stock and remove it from the portfolio and add the cash to the cash balance. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to sell,int. :return: True if the stock was sold successfully, False if the quantity of the stock is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ if self.remove_stock(stock) == False: return False self.cash_balance += stock['price'] * stock['quantity'] return True def calculate_portfolio_value(self): """ Calculate the total value of the portfolio. :return: the total value of the portfolio, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.calculate_portfolio_value() 11500.0 """ total_value = self.cash_balance for stock in self.portfolio: total_value += stock['price'] * stock['quantity'] return total_value def get_portfolio_summary(self): """ Get a summary of the portfolio. :return: a tuple of the total value of the portfolio and a list of dictionaries with keys "name" and "value" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.get_portfolio_summary() (11500.0, [{'name': 'AAPL', 'value': 1500.0}]) """ summary = [] for stock in self.portfolio: value = self.get_stock_value(stock) summary.append({"name": stock["name"], "value": value}) portfolio_value = self.calculate_portfolio_value() return portfolio_value, summary def get_stock_value(self, stock): return stock['price'] * stock['quantity']
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockPortfolioTracker class with a cash balance and an empty portfolio. """ self.portfolio = [] self.cash_balance = cash_balance def add_stock(self, stock): """ Add a stock to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.add_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ def remove_stock(self, stock): """ Remove a stock from the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.remove_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ def buy_stock(self, stock): """ Buy a stock and add it to the portfolio. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to buy,int. :return: True if the stock was bought successfully, False if the cash balance is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.buy_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] """ def sell_stock(self, stock): """ Sell a stock and remove it from the portfolio and add the cash to the cash balance. :param stock: a dictionary with keys "name", "price", and "quantity" :param quantity: the quantity of the stock to sell,int. :return: True if the stock was sold successfully, False if the quantity of the stock is not enough. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.sell_stock({"name": "AAPL", "price": 150.0, "quantity": 10}) True >>> tracker.portfolio [] """ def calculate_portfolio_value(self): """ Calculate the total value of the portfolio. :return: the total value of the portfolio, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.calculate_portfolio_value() 11500.0 """ def get_portfolio_summary(self): """ Get a summary of the portfolio. :return: a tuple of the total value of the portfolio and a list of dictionaries with keys "name" and "value" >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}] >>> tracker.get_portfolio_summary() (11500.0, [{'name': 'AAPL', 'value': 1500.0}]) """ def get_stock_value(self, stock): """ Get the value of a stock. :param stock: a dictionary with keys "name", "price", and "quantity" :return: the value of the stock, float. >>> tracker = StockPortfolioTracker(10000.0) >>> tracker.get_stock_value({"name": "AAPL", "price": 150.0, "quantity": 10}) 1500.0 """
def get_stock_value(self, stock): return stock['price'] * stock['quantity']
Get the value of a stock.
ClassEval_83_sum
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): self.database_name = database_name def insert_student(self, student_data): """ Inserts a new student into the "students" table. :param student_data: dict, a dictionary containing the student's information (name, age, gender, grade). :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9} >>> processor.insert_student(student_data) """ conn = sqlite3.connect(self.database_name) cursor = conn.cursor() insert_query = """ INSERT INTO students (name, age, gender, grade) VALUES (?, ?, ?, ?) """ cursor.execute(insert_query, (student_data['name'], student_data['age'], student_data['gender'], student_data['grade'])) conn.commit() conn.close() def search_student_by_name(self, name): """ Searches for a student in the "students" table by their name. :param name: str, the name of the student to search for. :return: list of tuples, the rows from the "students" table that match the search criteria. >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> result = processor.search_student_by_name("John") """ conn = sqlite3.connect(self.database_name) cursor = conn.cursor() select_query = "SELECT * FROM students WHERE name = ?" cursor.execute(select_query, (name,)) result = cursor.fetchall() conn.close() return result def delete_student_by_name(self, name): """ Deletes a student from the "students" table by their name. :param name: str, the name of the student to delete. :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9} >>> processor.insert_student(student_data) >>> processor.delete_student_by_name("John") """ conn = sqlite3.connect(self.database_name) cursor = conn.cursor() delete_query = "DELETE FROM students WHERE name = ?" cursor.execute(delete_query, (name,)) conn.commit() conn.close()
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): """ Initializes the StudentDatabaseProcessor object with the specified database name. :param database_name: str, the name of the SQLite database. """ self.database_name = database_name def insert_student(self, student_data): """ Inserts a new student into the "students" table. :param student_data: dict, a dictionary containing the student's information (name, age, gender, grade). :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9} >>> processor.insert_student(student_data) """ def search_student_by_name(self, name): """ Searches for a student in the "students" table by their name. :param name: str, the name of the student to search for. :return: list of tuples, the rows from the "students" table that match the search criteria. >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> result = processor.search_student_by_name("John") """ def delete_student_by_name(self, name): """ Deletes a student from the "students" table by their name. :param name: str, the name of the student to delete. :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9} >>> processor.insert_student(student_data) >>> processor.delete_student_by_name("John") """
def create_student_table(self): conn = sqlite3.connect(self.database_name) cursor = conn.cursor() create_table_query = """ CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER, gender TEXT, grade INTEGER ) """ cursor.execute(create_table_query) conn.commit() conn.close()
Creates a "students" table in the database if it does not exist already.Fields include ID of type int, name of type str, age of type int, gender of type str, and grade of type int
ClassEval_83_sum
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): self.database_name = database_name def create_student_table(self): """ Creates a "students" table in the database if it does not exist already.Fields include ID of type int, name of type str, age of type int, gender of type str, and grade of type int :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() """ conn = sqlite3.connect(self.database_name) cursor = conn.cursor() create_table_query = """ CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER, gender TEXT, grade INTEGER ) """ cursor.execute(create_table_query) conn.commit() conn.close() def search_student_by_name(self, name): """ Searches for a student in the "students" table by their name. :param name: str, the name of the student to search for. :return: list of tuples, the rows from the "students" table that match the search criteria. >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> result = processor.search_student_by_name("John") """ conn = sqlite3.connect(self.database_name) cursor = conn.cursor() select_query = "SELECT * FROM students WHERE name = ?" cursor.execute(select_query, (name,)) result = cursor.fetchall() conn.close() return result def delete_student_by_name(self, name): """ Deletes a student from the "students" table by their name. :param name: str, the name of the student to delete. :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9} >>> processor.insert_student(student_data) >>> processor.delete_student_by_name("John") """ conn = sqlite3.connect(self.database_name) cursor = conn.cursor() delete_query = "DELETE FROM students WHERE name = ?" cursor.execute(delete_query, (name,)) conn.commit() conn.close()
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): """ Initializes the StudentDatabaseProcessor object with the specified database name. :param database_name: str, the name of the SQLite database. """ self.database_name = database_name def create_student_table(self): """ Creates a "students" table in the database if it does not exist already.Fields include ID of type int, name of type str, age of type int, gender of type str, and grade of type int :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() """ def search_student_by_name(self, name): """ Searches for a student in the "students" table by their name. :param name: str, the name of the student to search for. :return: list of tuples, the rows from the "students" table that match the search criteria. >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> result = processor.search_student_by_name("John") """ def delete_student_by_name(self, name): """ Deletes a student from the "students" table by their name. :param name: str, the name of the student to delete. :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9} >>> processor.insert_student(student_data) >>> processor.delete_student_by_name("John") """
def insert_student(self, student_data): conn = sqlite3.connect(self.database_name) cursor = conn.cursor() insert_query = """ INSERT INTO students (name, age, gender, grade) VALUES (?, ?, ?, ?) """ cursor.execute(insert_query, (student_data['name'], student_data['age'], student_data['gender'], student_data['grade'])) conn.commit() conn.close()
Inserts a new student into the "students" table.
ClassEval_83_sum
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): self.database_name = database_name def create_student_table(self): """ Creates a "students" table in the database if it does not exist already.Fields include ID of type int, name of type str, age of type int, gender of type str, and grade of type int :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() """ conn = sqlite3.connect(self.database_name) cursor = conn.cursor() create_table_query = """ CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER, gender TEXT, grade INTEGER ) """ cursor.execute(create_table_query) conn.commit() conn.close() def insert_student(self, student_data): """ Inserts a new student into the "students" table. :param student_data: dict, a dictionary containing the student's information (name, age, gender, grade). :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9} >>> processor.insert_student(student_data) """ conn = sqlite3.connect(self.database_name) cursor = conn.cursor() insert_query = """ INSERT INTO students (name, age, gender, grade) VALUES (?, ?, ?, ?) """ cursor.execute(insert_query, (student_data['name'], student_data['age'], student_data['gender'], student_data['grade'])) conn.commit() conn.close() def delete_student_by_name(self, name): """ Deletes a student from the "students" table by their name. :param name: str, the name of the student to delete. :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9} >>> processor.insert_student(student_data) >>> processor.delete_student_by_name("John") """ conn = sqlite3.connect(self.database_name) cursor = conn.cursor() delete_query = "DELETE FROM students WHERE name = ?" cursor.execute(delete_query, (name,)) conn.commit() conn.close()
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): """ Initializes the StudentDatabaseProcessor object with the specified database name. :param database_name: str, the name of the SQLite database. """ self.database_name = database_name def create_student_table(self): """ Creates a "students" table in the database if it does not exist already.Fields include ID of type int, name of type str, age of type int, gender of type str, and grade of type int :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() """ def insert_student(self, student_data): """ Inserts a new student into the "students" table. :param student_data: dict, a dictionary containing the student's information (name, age, gender, grade). :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9} >>> processor.insert_student(student_data) """ def delete_student_by_name(self, name): """ Deletes a student from the "students" table by their name. :param name: str, the name of the student to delete. :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9} >>> processor.insert_student(student_data) >>> processor.delete_student_by_name("John") """
def search_student_by_name(self, name): conn = sqlite3.connect(self.database_name) cursor = conn.cursor() select_query = "SELECT * FROM students WHERE name = ?" cursor.execute(select_query, (name,)) result = cursor.fetchall() conn.close() return result
Searches for a student in the "students" table by their name.
ClassEval_83_sum
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): self.database_name = database_name def create_student_table(self): """ Creates a "students" table in the database if it does not exist already.Fields include ID of type int, name of type str, age of type int, gender of type str, and grade of type int :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() """ conn = sqlite3.connect(self.database_name) cursor = conn.cursor() create_table_query = """ CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER, gender TEXT, grade INTEGER ) """ cursor.execute(create_table_query) conn.commit() conn.close() def insert_student(self, student_data): """ Inserts a new student into the "students" table. :param student_data: dict, a dictionary containing the student's information (name, age, gender, grade). :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9} >>> processor.insert_student(student_data) """ conn = sqlite3.connect(self.database_name) cursor = conn.cursor() insert_query = """ INSERT INTO students (name, age, gender, grade) VALUES (?, ?, ?, ?) """ cursor.execute(insert_query, (student_data['name'], student_data['age'], student_data['gender'], student_data['grade'])) conn.commit() conn.close() def search_student_by_name(self, name): """ Searches for a student in the "students" table by their name. :param name: str, the name of the student to search for. :return: list of tuples, the rows from the "students" table that match the search criteria. >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> result = processor.search_student_by_name("John") """ conn = sqlite3.connect(self.database_name) cursor = conn.cursor() select_query = "SELECT * FROM students WHERE name = ?" cursor.execute(select_query, (name,)) result = cursor.fetchall() conn.close() return result def delete_student_by_name(self, name): conn = sqlite3.connect(self.database_name) cursor = conn.cursor() delete_query = "DELETE FROM students WHERE name = ?" cursor.execute(delete_query, (name,)) conn.commit() conn.close()
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): """ Initializes the StudentDatabaseProcessor object with the specified database name. :param database_name: str, the name of the SQLite database. """ self.database_name = database_name def create_student_table(self): """ Creates a "students" table in the database if it does not exist already.Fields include ID of type int, name of type str, age of type int, gender of type str, and grade of type int :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() """ def insert_student(self, student_data): """ Inserts a new student into the "students" table. :param student_data: dict, a dictionary containing the student's information (name, age, gender, grade). :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9} >>> processor.insert_student(student_data) """ def search_student_by_name(self, name): """ Searches for a student in the "students" table by their name. :param name: str, the name of the student to search for. :return: list of tuples, the rows from the "students" table that match the search criteria. >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> result = processor.search_student_by_name("John") """ def delete_student_by_name(self, name): """ Deletes a student from the "students" table by their name. :param name: str, the name of the student to delete. :return: None >>> processor = StudentDatabaseProcessor("students.db") >>> processor.create_student_table() >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9} >>> processor.insert_student(student_data) >>> processor.delete_student_by_name("John") """
def delete_student_by_name(self, name): conn = sqlite3.connect(self.database_name) cursor = conn.cursor() delete_query = "DELETE FROM students WHERE name = ?" cursor.execute(delete_query, (name,)) conn.commit() conn.close()
Deletes a student from the "students" table by their name.
ClassEval_84_sum
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): self.file_path = file_path def read_file(self): """ Read the return the content of self.file_path file. :return: the same return as the read() method >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file() '{\n "name": "test",\n "age": 12\n}' """ with open(self.file_path, 'r') as file: return file.read() def write_file(self, content): """ Write content into the self.file_path file, and overwrite if the file has already existed. :param content: any content >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.write_file('Hello world!') >>> textFileProcessor.read_file() 'Hello world!' """ with open(self.file_path, 'w') as file: file.write(content) def process_file(self): """ Read the self.file_path file and filter out non-alphabetic characters from the content string. Overwrite the after-processed data into the same self.file_path file. >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file() '{\n "name": "test",\n "age": 12\n}' >>> textFileProcessor.process_file() 'nametestage' """ content = self.read_file() content = ''.join([char for char in content if char.isalpha()]) self.write_file(content) return content
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): """ Initialize the file path. :param file_path: str """ self.file_path = file_path def read_file(self): """ Read the return the content of self.file_path file. :return: the same return as the read() method >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file() '{\n "name": "test",\n "age": 12\n}' """ def write_file(self, content): """ Write content into the self.file_path file, and overwrite if the file has already existed. :param content: any content >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.write_file('Hello world!') >>> textFileProcessor.read_file() 'Hello world!' """ def process_file(self): """ Read the self.file_path file and filter out non-alphabetic characters from the content string. Overwrite the after-processed data into the same self.file_path file. >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file() '{\n "name": "test",\n "age": 12\n}' >>> textFileProcessor.process_file() 'nametestage' """
def read_file_as_json(self): with open(self.file_path, 'r') as file: data = json.load(file) return data
Read the self.file_path file as json format. if the file content doesn't obey json format, the code will raise error.
ClassEval_84_sum
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): self.file_path = file_path def read_file_as_json(self): """ Read the self.file_path file as json format. if the file content doesn't obey json format, the code will raise error. :return data: dict if the file is stored as json format, or str/int/float.. according to the file content otherwise. >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file_as_json() {'name': 'test', 'age': 12} >>> type(textFileProcessor.read_file_as_json()) <class 'dict'> """ with open(self.file_path, 'r') as file: data = json.load(file) return data def write_file(self, content): """ Write content into the self.file_path file, and overwrite if the file has already existed. :param content: any content >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.write_file('Hello world!') >>> textFileProcessor.read_file() 'Hello world!' """ with open(self.file_path, 'w') as file: file.write(content) def process_file(self): """ Read the self.file_path file and filter out non-alphabetic characters from the content string. Overwrite the after-processed data into the same self.file_path file. >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file() '{\n "name": "test",\n "age": 12\n}' >>> textFileProcessor.process_file() 'nametestage' """ content = self.read_file() content = ''.join([char for char in content if char.isalpha()]) self.write_file(content) return content
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): """ Initialize the file path. :param file_path: str """ self.file_path = file_path def read_file_as_json(self): """ Read the self.file_path file as json format. if the file content doesn't obey json format, the code will raise error. :return data: dict if the file is stored as json format, or str/int/float.. according to the file content otherwise. >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file_as_json() {'name': 'test', 'age': 12} >>> type(textFileProcessor.read_file_as_json()) <class 'dict'> """ def write_file(self, content): """ Write content into the self.file_path file, and overwrite if the file has already existed. :param content: any content >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.write_file('Hello world!') >>> textFileProcessor.read_file() 'Hello world!' """ def process_file(self): """ Read the self.file_path file and filter out non-alphabetic characters from the content string. Overwrite the after-processed data into the same self.file_path file. >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file() '{\n "name": "test",\n "age": 12\n}' >>> textFileProcessor.process_file() 'nametestage' """
def read_file(self): with open(self.file_path, 'r') as file: return file.read()
Read the return the content of self.file_path file.
ClassEval_84_sum
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): self.file_path = file_path def read_file_as_json(self): """ Read the self.file_path file as json format. if the file content doesn't obey json format, the code will raise error. :return data: dict if the file is stored as json format, or str/int/float.. according to the file content otherwise. >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file_as_json() {'name': 'test', 'age': 12} >>> type(textFileProcessor.read_file_as_json()) <class 'dict'> """ with open(self.file_path, 'r') as file: data = json.load(file) return data def read_file(self): """ Read the return the content of self.file_path file. :return: the same return as the read() method >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file() '{\n "name": "test",\n "age": 12\n}' """ with open(self.file_path, 'r') as file: return file.read() def process_file(self): """ Read the self.file_path file and filter out non-alphabetic characters from the content string. Overwrite the after-processed data into the same self.file_path file. >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file() '{\n "name": "test",\n "age": 12\n}' >>> textFileProcessor.process_file() 'nametestage' """ content = self.read_file() content = ''.join([char for char in content if char.isalpha()]) self.write_file(content) return content
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): """ Initialize the file path. :param file_path: str """ self.file_path = file_path def read_file_as_json(self): """ Read the self.file_path file as json format. if the file content doesn't obey json format, the code will raise error. :return data: dict if the file is stored as json format, or str/int/float.. according to the file content otherwise. >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file_as_json() {'name': 'test', 'age': 12} >>> type(textFileProcessor.read_file_as_json()) <class 'dict'> """ def read_file(self): """ Read the return the content of self.file_path file. :return: the same return as the read() method >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file() '{\n "name": "test",\n "age": 12\n}' """ def process_file(self): """ Read the self.file_path file and filter out non-alphabetic characters from the content string. Overwrite the after-processed data into the same self.file_path file. >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file() '{\n "name": "test",\n "age": 12\n}' >>> textFileProcessor.process_file() 'nametestage' """
def write_file(self, content): with open(self.file_path, 'w') as file: file.write(content)
Write content into the self.file_path file, and overwrite if the file has already existed.
ClassEval_84_sum
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): self.file_path = file_path def read_file_as_json(self): """ Read the self.file_path file as json format. if the file content doesn't obey json format, the code will raise error. :return data: dict if the file is stored as json format, or str/int/float.. according to the file content otherwise. >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file_as_json() {'name': 'test', 'age': 12} >>> type(textFileProcessor.read_file_as_json()) <class 'dict'> """ with open(self.file_path, 'r') as file: data = json.load(file) return data def read_file(self): """ Read the return the content of self.file_path file. :return: the same return as the read() method >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file() '{\n "name": "test",\n "age": 12\n}' """ with open(self.file_path, 'r') as file: return file.read() def write_file(self, content): """ Write content into the self.file_path file, and overwrite if the file has already existed. :param content: any content >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.write_file('Hello world!') >>> textFileProcessor.read_file() 'Hello world!' """ with open(self.file_path, 'w') as file: file.write(content) def process_file(self): content = self.read_file() content = ''.join([char for char in content if char.isalpha()]) self.write_file(content) return content
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): """ Initialize the file path. :param file_path: str """ self.file_path = file_path def read_file_as_json(self): """ Read the self.file_path file as json format. if the file content doesn't obey json format, the code will raise error. :return data: dict if the file is stored as json format, or str/int/float.. according to the file content otherwise. >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file_as_json() {'name': 'test', 'age': 12} >>> type(textFileProcessor.read_file_as_json()) <class 'dict'> """ def read_file(self): """ Read the return the content of self.file_path file. :return: the same return as the read() method >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file() '{\n "name": "test",\n "age": 12\n}' """ def write_file(self, content): """ Write content into the self.file_path file, and overwrite if the file has already existed. :param content: any content >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.write_file('Hello world!') >>> textFileProcessor.read_file() 'Hello world!' """ def process_file(self): """ Read the self.file_path file and filter out non-alphabetic characters from the content string. Overwrite the after-processed data into the same self.file_path file. >>> textFileProcessor = TextFileProcessor('test.json') >>> textFileProcessor.read_file() '{\n "name": "test",\n "age": 12\n}' >>> textFileProcessor.process_file() 'nametestage' """
def process_file(self): content = self.read_file() content = ''.join([char for char in content if char.isalpha()]) self.write_file(content) return content
Read the self.file_path file and filter out non-alphabetic characters from the content string. Overwrite the after-processed data into the same self.file_path file.
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def set_target_temperature(self, temperature): """ Set the target temperature :param temperature: float, the target temperature >>> thermostat.set_target_temperature(37.6) >>> thermostat.target_temperature 37.6 """ self.target_temperature = temperature def get_mode(self): """ Get the current work mode :return mode: str, working mode. only ['heat', 'cool'] """ return self.mode def set_mode(self, mode): """ Get the current work mode :param mode: str, working mode. only ['heat', 'cool'] >>> thermostat.set_mode('cool') >>> thermostat.mode 'cool' """ if mode in ['heat', 'cool']: self.mode = mode else: return False def auto_set_mode(self): """ Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_set_mode() >>> thermostat.mode 'heat' """ if self.current_temperature < self.target_temperature: self.mode = 'heat' else: self.mode = 'cool' def auto_check_conflict(self): """ Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically. :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_check_conflict() False >>> thermostat.mode 'heat' """ if self.current_temperature > self.target_temperature: if self.mode == 'cool': return True else: self.auto_set_mode() return False else: if self.mode == 'heat': return True else: self.auto_set_mode() return False def simulate_operation(self): """ simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached. :return time: int, the time it took to complete the simulation. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.simulate_operation() 18 """ self.auto_set_mode() use_time = 0 if self.mode == 'heat': while(self.current_temperature < self.target_temperature): self.current_temperature += 1 use_time += 1 else: while(self.current_temperature > self.target_temperature): self.current_temperature -= 1 use_time += 1 return use_time
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of the Thermostat class, including the current temperature, target temperature, and operating mode. :param current_temperature: float :param target_temperature: float :param mode: str, the work mode """ self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def set_target_temperature(self, temperature): """ Set the target temperature :param temperature: float, the target temperature >>> thermostat.set_target_temperature(37.6) >>> thermostat.target_temperature 37.6 """ def get_mode(self): """ Get the current work mode :return mode: str, working mode. only ['heat', 'cool'] """ def set_mode(self, mode): """ Get the current work mode :param mode: str, working mode. only ['heat', 'cool'] >>> thermostat.set_mode('cool') >>> thermostat.mode 'cool' """ def auto_set_mode(self): """ Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_set_mode() >>> thermostat.mode 'heat' """ def auto_check_conflict(self): """ Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically. :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_check_conflict() False >>> thermostat.mode 'heat' """ def simulate_operation(self): """ simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached. :return time: int, the time it took to complete the simulation. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.simulate_operation() 18 """
def get_target_temperature(self): return self.target_temperature
Get the target temperature of an instance of the Thermostat class.
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def get_target_temperature(self): """ Get the target temperature of an instance of the Thermostat class. :return self.current_temperature: int >>> thermostat.get_target_temperature() 37.5 """ return self.target_temperature def get_mode(self): """ Get the current work mode :return mode: str, working mode. only ['heat', 'cool'] """ return self.mode def set_mode(self, mode): """ Get the current work mode :param mode: str, working mode. only ['heat', 'cool'] >>> thermostat.set_mode('cool') >>> thermostat.mode 'cool' """ if mode in ['heat', 'cool']: self.mode = mode else: return False def auto_set_mode(self): """ Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_set_mode() >>> thermostat.mode 'heat' """ if self.current_temperature < self.target_temperature: self.mode = 'heat' else: self.mode = 'cool' def auto_check_conflict(self): """ Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically. :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_check_conflict() False >>> thermostat.mode 'heat' """ if self.current_temperature > self.target_temperature: if self.mode == 'cool': return True else: self.auto_set_mode() return False else: if self.mode == 'heat': return True else: self.auto_set_mode() return False def simulate_operation(self): """ simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached. :return time: int, the time it took to complete the simulation. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.simulate_operation() 18 """ self.auto_set_mode() use_time = 0 if self.mode == 'heat': while(self.current_temperature < self.target_temperature): self.current_temperature += 1 use_time += 1 else: while(self.current_temperature > self.target_temperature): self.current_temperature -= 1 use_time += 1 return use_time
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of the Thermostat class, including the current temperature, target temperature, and operating mode. :param current_temperature: float :param target_temperature: float :param mode: str, the work mode """ self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def get_target_temperature(self): """ Get the target temperature of an instance of the Thermostat class. :return self.current_temperature: int >>> thermostat.get_target_temperature() 37.5 """ def get_mode(self): """ Get the current work mode :return mode: str, working mode. only ['heat', 'cool'] """ def set_mode(self, mode): """ Get the current work mode :param mode: str, working mode. only ['heat', 'cool'] >>> thermostat.set_mode('cool') >>> thermostat.mode 'cool' """ def auto_set_mode(self): """ Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_set_mode() >>> thermostat.mode 'heat' """ def auto_check_conflict(self): """ Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically. :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_check_conflict() False >>> thermostat.mode 'heat' """ def simulate_operation(self): """ simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached. :return time: int, the time it took to complete the simulation. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.simulate_operation() 18 """
def set_target_temperature(self, temperature): self.target_temperature = temperature
Set the target temperature
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def get_target_temperature(self): """ Get the target temperature of an instance of the Thermostat class. :return self.current_temperature: int >>> thermostat.get_target_temperature() 37.5 """ return self.target_temperature def set_target_temperature(self, temperature): """ Set the target temperature :param temperature: float, the target temperature >>> thermostat.set_target_temperature(37.6) >>> thermostat.target_temperature 37.6 """ self.target_temperature = temperature def set_mode(self, mode): """ Get the current work mode :param mode: str, working mode. only ['heat', 'cool'] >>> thermostat.set_mode('cool') >>> thermostat.mode 'cool' """ if mode in ['heat', 'cool']: self.mode = mode else: return False def auto_set_mode(self): """ Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_set_mode() >>> thermostat.mode 'heat' """ if self.current_temperature < self.target_temperature: self.mode = 'heat' else: self.mode = 'cool' def auto_check_conflict(self): """ Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically. :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_check_conflict() False >>> thermostat.mode 'heat' """ if self.current_temperature > self.target_temperature: if self.mode == 'cool': return True else: self.auto_set_mode() return False else: if self.mode == 'heat': return True else: self.auto_set_mode() return False def simulate_operation(self): """ simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached. :return time: int, the time it took to complete the simulation. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.simulate_operation() 18 """ self.auto_set_mode() use_time = 0 if self.mode == 'heat': while(self.current_temperature < self.target_temperature): self.current_temperature += 1 use_time += 1 else: while(self.current_temperature > self.target_temperature): self.current_temperature -= 1 use_time += 1 return use_time
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of the Thermostat class, including the current temperature, target temperature, and operating mode. :param current_temperature: float :param target_temperature: float :param mode: str, the work mode """ self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def get_target_temperature(self): """ Get the target temperature of an instance of the Thermostat class. :return self.current_temperature: int >>> thermostat.get_target_temperature() 37.5 """ def set_target_temperature(self, temperature): """ Set the target temperature :param temperature: float, the target temperature >>> thermostat.set_target_temperature(37.6) >>> thermostat.target_temperature 37.6 """ def set_mode(self, mode): """ Get the current work mode :param mode: str, working mode. only ['heat', 'cool'] >>> thermostat.set_mode('cool') >>> thermostat.mode 'cool' """ def auto_set_mode(self): """ Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_set_mode() >>> thermostat.mode 'heat' """ def auto_check_conflict(self): """ Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically. :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_check_conflict() False >>> thermostat.mode 'heat' """ def simulate_operation(self): """ simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached. :return time: int, the time it took to complete the simulation. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.simulate_operation() 18 """
def get_mode(self): return self.mode
Get the current work mode
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def get_target_temperature(self): """ Get the target temperature of an instance of the Thermostat class. :return self.current_temperature: int >>> thermostat.get_target_temperature() 37.5 """ return self.target_temperature def set_target_temperature(self, temperature): """ Set the target temperature :param temperature: float, the target temperature >>> thermostat.set_target_temperature(37.6) >>> thermostat.target_temperature 37.6 """ self.target_temperature = temperature def get_mode(self): """ Get the current work mode :return mode: str, working mode. only ['heat', 'cool'] """ return self.mode def auto_set_mode(self): """ Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_set_mode() >>> thermostat.mode 'heat' """ if self.current_temperature < self.target_temperature: self.mode = 'heat' else: self.mode = 'cool' def auto_check_conflict(self): """ Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically. :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_check_conflict() False >>> thermostat.mode 'heat' """ if self.current_temperature > self.target_temperature: if self.mode == 'cool': return True else: self.auto_set_mode() return False else: if self.mode == 'heat': return True else: self.auto_set_mode() return False def simulate_operation(self): """ simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached. :return time: int, the time it took to complete the simulation. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.simulate_operation() 18 """ self.auto_set_mode() use_time = 0 if self.mode == 'heat': while(self.current_temperature < self.target_temperature): self.current_temperature += 1 use_time += 1 else: while(self.current_temperature > self.target_temperature): self.current_temperature -= 1 use_time += 1 return use_time
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of the Thermostat class, including the current temperature, target temperature, and operating mode. :param current_temperature: float :param target_temperature: float :param mode: str, the work mode """ self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def get_target_temperature(self): """ Get the target temperature of an instance of the Thermostat class. :return self.current_temperature: int >>> thermostat.get_target_temperature() 37.5 """ def set_target_temperature(self, temperature): """ Set the target temperature :param temperature: float, the target temperature >>> thermostat.set_target_temperature(37.6) >>> thermostat.target_temperature 37.6 """ def get_mode(self): """ Get the current work mode :return mode: str, working mode. only ['heat', 'cool'] """ def auto_set_mode(self): """ Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_set_mode() >>> thermostat.mode 'heat' """ def auto_check_conflict(self): """ Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically. :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_check_conflict() False >>> thermostat.mode 'heat' """ def simulate_operation(self): """ simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached. :return time: int, the time it took to complete the simulation. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.simulate_operation() 18 """
def set_mode(self, mode): if mode in ['heat', 'cool']: self.mode = mode else: return False
Get the current work mode
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def get_target_temperature(self): """ Get the target temperature of an instance of the Thermostat class. :return self.current_temperature: int >>> thermostat.get_target_temperature() 37.5 """ return self.target_temperature def set_target_temperature(self, temperature): """ Set the target temperature :param temperature: float, the target temperature >>> thermostat.set_target_temperature(37.6) >>> thermostat.target_temperature 37.6 """ self.target_temperature = temperature def get_mode(self): """ Get the current work mode :return mode: str, working mode. only ['heat', 'cool'] """ return self.mode def set_mode(self, mode): """ Get the current work mode :param mode: str, working mode. only ['heat', 'cool'] >>> thermostat.set_mode('cool') >>> thermostat.mode 'cool' """ if mode in ['heat', 'cool']: self.mode = mode else: return False def auto_check_conflict(self): """ Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically. :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_check_conflict() False >>> thermostat.mode 'heat' """ if self.current_temperature > self.target_temperature: if self.mode == 'cool': return True else: self.auto_set_mode() return False else: if self.mode == 'heat': return True else: self.auto_set_mode() return False def simulate_operation(self): """ simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached. :return time: int, the time it took to complete the simulation. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.simulate_operation() 18 """ self.auto_set_mode() use_time = 0 if self.mode == 'heat': while(self.current_temperature < self.target_temperature): self.current_temperature += 1 use_time += 1 else: while(self.current_temperature > self.target_temperature): self.current_temperature -= 1 use_time += 1 return use_time
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of the Thermostat class, including the current temperature, target temperature, and operating mode. :param current_temperature: float :param target_temperature: float :param mode: str, the work mode """ self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def get_target_temperature(self): """ Get the target temperature of an instance of the Thermostat class. :return self.current_temperature: int >>> thermostat.get_target_temperature() 37.5 """ def set_target_temperature(self, temperature): """ Set the target temperature :param temperature: float, the target temperature >>> thermostat.set_target_temperature(37.6) >>> thermostat.target_temperature 37.6 """ def get_mode(self): """ Get the current work mode :return mode: str, working mode. only ['heat', 'cool'] """ def set_mode(self, mode): """ Get the current work mode :param mode: str, working mode. only ['heat', 'cool'] >>> thermostat.set_mode('cool') >>> thermostat.mode 'cool' """ def auto_check_conflict(self): """ Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically. :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_check_conflict() False >>> thermostat.mode 'heat' """ def simulate_operation(self): """ simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached. :return time: int, the time it took to complete the simulation. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.simulate_operation() 18 """
def auto_set_mode(self): if self.current_temperature < self.target_temperature: self.mode = 'heat' else: self.mode = 'cool'
Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'.
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def get_target_temperature(self): """ Get the target temperature of an instance of the Thermostat class. :return self.current_temperature: int >>> thermostat.get_target_temperature() 37.5 """ return self.target_temperature def set_target_temperature(self, temperature): """ Set the target temperature :param temperature: float, the target temperature >>> thermostat.set_target_temperature(37.6) >>> thermostat.target_temperature 37.6 """ self.target_temperature = temperature def get_mode(self): """ Get the current work mode :return mode: str, working mode. only ['heat', 'cool'] """ return self.mode def set_mode(self, mode): """ Get the current work mode :param mode: str, working mode. only ['heat', 'cool'] >>> thermostat.set_mode('cool') >>> thermostat.mode 'cool' """ if mode in ['heat', 'cool']: self.mode = mode else: return False def auto_set_mode(self): """ Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_set_mode() >>> thermostat.mode 'heat' """ if self.current_temperature < self.target_temperature: self.mode = 'heat' else: self.mode = 'cool' def simulate_operation(self): """ simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached. :return time: int, the time it took to complete the simulation. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.simulate_operation() 18 """ self.auto_set_mode() use_time = 0 if self.mode == 'heat': while(self.current_temperature < self.target_temperature): self.current_temperature += 1 use_time += 1 else: while(self.current_temperature > self.target_temperature): self.current_temperature -= 1 use_time += 1 return use_time
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of the Thermostat class, including the current temperature, target temperature, and operating mode. :param current_temperature: float :param target_temperature: float :param mode: str, the work mode """ self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def get_target_temperature(self): """ Get the target temperature of an instance of the Thermostat class. :return self.current_temperature: int >>> thermostat.get_target_temperature() 37.5 """ def set_target_temperature(self, temperature): """ Set the target temperature :param temperature: float, the target temperature >>> thermostat.set_target_temperature(37.6) >>> thermostat.target_temperature 37.6 """ def get_mode(self): """ Get the current work mode :return mode: str, working mode. only ['heat', 'cool'] """ def set_mode(self, mode): """ Get the current work mode :param mode: str, working mode. only ['heat', 'cool'] >>> thermostat.set_mode('cool') >>> thermostat.mode 'cool' """ def auto_set_mode(self): """ Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_set_mode() >>> thermostat.mode 'heat' """ def simulate_operation(self): """ simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached. :return time: int, the time it took to complete the simulation. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.simulate_operation() 18 """
def auto_check_conflict(self): if self.current_temperature > self.target_temperature: if self.mode == 'cool': return True else: self.auto_set_mode() return False else: if self.mode == 'heat': return True else: self.auto_set_mode() return False
Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically.
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def get_target_temperature(self): """ Get the target temperature of an instance of the Thermostat class. :return self.current_temperature: int >>> thermostat.get_target_temperature() 37.5 """ return self.target_temperature def set_target_temperature(self, temperature): """ Set the target temperature :param temperature: float, the target temperature >>> thermostat.set_target_temperature(37.6) >>> thermostat.target_temperature 37.6 """ self.target_temperature = temperature def get_mode(self): """ Get the current work mode :return mode: str, working mode. only ['heat', 'cool'] """ return self.mode def set_mode(self, mode): """ Get the current work mode :param mode: str, working mode. only ['heat', 'cool'] >>> thermostat.set_mode('cool') >>> thermostat.mode 'cool' """ if mode in ['heat', 'cool']: self.mode = mode else: return False def auto_set_mode(self): """ Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_set_mode() >>> thermostat.mode 'heat' """ if self.current_temperature < self.target_temperature: self.mode = 'heat' else: self.mode = 'cool' def auto_check_conflict(self): """ Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically. :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_check_conflict() False >>> thermostat.mode 'heat' """ if self.current_temperature > self.target_temperature: if self.mode == 'cool': return True else: self.auto_set_mode() return False else: if self.mode == 'heat': return True else: self.auto_set_mode() return False def simulate_operation(self): self.auto_set_mode() use_time = 0 if self.mode == 'heat': while(self.current_temperature < self.target_temperature): self.current_temperature += 1 use_time += 1 else: while(self.current_temperature > self.target_temperature): self.current_temperature -= 1 use_time += 1 return use_time
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of the Thermostat class, including the current temperature, target temperature, and operating mode. :param current_temperature: float :param target_temperature: float :param mode: str, the work mode """ self.current_temperature = current_temperature self.target_temperature = target_temperature self.mode = mode def get_target_temperature(self): """ Get the target temperature of an instance of the Thermostat class. :return self.current_temperature: int >>> thermostat.get_target_temperature() 37.5 """ def set_target_temperature(self, temperature): """ Set the target temperature :param temperature: float, the target temperature >>> thermostat.set_target_temperature(37.6) >>> thermostat.target_temperature 37.6 """ def get_mode(self): """ Get the current work mode :return mode: str, working mode. only ['heat', 'cool'] """ def set_mode(self, mode): """ Get the current work mode :param mode: str, working mode. only ['heat', 'cool'] >>> thermostat.set_mode('cool') >>> thermostat.mode 'cool' """ def auto_set_mode(self): """ Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_set_mode() >>> thermostat.mode 'heat' """ def auto_check_conflict(self): """ Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically. :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.auto_check_conflict() False >>> thermostat.mode 'heat' """ def simulate_operation(self): """ simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached. :return time: int, the time it took to complete the simulation. >>> thermostat = Thermostat(20.4, 37.5, 'cool') >>> thermostat.simulate_operation() 18 """
def simulate_operation(self): self.auto_set_mode() use_time = 0 if self.mode == 'heat': while(self.current_temperature < self.target_temperature): self.current_temperature += 1 use_time += 1 else: while(self.current_temperature > self.target_temperature): self.current_temperature -= 1 use_time += 1 return use_time
simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached.
ClassEval_86_sum
class TicTacToe: """ The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full. """ def __init__(self, N=3): self.board = [[' ' for _ in range(N)] for _ in range(3)] self.current_player = 'X' def check_winner(self): """ Check if there is a winner on the board in rows, columns and diagonals three directions :return: str or None, the mark of the winner ('X' or 'O'), or None if there is no winner yet >>> moves = [(1, 0), (2, 0), (1, 1), (2, 1), (1, 2)] >>> for move in moves: ... ttt.make_move(move[0], move[1]) >>> ttt.check_winner() 'X' """ for row in self.board: if row[0] == row[1] == row[2] != ' ': return row[0] for col in range(3): if self.board[0][col] == self.board[1][col] == self.board[2][col] != ' ': return self.board[0][col] if self.board[0][0] == self.board[1][1] == self.board[2][2] != ' ': return self.board[0][0] if self.board[0][2] == self.board[1][1] == self.board[2][0] != ' ': return self.board[0][2] return None def is_board_full(self): """ Check if the game board is completely filled. :return: bool, indicating whether the game board is full or not >>> ttt.is_board_full() False """ for row in self.board: if ' ' in row: return False return True
class TicTacToe: """ The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full. """ def __init__(self, N=3): """ Initialize a 3x3 game board with all empty spaces and current symble player, default is 'X'. """ self.board = [[' ' for _ in range(N)] for _ in range(3)] self.current_player = 'X' def check_winner(self): """ Check if there is a winner on the board in rows, columns and diagonals three directions :return: str or None, the mark of the winner ('X' or 'O'), or None if there is no winner yet >>> moves = [(1, 0), (2, 0), (1, 1), (2, 1), (1, 2)] >>> for move in moves: ... ttt.make_move(move[0], move[1]) >>> ttt.check_winner() 'X' """ def is_board_full(self): """ Check if the game board is completely filled. :return: bool, indicating whether the game board is full or not >>> ttt.is_board_full() False """
def make_move(self, row, col): if self.board[row][col] == ' ': self.board[row][col] = self.current_player self.current_player = 'O' if self.current_player == 'X' else 'X' return True else: return False
Place the current player's mark at the specified position on the board and switch the mark.
ClassEval_86_sum
class TicTacToe: """ The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full. """ def __init__(self, N=3): self.board = [[' ' for _ in range(N)] for _ in range(3)] self.current_player = 'X' def make_move(self, row, col): """ Place the current player's mark at the specified position on the board and switch the mark. :param row: int, the row index of the position :param col: int, the column index of the position :return: bool, indicating whether the move was successful or not >>> ttt.current_player 'X' >>> ttt.make_move(1, 1) >>> ttt.current_player 'O' """ if self.board[row][col] == ' ': self.board[row][col] = self.current_player self.current_player = 'O' if self.current_player == 'X' else 'X' return True else: return False def is_board_full(self): """ Check if the game board is completely filled. :return: bool, indicating whether the game board is full or not >>> ttt.is_board_full() False """ for row in self.board: if ' ' in row: return False return True
class TicTacToe: """ The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full. """ def __init__(self, N=3): """ Initialize a 3x3 game board with all empty spaces and current symble player, default is 'X'. """ self.board = [[' ' for _ in range(N)] for _ in range(3)] self.current_player = 'X' def make_move(self, row, col): """ Place the current player's mark at the specified position on the board and switch the mark. :param row: int, the row index of the position :param col: int, the column index of the position :return: bool, indicating whether the move was successful or not >>> ttt.current_player 'X' >>> ttt.make_move(1, 1) >>> ttt.current_player 'O' """ def is_board_full(self): """ Check if the game board is completely filled. :return: bool, indicating whether the game board is full or not >>> ttt.is_board_full() False """
def check_winner(self): for row in self.board: if row[0] == row[1] == row[2] != ' ': return row[0] for col in range(3): if self.board[0][col] == self.board[1][col] == self.board[2][col] != ' ': return self.board[0][col] if self.board[0][0] == self.board[1][1] == self.board[2][2] != ' ': return self.board[0][0] if self.board[0][2] == self.board[1][1] == self.board[2][0] != ' ': return self.board[0][2] return None
Check if there is a winner on the board in rows, columns and diagonals three directions
ClassEval_86_sum
class TicTacToe: """ The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full. """ def __init__(self, N=3): self.board = [[' ' for _ in range(N)] for _ in range(3)] self.current_player = 'X' def make_move(self, row, col): """ Place the current player's mark at the specified position on the board and switch the mark. :param row: int, the row index of the position :param col: int, the column index of the position :return: bool, indicating whether the move was successful or not >>> ttt.current_player 'X' >>> ttt.make_move(1, 1) >>> ttt.current_player 'O' """ if self.board[row][col] == ' ': self.board[row][col] = self.current_player self.current_player = 'O' if self.current_player == 'X' else 'X' return True else: return False def check_winner(self): """ Check if there is a winner on the board in rows, columns and diagonals three directions :return: str or None, the mark of the winner ('X' or 'O'), or None if there is no winner yet >>> moves = [(1, 0), (2, 0), (1, 1), (2, 1), (1, 2)] >>> for move in moves: ... ttt.make_move(move[0], move[1]) >>> ttt.check_winner() 'X' """ for row in self.board: if row[0] == row[1] == row[2] != ' ': return row[0] for col in range(3): if self.board[0][col] == self.board[1][col] == self.board[2][col] != ' ': return self.board[0][col] if self.board[0][0] == self.board[1][1] == self.board[2][2] != ' ': return self.board[0][0] if self.board[0][2] == self.board[1][1] == self.board[2][0] != ' ': return self.board[0][2] return None def is_board_full(self): for row in self.board: if ' ' in row: return False return True
class TicTacToe: """ The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full. """ def __init__(self, N=3): """ Initialize a 3x3 game board with all empty spaces and current symble player, default is 'X'. """ self.board = [[' ' for _ in range(N)] for _ in range(3)] self.current_player = 'X' def make_move(self, row, col): """ Place the current player's mark at the specified position on the board and switch the mark. :param row: int, the row index of the position :param col: int, the column index of the position :return: bool, indicating whether the move was successful or not >>> ttt.current_player 'X' >>> ttt.make_move(1, 1) >>> ttt.current_player 'O' """ def check_winner(self): """ Check if there is a winner on the board in rows, columns and diagonals three directions :return: str or None, the mark of the winner ('X' or 'O'), or None if there is no winner yet >>> moves = [(1, 0), (2, 0), (1, 1), (2, 1), (1, 2)] >>> for move in moves: ... ttt.make_move(move[0], move[1]) >>> ttt.check_winner() 'X' """ def is_board_full(self): """ Check if the game board is completely filled. :return: bool, indicating whether the game board is full or not >>> ttt.is_board_full() False """
def is_board_full(self): for row in self.board: if ' ' in row: return False return True
Check if the game board is completely filled.
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): self.datetime = datetime.datetime.now() def get_current_date(self): """ Return the current date in the format of "%Y-%m-%d" :return: string >>> timeutils.get_current_date() "2023-06-14" """ format = "%Y-%m-%d" return self.datetime.strftime(format) def add_seconds(self, seconds): """ Add the specified number of seconds to the current time :param seconds: int, number of seconds to add :return: string, time after adding the specified number of seconds in the format '%H:%M:%S' >>> timeutils.add_seconds(600) "19:29:22" """ new_datetime = self.datetime + datetime.timedelta(seconds=seconds) format = "%H:%M:%S" return new_datetime.strftime(format) def string_to_datetime(self, string): """ Convert the time string to a datetime instance :param string: string, string before converting format :return: datetime instance >>> timeutils.string_to_datetime("2001-7-18 1:1:1") 2001-07-18 01:01:01 """ return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S") def datetime_to_string(self, datetime): """ Convert a datetime instance to a string :param datetime: the datetime instance to convert :return: string, converted time string >>> timeutils.datetime_to_string(timeutils.datetime) "2023-06-14 19:30:03" """ return datetime.strftime("%Y-%m-%d %H:%M:%S") def get_minutes(self, string_time1, string_time2): """ Calculate how many minutes have passed between two times, and round the results to the nearest :return: int, the number of minutes between two times, rounded off >>> timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1") 60 """ time1 = self.string_to_datetime(string_time1) time2 = self.string_to_datetime(string_time2) return round((time2 - time1).seconds / 60) def get_format_time(self, year, month, day, hour, minute, second): """ get format time :param year: int :param month: int :param day: int :param hour: int :param minute: int :param second: int :return: formatted time string >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1) "2001-07-18 01:01:01" """ format = "%Y-%m-%d %H:%M:%S" time_item = datetime.datetime(year, month, day, hour, minute, second) return time_item.strftime(format)
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): """ Get the current datetime """ self.datetime = datetime.datetime.now() def get_current_date(self): """ Return the current date in the format of "%Y-%m-%d" :return: string >>> timeutils.get_current_date() "2023-06-14" """ def add_seconds(self, seconds): """ Add the specified number of seconds to the current time :param seconds: int, number of seconds to add :return: string, time after adding the specified number of seconds in the format '%H:%M:%S' >>> timeutils.add_seconds(600) "19:29:22" """ def string_to_datetime(self, string): """ Convert the time string to a datetime instance :param string: string, string before converting format :return: datetime instance >>> timeutils.string_to_datetime("2001-7-18 1:1:1") 2001-07-18 01:01:01 """ def datetime_to_string(self, datetime): """ Convert a datetime instance to a string :param datetime: the datetime instance to convert :return: string, converted time string >>> timeutils.datetime_to_string(timeutils.datetime) "2023-06-14 19:30:03" """ def get_minutes(self, string_time1, string_time2): """ Calculate how many minutes have passed between two times, and round the results to the nearest :return: int, the number of minutes between two times, rounded off >>> timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1") 60 """ def get_format_time(self, year, month, day, hour, minute, second): """ get format time :param year: int :param month: int :param day: int :param hour: int :param minute: int :param second: int :return: formatted time string >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1) "2001-07-18 01:01:01" """
def get_current_time(self): format = "%H:%M:%S" return self.datetime.strftime(format)
Return the current time in the format of '%H:%M:%S'
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): self.datetime = datetime.datetime.now() def get_current_time(self): """ Return the current time in the format of '%H:%M:%S' :return: string >>> timeutils = TimeUtils() >>> timeutils.get_current_time() "19:19:22" """ format = "%H:%M:%S" return self.datetime.strftime(format) def add_seconds(self, seconds): """ Add the specified number of seconds to the current time :param seconds: int, number of seconds to add :return: string, time after adding the specified number of seconds in the format '%H:%M:%S' >>> timeutils.add_seconds(600) "19:29:22" """ new_datetime = self.datetime + datetime.timedelta(seconds=seconds) format = "%H:%M:%S" return new_datetime.strftime(format) def string_to_datetime(self, string): """ Convert the time string to a datetime instance :param string: string, string before converting format :return: datetime instance >>> timeutils.string_to_datetime("2001-7-18 1:1:1") 2001-07-18 01:01:01 """ return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S") def datetime_to_string(self, datetime): """ Convert a datetime instance to a string :param datetime: the datetime instance to convert :return: string, converted time string >>> timeutils.datetime_to_string(timeutils.datetime) "2023-06-14 19:30:03" """ return datetime.strftime("%Y-%m-%d %H:%M:%S") def get_minutes(self, string_time1, string_time2): """ Calculate how many minutes have passed between two times, and round the results to the nearest :return: int, the number of minutes between two times, rounded off >>> timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1") 60 """ time1 = self.string_to_datetime(string_time1) time2 = self.string_to_datetime(string_time2) return round((time2 - time1).seconds / 60) def get_format_time(self, year, month, day, hour, minute, second): """ get format time :param year: int :param month: int :param day: int :param hour: int :param minute: int :param second: int :return: formatted time string >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1) "2001-07-18 01:01:01" """ format = "%Y-%m-%d %H:%M:%S" time_item = datetime.datetime(year, month, day, hour, minute, second) return time_item.strftime(format)
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): """ Get the current datetime """ self.datetime = datetime.datetime.now() def get_current_time(self): """ Return the current time in the format of '%H:%M:%S' :return: string >>> timeutils = TimeUtils() >>> timeutils.get_current_time() "19:19:22" """ def add_seconds(self, seconds): """ Add the specified number of seconds to the current time :param seconds: int, number of seconds to add :return: string, time after adding the specified number of seconds in the format '%H:%M:%S' >>> timeutils.add_seconds(600) "19:29:22" """ def string_to_datetime(self, string): """ Convert the time string to a datetime instance :param string: string, string before converting format :return: datetime instance >>> timeutils.string_to_datetime("2001-7-18 1:1:1") 2001-07-18 01:01:01 """ def datetime_to_string(self, datetime): """ Convert a datetime instance to a string :param datetime: the datetime instance to convert :return: string, converted time string >>> timeutils.datetime_to_string(timeutils.datetime) "2023-06-14 19:30:03" """ def get_minutes(self, string_time1, string_time2): """ Calculate how many minutes have passed between two times, and round the results to the nearest :return: int, the number of minutes between two times, rounded off >>> timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1") 60 """ def get_format_time(self, year, month, day, hour, minute, second): """ get format time :param year: int :param month: int :param day: int :param hour: int :param minute: int :param second: int :return: formatted time string >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1) "2001-07-18 01:01:01" """
def get_current_date(self): format = "%Y-%m-%d" return self.datetime.strftime(format)
Return the current date in the format of "%Y-%m-%d"
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): self.datetime = datetime.datetime.now() def get_current_time(self): """ Return the current time in the format of '%H:%M:%S' :return: string >>> timeutils = TimeUtils() >>> timeutils.get_current_time() "19:19:22" """ format = "%H:%M:%S" return self.datetime.strftime(format) def get_current_date(self): """ Return the current date in the format of "%Y-%m-%d" :return: string >>> timeutils.get_current_date() "2023-06-14" """ format = "%Y-%m-%d" return self.datetime.strftime(format) def string_to_datetime(self, string): """ Convert the time string to a datetime instance :param string: string, string before converting format :return: datetime instance >>> timeutils.string_to_datetime("2001-7-18 1:1:1") 2001-07-18 01:01:01 """ return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S") def datetime_to_string(self, datetime): """ Convert a datetime instance to a string :param datetime: the datetime instance to convert :return: string, converted time string >>> timeutils.datetime_to_string(timeutils.datetime) "2023-06-14 19:30:03" """ return datetime.strftime("%Y-%m-%d %H:%M:%S") def get_minutes(self, string_time1, string_time2): """ Calculate how many minutes have passed between two times, and round the results to the nearest :return: int, the number of minutes between two times, rounded off >>> timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1") 60 """ time1 = self.string_to_datetime(string_time1) time2 = self.string_to_datetime(string_time2) return round((time2 - time1).seconds / 60) def get_format_time(self, year, month, day, hour, minute, second): """ get format time :param year: int :param month: int :param day: int :param hour: int :param minute: int :param second: int :return: formatted time string >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1) "2001-07-18 01:01:01" """ format = "%Y-%m-%d %H:%M:%S" time_item = datetime.datetime(year, month, day, hour, minute, second) return time_item.strftime(format)
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): """ Get the current datetime """ self.datetime = datetime.datetime.now() def get_current_time(self): """ Return the current time in the format of '%H:%M:%S' :return: string >>> timeutils = TimeUtils() >>> timeutils.get_current_time() "19:19:22" """ def get_current_date(self): """ Return the current date in the format of "%Y-%m-%d" :return: string >>> timeutils.get_current_date() "2023-06-14" """ def string_to_datetime(self, string): """ Convert the time string to a datetime instance :param string: string, string before converting format :return: datetime instance >>> timeutils.string_to_datetime("2001-7-18 1:1:1") 2001-07-18 01:01:01 """ def datetime_to_string(self, datetime): """ Convert a datetime instance to a string :param datetime: the datetime instance to convert :return: string, converted time string >>> timeutils.datetime_to_string(timeutils.datetime) "2023-06-14 19:30:03" """ def get_minutes(self, string_time1, string_time2): """ Calculate how many minutes have passed between two times, and round the results to the nearest :return: int, the number of minutes between two times, rounded off >>> timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1") 60 """ def get_format_time(self, year, month, day, hour, minute, second): """ get format time :param year: int :param month: int :param day: int :param hour: int :param minute: int :param second: int :return: formatted time string >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1) "2001-07-18 01:01:01" """
def add_seconds(self, seconds): new_datetime = self.datetime + datetime.timedelta(seconds=seconds) format = "%H:%M:%S" return new_datetime.strftime(format)
Add the specified number of seconds to the current time
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): self.datetime = datetime.datetime.now() def get_current_time(self): """ Return the current time in the format of '%H:%M:%S' :return: string >>> timeutils = TimeUtils() >>> timeutils.get_current_time() "19:19:22" """ format = "%H:%M:%S" return self.datetime.strftime(format) def get_current_date(self): """ Return the current date in the format of "%Y-%m-%d" :return: string >>> timeutils.get_current_date() "2023-06-14" """ format = "%Y-%m-%d" return self.datetime.strftime(format) def add_seconds(self, seconds): """ Add the specified number of seconds to the current time :param seconds: int, number of seconds to add :return: string, time after adding the specified number of seconds in the format '%H:%M:%S' >>> timeutils.add_seconds(600) "19:29:22" """ new_datetime = self.datetime + datetime.timedelta(seconds=seconds) format = "%H:%M:%S" return new_datetime.strftime(format) def datetime_to_string(self, datetime): """ Convert a datetime instance to a string :param datetime: the datetime instance to convert :return: string, converted time string >>> timeutils.datetime_to_string(timeutils.datetime) "2023-06-14 19:30:03" """ return datetime.strftime("%Y-%m-%d %H:%M:%S") def get_minutes(self, string_time1, string_time2): """ Calculate how many minutes have passed between two times, and round the results to the nearest :return: int, the number of minutes between two times, rounded off >>> timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1") 60 """ time1 = self.string_to_datetime(string_time1) time2 = self.string_to_datetime(string_time2) return round((time2 - time1).seconds / 60) def get_format_time(self, year, month, day, hour, minute, second): """ get format time :param year: int :param month: int :param day: int :param hour: int :param minute: int :param second: int :return: formatted time string >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1) "2001-07-18 01:01:01" """ format = "%Y-%m-%d %H:%M:%S" time_item = datetime.datetime(year, month, day, hour, minute, second) return time_item.strftime(format)
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): """ Get the current datetime """ self.datetime = datetime.datetime.now() def get_current_time(self): """ Return the current time in the format of '%H:%M:%S' :return: string >>> timeutils = TimeUtils() >>> timeutils.get_current_time() "19:19:22" """ def get_current_date(self): """ Return the current date in the format of "%Y-%m-%d" :return: string >>> timeutils.get_current_date() "2023-06-14" """ def add_seconds(self, seconds): """ Add the specified number of seconds to the current time :param seconds: int, number of seconds to add :return: string, time after adding the specified number of seconds in the format '%H:%M:%S' >>> timeutils.add_seconds(600) "19:29:22" """ def datetime_to_string(self, datetime): """ Convert a datetime instance to a string :param datetime: the datetime instance to convert :return: string, converted time string >>> timeutils.datetime_to_string(timeutils.datetime) "2023-06-14 19:30:03" """ def get_minutes(self, string_time1, string_time2): """ Calculate how many minutes have passed between two times, and round the results to the nearest :return: int, the number of minutes between two times, rounded off >>> timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1") 60 """ def get_format_time(self, year, month, day, hour, minute, second): """ get format time :param year: int :param month: int :param day: int :param hour: int :param minute: int :param second: int :return: formatted time string >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1) "2001-07-18 01:01:01" """
def string_to_datetime(self, string): return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")
Convert the time string to a datetime instance
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): self.datetime = datetime.datetime.now() def get_current_time(self): """ Return the current time in the format of '%H:%M:%S' :return: string >>> timeutils = TimeUtils() >>> timeutils.get_current_time() "19:19:22" """ format = "%H:%M:%S" return self.datetime.strftime(format) def get_current_date(self): """ Return the current date in the format of "%Y-%m-%d" :return: string >>> timeutils.get_current_date() "2023-06-14" """ format = "%Y-%m-%d" return self.datetime.strftime(format) def add_seconds(self, seconds): """ Add the specified number of seconds to the current time :param seconds: int, number of seconds to add :return: string, time after adding the specified number of seconds in the format '%H:%M:%S' >>> timeutils.add_seconds(600) "19:29:22" """ new_datetime = self.datetime + datetime.timedelta(seconds=seconds) format = "%H:%M:%S" return new_datetime.strftime(format) def string_to_datetime(self, string): """ Convert the time string to a datetime instance :param string: string, string before converting format :return: datetime instance >>> timeutils.string_to_datetime("2001-7-18 1:1:1") 2001-07-18 01:01:01 """ return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S") def get_minutes(self, string_time1, string_time2): """ Calculate how many minutes have passed between two times, and round the results to the nearest :return: int, the number of minutes between two times, rounded off >>> timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1") 60 """ time1 = self.string_to_datetime(string_time1) time2 = self.string_to_datetime(string_time2) return round((time2 - time1).seconds / 60) def get_format_time(self, year, month, day, hour, minute, second): """ get format time :param year: int :param month: int :param day: int :param hour: int :param minute: int :param second: int :return: formatted time string >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1) "2001-07-18 01:01:01" """ format = "%Y-%m-%d %H:%M:%S" time_item = datetime.datetime(year, month, day, hour, minute, second) return time_item.strftime(format)
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): """ Get the current datetime """ self.datetime = datetime.datetime.now() def get_current_time(self): """ Return the current time in the format of '%H:%M:%S' :return: string >>> timeutils = TimeUtils() >>> timeutils.get_current_time() "19:19:22" """ def get_current_date(self): """ Return the current date in the format of "%Y-%m-%d" :return: string >>> timeutils.get_current_date() "2023-06-14" """ def add_seconds(self, seconds): """ Add the specified number of seconds to the current time :param seconds: int, number of seconds to add :return: string, time after adding the specified number of seconds in the format '%H:%M:%S' >>> timeutils.add_seconds(600) "19:29:22" """ def string_to_datetime(self, string): """ Convert the time string to a datetime instance :param string: string, string before converting format :return: datetime instance >>> timeutils.string_to_datetime("2001-7-18 1:1:1") 2001-07-18 01:01:01 """ def get_minutes(self, string_time1, string_time2): """ Calculate how many minutes have passed between two times, and round the results to the nearest :return: int, the number of minutes between two times, rounded off >>> timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1") 60 """ def get_format_time(self, year, month, day, hour, minute, second): """ get format time :param year: int :param month: int :param day: int :param hour: int :param minute: int :param second: int :return: formatted time string >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1) "2001-07-18 01:01:01" """
def datetime_to_string(self, datetime): return datetime.strftime("%Y-%m-%d %H:%M:%S")
Convert a datetime instance to a string
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): self.datetime = datetime.datetime.now() def get_current_time(self): """ Return the current time in the format of '%H:%M:%S' :return: string >>> timeutils = TimeUtils() >>> timeutils.get_current_time() "19:19:22" """ format = "%H:%M:%S" return self.datetime.strftime(format) def get_current_date(self): """ Return the current date in the format of "%Y-%m-%d" :return: string >>> timeutils.get_current_date() "2023-06-14" """ format = "%Y-%m-%d" return self.datetime.strftime(format) def add_seconds(self, seconds): """ Add the specified number of seconds to the current time :param seconds: int, number of seconds to add :return: string, time after adding the specified number of seconds in the format '%H:%M:%S' >>> timeutils.add_seconds(600) "19:29:22" """ new_datetime = self.datetime + datetime.timedelta(seconds=seconds) format = "%H:%M:%S" return new_datetime.strftime(format) def string_to_datetime(self, string): """ Convert the time string to a datetime instance :param string: string, string before converting format :return: datetime instance >>> timeutils.string_to_datetime("2001-7-18 1:1:1") 2001-07-18 01:01:01 """ return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S") def datetime_to_string(self, datetime): """ Convert a datetime instance to a string :param datetime: the datetime instance to convert :return: string, converted time string >>> timeutils.datetime_to_string(timeutils.datetime) "2023-06-14 19:30:03" """ return datetime.strftime("%Y-%m-%d %H:%M:%S") def get_format_time(self, year, month, day, hour, minute, second): """ get format time :param year: int :param month: int :param day: int :param hour: int :param minute: int :param second: int :return: formatted time string >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1) "2001-07-18 01:01:01" """ format = "%Y-%m-%d %H:%M:%S" time_item = datetime.datetime(year, month, day, hour, minute, second) return time_item.strftime(format)
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): """ Get the current datetime """ self.datetime = datetime.datetime.now() def get_current_time(self): """ Return the current time in the format of '%H:%M:%S' :return: string >>> timeutils = TimeUtils() >>> timeutils.get_current_time() "19:19:22" """ def get_current_date(self): """ Return the current date in the format of "%Y-%m-%d" :return: string >>> timeutils.get_current_date() "2023-06-14" """ def add_seconds(self, seconds): """ Add the specified number of seconds to the current time :param seconds: int, number of seconds to add :return: string, time after adding the specified number of seconds in the format '%H:%M:%S' >>> timeutils.add_seconds(600) "19:29:22" """ def string_to_datetime(self, string): """ Convert the time string to a datetime instance :param string: string, string before converting format :return: datetime instance >>> timeutils.string_to_datetime("2001-7-18 1:1:1") 2001-07-18 01:01:01 """ def datetime_to_string(self, datetime): """ Convert a datetime instance to a string :param datetime: the datetime instance to convert :return: string, converted time string >>> timeutils.datetime_to_string(timeutils.datetime) "2023-06-14 19:30:03" """ def get_format_time(self, year, month, day, hour, minute, second): """ get format time :param year: int :param month: int :param day: int :param hour: int :param minute: int :param second: int :return: formatted time string >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1) "2001-07-18 01:01:01" """
def get_minutes(self, string_time1, string_time2): time1 = self.string_to_datetime(string_time1) time2 = self.string_to_datetime(string_time2) return round((time2 - time1).seconds / 60)
Calculate how many minutes have passed between two times, and round the results to the nearest
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): self.datetime = datetime.datetime.now() def get_current_time(self): """ Return the current time in the format of '%H:%M:%S' :return: string >>> timeutils = TimeUtils() >>> timeutils.get_current_time() "19:19:22" """ format = "%H:%M:%S" return self.datetime.strftime(format) def get_current_date(self): """ Return the current date in the format of "%Y-%m-%d" :return: string >>> timeutils.get_current_date() "2023-06-14" """ format = "%Y-%m-%d" return self.datetime.strftime(format) def add_seconds(self, seconds): """ Add the specified number of seconds to the current time :param seconds: int, number of seconds to add :return: string, time after adding the specified number of seconds in the format '%H:%M:%S' >>> timeutils.add_seconds(600) "19:29:22" """ new_datetime = self.datetime + datetime.timedelta(seconds=seconds) format = "%H:%M:%S" return new_datetime.strftime(format) def string_to_datetime(self, string): """ Convert the time string to a datetime instance :param string: string, string before converting format :return: datetime instance >>> timeutils.string_to_datetime("2001-7-18 1:1:1") 2001-07-18 01:01:01 """ return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S") def datetime_to_string(self, datetime): """ Convert a datetime instance to a string :param datetime: the datetime instance to convert :return: string, converted time string >>> timeutils.datetime_to_string(timeutils.datetime) "2023-06-14 19:30:03" """ return datetime.strftime("%Y-%m-%d %H:%M:%S") def get_minutes(self, string_time1, string_time2): """ Calculate how many minutes have passed between two times, and round the results to the nearest :return: int, the number of minutes between two times, rounded off >>> timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1") 60 """ time1 = self.string_to_datetime(string_time1) time2 = self.string_to_datetime(string_time2) return round((time2 - time1).seconds / 60) def get_format_time(self, year, month, day, hour, minute, second): format = "%Y-%m-%d %H:%M:%S" time_item = datetime.datetime(year, month, day, hour, minute, second) return time_item.strftime(format)
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): """ Get the current datetime """ self.datetime = datetime.datetime.now() def get_current_time(self): """ Return the current time in the format of '%H:%M:%S' :return: string >>> timeutils = TimeUtils() >>> timeutils.get_current_time() "19:19:22" """ def get_current_date(self): """ Return the current date in the format of "%Y-%m-%d" :return: string >>> timeutils.get_current_date() "2023-06-14" """ def add_seconds(self, seconds): """ Add the specified number of seconds to the current time :param seconds: int, number of seconds to add :return: string, time after adding the specified number of seconds in the format '%H:%M:%S' >>> timeutils.add_seconds(600) "19:29:22" """ def string_to_datetime(self, string): """ Convert the time string to a datetime instance :param string: string, string before converting format :return: datetime instance >>> timeutils.string_to_datetime("2001-7-18 1:1:1") 2001-07-18 01:01:01 """ def datetime_to_string(self, datetime): """ Convert a datetime instance to a string :param datetime: the datetime instance to convert :return: string, converted time string >>> timeutils.datetime_to_string(timeutils.datetime) "2023-06-14 19:30:03" """ def get_minutes(self, string_time1, string_time2): """ Calculate how many minutes have passed between two times, and round the results to the nearest :return: int, the number of minutes between two times, rounded off >>> timeutils.get_minutes("2001-7-18 1:1:1", "2001-7-18 2:1:1") 60 """ def get_format_time(self, year, month, day, hour, minute, second): """ get format time :param year: int :param month: int :param day: int :param hour: int :param minute: int :param second: int :return: formatted time string >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1) "2001-07-18 01:01:01" """
def get_format_time(self, year, month, day, hour, minute, second): format = "%Y-%m-%d %H:%M:%S" time_item = datetime.datetime(year, month, day, hour, minute, second) return time_item.strftime(format)
get format time
ClassEval_88_sum
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def factorial(self, a): """ Calculate the factorial of a :param a: int :return: int >>> tricalculator.factorial(5) 120 """ b = 1 while a != 1: b *= a a -= 1 return b def taylor(self, x, n): """ Finding the n-order Taylor expansion value of cos (x/180 * pi) :param x: int :param n: int :return: float >>> tricalculator.taylor(60, 50) 0.5000000000000001 """ a = 1 x = x / 180 * pi count = 1 for k in range(1, n): if count % 2 != 0: a -= (x ** (2 * k)) / self.factorial(2 * k) else: a += (x ** (2 * k)) / self.factorial(2 * k) count += 1 return a def sin(self, x): """ Calculate the sin value of the x-degree angle :param x: float :return: float >>> tricalculator.sin(30) 0.5 """ x = x / 180 * pi g = 0 t = x n = 1 while fabs(t) >= 1e-15: g += t n += 1 t = -t * x * x / (2 * n - 1) / (2 * n - 2) return round(g, 10) def tan(self, x): """ Calculate the tan value of the x-degree angle :param x: float :return: float >>> tricalculator.tan(45) 1.0 """ if self.cos(x) != 0: result = self.sin(x) / self.cos(x) return round(result, 10) else: return False
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def factorial(self, a): """ Calculate the factorial of a :param a: int :return: int >>> tricalculator.factorial(5) 120 """ def taylor(self, x, n): """ Finding the n-order Taylor expansion value of cos (x/180 * pi) :param x: int :param n: int :return: float >>> tricalculator.taylor(60, 50) 0.5000000000000001 """ def sin(self, x): """ Calculate the sin value of the x-degree angle :param x: float :return: float >>> tricalculator.sin(30) 0.5 """ def tan(self, x): """ Calculate the tan value of the x-degree angle :param x: float :return: float >>> tricalculator.tan(45) 1.0 """
def cos(self, x): return round(self.taylor(x, 50), 10)
Calculate the cos value of the x-degree angle
ClassEval_88_sum
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle :param x:float :return:float >>> tricalculator = TriCalculator() >>> tricalculator.cos(60) 0.5 """ return round(self.taylor(x, 50), 10) def taylor(self, x, n): """ Finding the n-order Taylor expansion value of cos (x/180 * pi) :param x: int :param n: int :return: float >>> tricalculator.taylor(60, 50) 0.5000000000000001 """ a = 1 x = x / 180 * pi count = 1 for k in range(1, n): if count % 2 != 0: a -= (x ** (2 * k)) / self.factorial(2 * k) else: a += (x ** (2 * k)) / self.factorial(2 * k) count += 1 return a def sin(self, x): """ Calculate the sin value of the x-degree angle :param x: float :return: float >>> tricalculator.sin(30) 0.5 """ x = x / 180 * pi g = 0 t = x n = 1 while fabs(t) >= 1e-15: g += t n += 1 t = -t * x * x / (2 * n - 1) / (2 * n - 2) return round(g, 10) def tan(self, x): """ Calculate the tan value of the x-degree angle :param x: float :return: float >>> tricalculator.tan(45) 1.0 """ if self.cos(x) != 0: result = self.sin(x) / self.cos(x) return round(result, 10) else: return False
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle :param x:float :return:float >>> tricalculator = TriCalculator() >>> tricalculator.cos(60) 0.5 """ def taylor(self, x, n): """ Finding the n-order Taylor expansion value of cos (x/180 * pi) :param x: int :param n: int :return: float >>> tricalculator.taylor(60, 50) 0.5000000000000001 """ def sin(self, x): """ Calculate the sin value of the x-degree angle :param x: float :return: float >>> tricalculator.sin(30) 0.5 """ def tan(self, x): """ Calculate the tan value of the x-degree angle :param x: float :return: float >>> tricalculator.tan(45) 1.0 """
def factorial(self, a): b = 1 while a != 1: b *= a a -= 1 return b
Calculate the factorial of a
ClassEval_88_sum
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle :param x:float :return:float >>> tricalculator = TriCalculator() >>> tricalculator.cos(60) 0.5 """ return round(self.taylor(x, 50), 10) def factorial(self, a): """ Calculate the factorial of a :param a: int :return: int >>> tricalculator.factorial(5) 120 """ b = 1 while a != 1: b *= a a -= 1 return b def sin(self, x): """ Calculate the sin value of the x-degree angle :param x: float :return: float >>> tricalculator.sin(30) 0.5 """ x = x / 180 * pi g = 0 t = x n = 1 while fabs(t) >= 1e-15: g += t n += 1 t = -t * x * x / (2 * n - 1) / (2 * n - 2) return round(g, 10) def tan(self, x): """ Calculate the tan value of the x-degree angle :param x: float :return: float >>> tricalculator.tan(45) 1.0 """ if self.cos(x) != 0: result = self.sin(x) / self.cos(x) return round(result, 10) else: return False
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle :param x:float :return:float >>> tricalculator = TriCalculator() >>> tricalculator.cos(60) 0.5 """ def factorial(self, a): """ Calculate the factorial of a :param a: int :return: int >>> tricalculator.factorial(5) 120 """ def sin(self, x): """ Calculate the sin value of the x-degree angle :param x: float :return: float >>> tricalculator.sin(30) 0.5 """ def tan(self, x): """ Calculate the tan value of the x-degree angle :param x: float :return: float >>> tricalculator.tan(45) 1.0 """
def taylor(self, x, n): a = 1 x = x / 180 * pi count = 1 for k in range(1, n): if count % 2 != 0: a -= (x ** (2 * k)) / self.factorial(2 * k) else: a += (x ** (2 * k)) / self.factorial(2 * k) count += 1 return a
Finding the n-order Taylor expansion value of cos (x/180 * pi)
ClassEval_88_sum
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle :param x:float :return:float >>> tricalculator = TriCalculator() >>> tricalculator.cos(60) 0.5 """ return round(self.taylor(x, 50), 10) def factorial(self, a): """ Calculate the factorial of a :param a: int :return: int >>> tricalculator.factorial(5) 120 """ b = 1 while a != 1: b *= a a -= 1 return b def taylor(self, x, n): """ Finding the n-order Taylor expansion value of cos (x/180 * pi) :param x: int :param n: int :return: float >>> tricalculator.taylor(60, 50) 0.5000000000000001 """ a = 1 x = x / 180 * pi count = 1 for k in range(1, n): if count % 2 != 0: a -= (x ** (2 * k)) / self.factorial(2 * k) else: a += (x ** (2 * k)) / self.factorial(2 * k) count += 1 return a def tan(self, x): """ Calculate the tan value of the x-degree angle :param x: float :return: float >>> tricalculator.tan(45) 1.0 """ if self.cos(x) != 0: result = self.sin(x) / self.cos(x) return round(result, 10) else: return False
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle :param x:float :return:float >>> tricalculator = TriCalculator() >>> tricalculator.cos(60) 0.5 """ def factorial(self, a): """ Calculate the factorial of a :param a: int :return: int >>> tricalculator.factorial(5) 120 """ def taylor(self, x, n): """ Finding the n-order Taylor expansion value of cos (x/180 * pi) :param x: int :param n: int :return: float >>> tricalculator.taylor(60, 50) 0.5000000000000001 """ def tan(self, x): """ Calculate the tan value of the x-degree angle :param x: float :return: float >>> tricalculator.tan(45) 1.0 """
def sin(self, x): x = x / 180 * pi g = 0 t = x n = 1 while fabs(t) >= 1e-15: g += t n += 1 t = -t * x * x / (2 * n - 1) / (2 * n - 2) return round(g, 10)
Calculate the sin value of the x-degree angle
ClassEval_88_sum
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle :param x:float :return:float >>> tricalculator = TriCalculator() >>> tricalculator.cos(60) 0.5 """ return round(self.taylor(x, 50), 10) def factorial(self, a): """ Calculate the factorial of a :param a: int :return: int >>> tricalculator.factorial(5) 120 """ b = 1 while a != 1: b *= a a -= 1 return b def taylor(self, x, n): """ Finding the n-order Taylor expansion value of cos (x/180 * pi) :param x: int :param n: int :return: float >>> tricalculator.taylor(60, 50) 0.5000000000000001 """ a = 1 x = x / 180 * pi count = 1 for k in range(1, n): if count % 2 != 0: a -= (x ** (2 * k)) / self.factorial(2 * k) else: a += (x ** (2 * k)) / self.factorial(2 * k) count += 1 return a def sin(self, x): """ Calculate the sin value of the x-degree angle :param x: float :return: float >>> tricalculator.sin(30) 0.5 """ x = x / 180 * pi g = 0 t = x n = 1 while fabs(t) >= 1e-15: g += t n += 1 t = -t * x * x / (2 * n - 1) / (2 * n - 2) return round(g, 10) def tan(self, x): if self.cos(x) != 0: result = self.sin(x) / self.cos(x) return round(result, 10) else: return False
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle :param x:float :return:float >>> tricalculator = TriCalculator() >>> tricalculator.cos(60) 0.5 """ def factorial(self, a): """ Calculate the factorial of a :param a: int :return: int >>> tricalculator.factorial(5) 120 """ def taylor(self, x, n): """ Finding the n-order Taylor expansion value of cos (x/180 * pi) :param x: int :param n: int :return: float >>> tricalculator.taylor(60, 50) 0.5000000000000001 """ def sin(self, x): """ Calculate the sin value of the x-degree angle :param x: float :return: float >>> tricalculator.sin(30) 0.5 """ def tan(self, x): """ Calculate the tan value of the x-degree angle :param x: float :return: float >>> tricalculator.tan(45) 1.0 """
def tan(self, x): if self.cos(x) != 0: result = self.sin(x) / self.cos(x) return round(result, 10) else: return False
Calculate the tan value of the x-degree angle
ClassEval_89_sum
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def get_my_cards(self): """ Get a list of four random numbers between 1 and 9 representing the player's cards. :return: list of integers, representing the player's cards >>> game = TwentyFourPointGame() >>> game.get_my_cards() """ self.nums = [] self._generate_cards() return self.nums def answer(self, expression): """ Check if a given mathematical expression using the cards can evaluate to 24. :param expression: string, mathematical expression using the cards :return: bool, True if the expression evaluates to 24, False otherwise >>> game = TwentyFourPointGame() >>> game.nums = [4, 3, 6, 6] >>> ans = "4*3+6+6" >>> ret = game.answer(ans) True """ if expression == 'pass': return self.get_my_cards() statistic = {} for c in expression: if c.isdigit() and int(c) in self.nums: statistic[c] = statistic.get(c, 0) + 1 nums_used = statistic.copy() for num in self.nums: if nums_used.get(str(num), -100) != -100 and nums_used[str(num)] > 0: nums_used[str(num)] -= 1 else: return False if all(count == 0 for count in nums_used.values()) == True: return self.evaluate_expression(expression) else: return False def evaluate_expression(self, expression): """ Evaluate a mathematical expression and check if the result is 24. :param expression: string, mathematical expression :return: bool, True if the expression evaluates to 24, False otherwise >>> game = TwentyFourPointGame() >>> nums = [4, 3, 6, 6] >>> ans = "4*3+6+6" >>> ret = game.evaluate_expression(ans) True """ try: if eval(expression) == 24: return True else: return False except Exception as e: return False
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def get_my_cards(self): """ Get a list of four random numbers between 1 and 9 representing the player's cards. :return: list of integers, representing the player's cards >>> game = TwentyFourPointGame() >>> game.get_my_cards() """ def answer(self, expression): """ Check if a given mathematical expression using the cards can evaluate to 24. :param expression: string, mathematical expression using the cards :return: bool, True if the expression evaluates to 24, False otherwise >>> game = TwentyFourPointGame() >>> game.nums = [4, 3, 6, 6] >>> ans = "4*3+6+6" >>> ret = game.answer(ans) True """ def evaluate_expression(self, expression): """ Evaluate a mathematical expression and check if the result is 24. :param expression: string, mathematical expression :return: bool, True if the expression evaluates to 24, False otherwise >>> game = TwentyFourPointGame() >>> nums = [4, 3, 6, 6] >>> ans = "4*3+6+6" >>> ret = game.evaluate_expression(ans) True """
def _generate_cards(self): for i in range(4): self.nums.append(random.randint(1, 9)) assert len(self.nums) == 4
Generate random numbers between 1 and 9 for the cards.
ClassEval_89_sum
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def _generate_cards(self): """ Generate random numbers between 1 and 9 for the cards. """ for i in range(4): self.nums.append(random.randint(1, 9)) assert len(self.nums) == 4 def answer(self, expression): """ Check if a given mathematical expression using the cards can evaluate to 24. :param expression: string, mathematical expression using the cards :return: bool, True if the expression evaluates to 24, False otherwise >>> game = TwentyFourPointGame() >>> game.nums = [4, 3, 6, 6] >>> ans = "4*3+6+6" >>> ret = game.answer(ans) True """ if expression == 'pass': return self.get_my_cards() statistic = {} for c in expression: if c.isdigit() and int(c) in self.nums: statistic[c] = statistic.get(c, 0) + 1 nums_used = statistic.copy() for num in self.nums: if nums_used.get(str(num), -100) != -100 and nums_used[str(num)] > 0: nums_used[str(num)] -= 1 else: return False if all(count == 0 for count in nums_used.values()) == True: return self.evaluate_expression(expression) else: return False def evaluate_expression(self, expression): """ Evaluate a mathematical expression and check if the result is 24. :param expression: string, mathematical expression :return: bool, True if the expression evaluates to 24, False otherwise >>> game = TwentyFourPointGame() >>> nums = [4, 3, 6, 6] >>> ans = "4*3+6+6" >>> ret = game.evaluate_expression(ans) True """ try: if eval(expression) == 24: return True else: return False except Exception as e: return False
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def _generate_cards(self): """ Generate random numbers between 1 and 9 for the cards. """ def answer(self, expression): """ Check if a given mathematical expression using the cards can evaluate to 24. :param expression: string, mathematical expression using the cards :return: bool, True if the expression evaluates to 24, False otherwise >>> game = TwentyFourPointGame() >>> game.nums = [4, 3, 6, 6] >>> ans = "4*3+6+6" >>> ret = game.answer(ans) True """ def evaluate_expression(self, expression): """ Evaluate a mathematical expression and check if the result is 24. :param expression: string, mathematical expression :return: bool, True if the expression evaluates to 24, False otherwise >>> game = TwentyFourPointGame() >>> nums = [4, 3, 6, 6] >>> ans = "4*3+6+6" >>> ret = game.evaluate_expression(ans) True """
def get_my_cards(self): self.nums = [] self._generate_cards() return self.nums
Get a list of four random numbers between 1 and 9 representing the player's cards.
ClassEval_89_sum
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def _generate_cards(self): """ Generate random numbers between 1 and 9 for the cards. """ for i in range(4): self.nums.append(random.randint(1, 9)) assert len(self.nums) == 4 def get_my_cards(self): """ Get a list of four random numbers between 1 and 9 representing the player's cards. :return: list of integers, representing the player's cards >>> game = TwentyFourPointGame() >>> game.get_my_cards() """ self.nums = [] self._generate_cards() return self.nums def evaluate_expression(self, expression): """ Evaluate a mathematical expression and check if the result is 24. :param expression: string, mathematical expression :return: bool, True if the expression evaluates to 24, False otherwise >>> game = TwentyFourPointGame() >>> nums = [4, 3, 6, 6] >>> ans = "4*3+6+6" >>> ret = game.evaluate_expression(ans) True """ try: if eval(expression) == 24: return True else: return False except Exception as e: return False
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def _generate_cards(self): """ Generate random numbers between 1 and 9 for the cards. """ def get_my_cards(self): """ Get a list of four random numbers between 1 and 9 representing the player's cards. :return: list of integers, representing the player's cards >>> game = TwentyFourPointGame() >>> game.get_my_cards() """ def evaluate_expression(self, expression): """ Evaluate a mathematical expression and check if the result is 24. :param expression: string, mathematical expression :return: bool, True if the expression evaluates to 24, False otherwise >>> game = TwentyFourPointGame() >>> nums = [4, 3, 6, 6] >>> ans = "4*3+6+6" >>> ret = game.evaluate_expression(ans) True """
def answer(self, expression): if expression == 'pass': return self.get_my_cards() statistic = {} for c in expression: if c.isdigit() and int(c) in self.nums: statistic[c] = statistic.get(c, 0) + 1 nums_used = statistic.copy() for num in self.nums: if nums_used.get(str(num), -100) != -100 and nums_used[str(num)] > 0: nums_used[str(num)] -= 1 else: return False if all(count == 0 for count in nums_used.values()) == True: return self.evaluate_expression(expression) else: return False
Check if a given mathematical expression using the cards can evaluate to 24.
ClassEval_89_sum
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def _generate_cards(self): """ Generate random numbers between 1 and 9 for the cards. """ for i in range(4): self.nums.append(random.randint(1, 9)) assert len(self.nums) == 4 def get_my_cards(self): """ Get a list of four random numbers between 1 and 9 representing the player's cards. :return: list of integers, representing the player's cards >>> game = TwentyFourPointGame() >>> game.get_my_cards() """ self.nums = [] self._generate_cards() return self.nums def answer(self, expression): """ Check if a given mathematical expression using the cards can evaluate to 24. :param expression: string, mathematical expression using the cards :return: bool, True if the expression evaluates to 24, False otherwise >>> game = TwentyFourPointGame() >>> game.nums = [4, 3, 6, 6] >>> ans = "4*3+6+6" >>> ret = game.answer(ans) True """ if expression == 'pass': return self.get_my_cards() statistic = {} for c in expression: if c.isdigit() and int(c) in self.nums: statistic[c] = statistic.get(c, 0) + 1 nums_used = statistic.copy() for num in self.nums: if nums_used.get(str(num), -100) != -100 and nums_used[str(num)] > 0: nums_used[str(num)] -= 1 else: return False if all(count == 0 for count in nums_used.values()) == True: return self.evaluate_expression(expression) else: return False def evaluate_expression(self, expression): try: if eval(expression) == 24: return True else: return False except Exception as e: return False
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def _generate_cards(self): """ Generate random numbers between 1 and 9 for the cards. """ def get_my_cards(self): """ Get a list of four random numbers between 1 and 9 representing the player's cards. :return: list of integers, representing the player's cards >>> game = TwentyFourPointGame() >>> game.get_my_cards() """ def answer(self, expression): """ Check if a given mathematical expression using the cards can evaluate to 24. :param expression: string, mathematical expression using the cards :return: bool, True if the expression evaluates to 24, False otherwise >>> game = TwentyFourPointGame() >>> game.nums = [4, 3, 6, 6] >>> ans = "4*3+6+6" >>> ret = game.answer(ans) True """ def evaluate_expression(self, expression): """ Evaluate a mathematical expression and check if the result is 24. :param expression: string, mathematical expression :return: bool, True if the expression evaluates to 24, False otherwise >>> game = TwentyFourPointGame() >>> nums = [4, 3, 6, 6] >>> ans = "4*3+6+6" >>> ret = game.evaluate_expression(ans) True """
def evaluate_expression(self, expression): try: if eval(expression) == 24: return True else: return False except Exception as e: return False
Evaluate a mathematical expression and check if the result is 24.
ClassEval_90_sum
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): self.url = url def get_host(self): """ Get the second part of the URL, which is the host domain name :return: string, If successful, return the host domain name of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_host() "www.baidu.com" """ scheme_end = self.url.find("://") if scheme_end != -1: url_without_scheme = self.url[scheme_end + 3:] host_end = url_without_scheme.find("/") if host_end != -1: return url_without_scheme[:host_end] return url_without_scheme return None def get_path(self): """ Get the third part of the URL, which is the address of the resource :return: string, If successful, return the address of the resource of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_path() "/s?wd=aaa&rsv_spt=1#page" """ scheme_end = self.url.find("://") if scheme_end != -1: url_without_scheme = self.url[scheme_end + 3:] host_end = url_without_scheme.find("/") if host_end != -1: return url_without_scheme[host_end:] return None def get_query_params(self): """ Get the request parameters for the URL :return: dict, If successful, return the request parameters of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_query_params() {"wd": "aaa", "rsv_spt": "1"} """ query_start = self.url.find("?") fragment_start = self.url.find("#") if query_start != -1: query_string = self.url[query_start + 1:fragment_start] params = {} if len(query_string) > 0: param_pairs = query_string.split("&") for pair in param_pairs: key_value = pair.split("=") if len(key_value) == 2: key, value = key_value params[key] = value return params return None def get_fragment(self): """ Get the fragment after '#' in the URL :return: string, If successful, return the fragment after '#' of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_fragment() "page" """ fragment_start = self.url.find("#") if fragment_start != -1: return self.url[fragment_start + 1:] return None
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): """ Initialize URLHandler's URL """ self.url = url def get_host(self): """ Get the second part of the URL, which is the host domain name :return: string, If successful, return the host domain name of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_host() "www.baidu.com" """ def get_path(self): """ Get the third part of the URL, which is the address of the resource :return: string, If successful, return the address of the resource of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_path() "/s?wd=aaa&rsv_spt=1#page" """ def get_query_params(self): """ Get the request parameters for the URL :return: dict, If successful, return the request parameters of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_query_params() {"wd": "aaa", "rsv_spt": "1"} """ def get_fragment(self): """ Get the fragment after '#' in the URL :return: string, If successful, return the fragment after '#' of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_fragment() "page" """
def get_scheme(self): scheme_end = self.url.find("://") if scheme_end != -1: return self.url[:scheme_end] return None
get the scheme of the URL
ClassEval_90_sum
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): self.url = url def get_scheme(self): """ get the scheme of the URL :return: string, If successful, return the scheme of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_scheme() "https" """ scheme_end = self.url.find("://") if scheme_end != -1: return self.url[:scheme_end] return None def get_path(self): """ Get the third part of the URL, which is the address of the resource :return: string, If successful, return the address of the resource of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_path() "/s?wd=aaa&rsv_spt=1#page" """ scheme_end = self.url.find("://") if scheme_end != -1: url_without_scheme = self.url[scheme_end + 3:] host_end = url_without_scheme.find("/") if host_end != -1: return url_without_scheme[host_end:] return None def get_query_params(self): """ Get the request parameters for the URL :return: dict, If successful, return the request parameters of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_query_params() {"wd": "aaa", "rsv_spt": "1"} """ query_start = self.url.find("?") fragment_start = self.url.find("#") if query_start != -1: query_string = self.url[query_start + 1:fragment_start] params = {} if len(query_string) > 0: param_pairs = query_string.split("&") for pair in param_pairs: key_value = pair.split("=") if len(key_value) == 2: key, value = key_value params[key] = value return params return None def get_fragment(self): """ Get the fragment after '#' in the URL :return: string, If successful, return the fragment after '#' of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_fragment() "page" """ fragment_start = self.url.find("#") if fragment_start != -1: return self.url[fragment_start + 1:] return None
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): """ Initialize URLHandler's URL """ self.url = url def get_scheme(self): """ get the scheme of the URL :return: string, If successful, return the scheme of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_scheme() "https" """ def get_path(self): """ Get the third part of the URL, which is the address of the resource :return: string, If successful, return the address of the resource of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_path() "/s?wd=aaa&rsv_spt=1#page" """ def get_query_params(self): """ Get the request parameters for the URL :return: dict, If successful, return the request parameters of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_query_params() {"wd": "aaa", "rsv_spt": "1"} """ def get_fragment(self): """ Get the fragment after '#' in the URL :return: string, If successful, return the fragment after '#' of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_fragment() "page" """
def get_host(self): scheme_end = self.url.find("://") if scheme_end != -1: url_without_scheme = self.url[scheme_end + 3:] host_end = url_without_scheme.find("/") if host_end != -1: return url_without_scheme[:host_end] return url_without_scheme return None
Get the second part of the URL, which is the host domain name
ClassEval_90_sum
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): self.url = url def get_scheme(self): """ get the scheme of the URL :return: string, If successful, return the scheme of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_scheme() "https" """ scheme_end = self.url.find("://") if scheme_end != -1: return self.url[:scheme_end] return None def get_host(self): """ Get the second part of the URL, which is the host domain name :return: string, If successful, return the host domain name of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_host() "www.baidu.com" """ scheme_end = self.url.find("://") if scheme_end != -1: url_without_scheme = self.url[scheme_end + 3:] host_end = url_without_scheme.find("/") if host_end != -1: return url_without_scheme[:host_end] return url_without_scheme return None def get_query_params(self): """ Get the request parameters for the URL :return: dict, If successful, return the request parameters of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_query_params() {"wd": "aaa", "rsv_spt": "1"} """ query_start = self.url.find("?") fragment_start = self.url.find("#") if query_start != -1: query_string = self.url[query_start + 1:fragment_start] params = {} if len(query_string) > 0: param_pairs = query_string.split("&") for pair in param_pairs: key_value = pair.split("=") if len(key_value) == 2: key, value = key_value params[key] = value return params return None def get_fragment(self): """ Get the fragment after '#' in the URL :return: string, If successful, return the fragment after '#' of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_fragment() "page" """ fragment_start = self.url.find("#") if fragment_start != -1: return self.url[fragment_start + 1:] return None
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): """ Initialize URLHandler's URL """ self.url = url def get_scheme(self): """ get the scheme of the URL :return: string, If successful, return the scheme of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_scheme() "https" """ def get_host(self): """ Get the second part of the URL, which is the host domain name :return: string, If successful, return the host domain name of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_host() "www.baidu.com" """ def get_query_params(self): """ Get the request parameters for the URL :return: dict, If successful, return the request parameters of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_query_params() {"wd": "aaa", "rsv_spt": "1"} """ def get_fragment(self): """ Get the fragment after '#' in the URL :return: string, If successful, return the fragment after '#' of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_fragment() "page" """
def get_path(self): scheme_end = self.url.find("://") if scheme_end != -1: url_without_scheme = self.url[scheme_end + 3:] host_end = url_without_scheme.find("/") if host_end != -1: return url_without_scheme[host_end:] return None
Get the third part of the URL, which is the address of the resource
ClassEval_90_sum
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): self.url = url def get_scheme(self): """ get the scheme of the URL :return: string, If successful, return the scheme of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_scheme() "https" """ scheme_end = self.url.find("://") if scheme_end != -1: return self.url[:scheme_end] return None def get_host(self): """ Get the second part of the URL, which is the host domain name :return: string, If successful, return the host domain name of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_host() "www.baidu.com" """ scheme_end = self.url.find("://") if scheme_end != -1: url_without_scheme = self.url[scheme_end + 3:] host_end = url_without_scheme.find("/") if host_end != -1: return url_without_scheme[:host_end] return url_without_scheme return None def get_path(self): """ Get the third part of the URL, which is the address of the resource :return: string, If successful, return the address of the resource of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_path() "/s?wd=aaa&rsv_spt=1#page" """ scheme_end = self.url.find("://") if scheme_end != -1: url_without_scheme = self.url[scheme_end + 3:] host_end = url_without_scheme.find("/") if host_end != -1: return url_without_scheme[host_end:] return None def get_fragment(self): """ Get the fragment after '#' in the URL :return: string, If successful, return the fragment after '#' of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_fragment() "page" """ fragment_start = self.url.find("#") if fragment_start != -1: return self.url[fragment_start + 1:] return None
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): """ Initialize URLHandler's URL """ self.url = url def get_scheme(self): """ get the scheme of the URL :return: string, If successful, return the scheme of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_scheme() "https" """ def get_host(self): """ Get the second part of the URL, which is the host domain name :return: string, If successful, return the host domain name of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_host() "www.baidu.com" """ def get_path(self): """ Get the third part of the URL, which is the address of the resource :return: string, If successful, return the address of the resource of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_path() "/s?wd=aaa&rsv_spt=1#page" """ def get_fragment(self): """ Get the fragment after '#' in the URL :return: string, If successful, return the fragment after '#' of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_fragment() "page" """
def get_query_params(self): query_start = self.url.find("?") fragment_start = self.url.find("#") if query_start != -1: query_string = self.url[query_start + 1:fragment_start] params = {} if len(query_string) > 0: param_pairs = query_string.split("&") for pair in param_pairs: key_value = pair.split("=") if len(key_value) == 2: key, value = key_value params[key] = value return params return None
Get the request parameters for the URL
ClassEval_90_sum
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): self.url = url def get_scheme(self): """ get the scheme of the URL :return: string, If successful, return the scheme of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_scheme() "https" """ scheme_end = self.url.find("://") if scheme_end != -1: return self.url[:scheme_end] return None def get_host(self): """ Get the second part of the URL, which is the host domain name :return: string, If successful, return the host domain name of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_host() "www.baidu.com" """ scheme_end = self.url.find("://") if scheme_end != -1: url_without_scheme = self.url[scheme_end + 3:] host_end = url_without_scheme.find("/") if host_end != -1: return url_without_scheme[:host_end] return url_without_scheme return None def get_path(self): """ Get the third part of the URL, which is the address of the resource :return: string, If successful, return the address of the resource of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_path() "/s?wd=aaa&rsv_spt=1#page" """ scheme_end = self.url.find("://") if scheme_end != -1: url_without_scheme = self.url[scheme_end + 3:] host_end = url_without_scheme.find("/") if host_end != -1: return url_without_scheme[host_end:] return None def get_query_params(self): """ Get the request parameters for the URL :return: dict, If successful, return the request parameters of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_query_params() {"wd": "aaa", "rsv_spt": "1"} """ query_start = self.url.find("?") fragment_start = self.url.find("#") if query_start != -1: query_string = self.url[query_start + 1:fragment_start] params = {} if len(query_string) > 0: param_pairs = query_string.split("&") for pair in param_pairs: key_value = pair.split("=") if len(key_value) == 2: key, value = key_value params[key] = value return params return None def get_fragment(self): fragment_start = self.url.find("#") if fragment_start != -1: return self.url[fragment_start + 1:] return None
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): """ Initialize URLHandler's URL """ self.url = url def get_scheme(self): """ get the scheme of the URL :return: string, If successful, return the scheme of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_scheme() "https" """ def get_host(self): """ Get the second part of the URL, which is the host domain name :return: string, If successful, return the host domain name of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_host() "www.baidu.com" """ def get_path(self): """ Get the third part of the URL, which is the address of the resource :return: string, If successful, return the address of the resource of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_path() "/s?wd=aaa&rsv_spt=1#page" """ def get_query_params(self): """ Get the request parameters for the URL :return: dict, If successful, return the request parameters of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_query_params() {"wd": "aaa", "rsv_spt": "1"} """ def get_fragment(self): """ Get the fragment after '#' in the URL :return: string, If successful, return the fragment after '#' of the URL >>> urlhandler = URLHandler("https://www.baidu.com/s?wd=aaa&rsv_spt=1#page") >>> urlhandler.get_fragment() "page" """
def get_fragment(self): fragment_start = self.url.find("#") if fragment_start != -1: return self.url[fragment_start + 1:] return None
Get the fragment after '#' in the URL
ClassEval_91_sum
import urllib.parse class UrlPath: """ The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding. """ def __init__(self): self.segments = [] self.with_end_tag = False def parse(self, path, charset): """ Parses a given path string and populates the list of segments in the UrlPath. :param path: str, the path string to parse. :param charset: str, the character encoding of the path string. >>> url_path = UrlPath() >>> url_path.parse('/foo/bar/', 'utf-8') url_path.segments = ['foo', 'bar'] """ if path: if path.endswith('/'): self.with_end_tag = True path = self.fix_path(path) if path: split = path.split('/') for seg in split: decoded_seg = urllib.parse.unquote(seg, encoding=charset) self.segments.append(decoded_seg) @staticmethod def fix_path(path): """ Fixes the given path string by removing leading and trailing slashes. :param path: str, the path string to fix. :return: str, the fixed path string. >>> url_path = UrlPath() >>> url_path.fix_path('/foo/bar/') 'foo/bar' """ if not path: return '' segment_str = path.strip('/') return segment_str
import urllib.parse class UrlPath: """ The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding. """ def __init__(self): """ Initializes the UrlPath object with an empty list of segments and a flag indicating the presence of an end tag. """ self.segments = [] self.with_end_tag = False def parse(self, path, charset): """ Parses a given path string and populates the list of segments in the UrlPath. :param path: str, the path string to parse. :param charset: str, the character encoding of the path string. >>> url_path = UrlPath() >>> url_path.parse('/foo/bar/', 'utf-8') url_path.segments = ['foo', 'bar'] """ @staticmethod def fix_path(path): """ Fixes the given path string by removing leading and trailing slashes. :param path: str, the path string to fix. :return: str, the fixed path string. >>> url_path = UrlPath() >>> url_path.fix_path('/foo/bar/') 'foo/bar' """
def add(self, segment): self.segments.append(self.fix_path(segment))
Adds a segment to the list of segments in the UrlPath.
ClassEval_91_sum
import urllib.parse class UrlPath: """ The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding. """ def __init__(self): self.segments = [] self.with_end_tag = False def add(self, segment): """ Adds a segment to the list of segments in the UrlPath. :param segment: str, the segment to add. >>> url_path = UrlPath() >>> url_path.add('foo') >>> url_path.add('bar') url_path.segments = ['foo', 'bar'] """ self.segments.append(self.fix_path(segment)) @staticmethod def fix_path(path): """ Fixes the given path string by removing leading and trailing slashes. :param path: str, the path string to fix. :return: str, the fixed path string. >>> url_path = UrlPath() >>> url_path.fix_path('/foo/bar/') 'foo/bar' """ if not path: return '' segment_str = path.strip('/') return segment_str
import urllib.parse class UrlPath: """ The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding. """ def __init__(self): """ Initializes the UrlPath object with an empty list of segments and a flag indicating the presence of an end tag. """ self.segments = [] self.with_end_tag = False def add(self, segment): """ Adds a segment to the list of segments in the UrlPath. :param segment: str, the segment to add. >>> url_path = UrlPath() >>> url_path.add('foo') >>> url_path.add('bar') url_path.segments = ['foo', 'bar'] """ @staticmethod def fix_path(path): """ Fixes the given path string by removing leading and trailing slashes. :param path: str, the path string to fix. :return: str, the fixed path string. >>> url_path = UrlPath() >>> url_path.fix_path('/foo/bar/') 'foo/bar' """
def parse(self, path, charset): if path: if path.endswith('/'): self.with_end_tag = True path = self.fix_path(path) if path: split = path.split('/') for seg in split: decoded_seg = urllib.parse.unquote(seg, encoding=charset) self.segments.append(decoded_seg)
Parses a given path string and populates the list of segments in the UrlPath.
ClassEval_91_sum
import urllib.parse class UrlPath: """ The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding. """ def __init__(self): self.segments = [] self.with_end_tag = False def add(self, segment): """ Adds a segment to the list of segments in the UrlPath. :param segment: str, the segment to add. >>> url_path = UrlPath() >>> url_path.add('foo') >>> url_path.add('bar') url_path.segments = ['foo', 'bar'] """ self.segments.append(self.fix_path(segment)) def parse(self, path, charset): """ Parses a given path string and populates the list of segments in the UrlPath. :param path: str, the path string to parse. :param charset: str, the character encoding of the path string. >>> url_path = UrlPath() >>> url_path.parse('/foo/bar/', 'utf-8') url_path.segments = ['foo', 'bar'] """ if path: if path.endswith('/'): self.with_end_tag = True path = self.fix_path(path) if path: split = path.split('/') for seg in split: decoded_seg = urllib.parse.unquote(seg, encoding=charset) self.segments.append(decoded_seg) @staticmethod def fix_path(path): if not path: return '' segment_str = path.strip('/') return segment_str
import urllib.parse class UrlPath: """ The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding. """ def __init__(self): """ Initializes the UrlPath object with an empty list of segments and a flag indicating the presence of an end tag. """ self.segments = [] self.with_end_tag = False def add(self, segment): """ Adds a segment to the list of segments in the UrlPath. :param segment: str, the segment to add. >>> url_path = UrlPath() >>> url_path.add('foo') >>> url_path.add('bar') url_path.segments = ['foo', 'bar'] """ def parse(self, path, charset): """ Parses a given path string and populates the list of segments in the UrlPath. :param path: str, the path string to parse. :param charset: str, the character encoding of the path string. >>> url_path = UrlPath() >>> url_path.parse('/foo/bar/', 'utf-8') url_path.segments = ['foo', 'bar'] """ @staticmethod def fix_path(path): """ Fixes the given path string by removing leading and trailing slashes. :param path: str, the path string to fix. :return: str, the fixed path string. >>> url_path = UrlPath() >>> url_path.fix_path('/foo/bar/') 'foo/bar' """
@staticmethod def fix_path(path): if not path: return '' segment_str = path.strip('/') return segment_str
Fixes the given path string by removing leading and trailing slashes.
ClassEval_92_sum
import sqlite3 class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() def search_user_by_username(self, username): """ Searches for users in the "users" table by username. :param username: str, the username of the user to search for. :return:list of tuples, the rows from the "users" table that match the search criteria. >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> result = user_db.search_user_by_username('user1') len(result) = 1 """ self.cursor.execute(''' SELECT * FROM users WHERE username = ? ''', (username,)) user = self.cursor.fetchone() return user def delete_user_by_username(self, username): """ Deletes a user from the "users" table by username. :param username: str, the username of the user to delete. :return: None >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> user_db.delete_user_by_username('user1') """ self.cursor.execute(''' DELETE FROM users WHERE username = ? ''', (username,)) self.connection.commit() def validate_user_login(self, username, password): """ Determine whether the user can log in, that is, the user is in the database and the password is correct :param username:str, the username of the user to validate. :param password:str, the password of the user to validate. :return:bool, representing whether the user can log in correctly >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> user_db.validate_user_login('user1', 'pass1') True """ user = self.search_user_by_username(username) if user is not None and user[1] == password: return True return False
class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): """ Initializes the UserLoginDB object with the specified database name. :param db_name: str, the name of the SQLite database. """ self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() def search_user_by_username(self, username): """ Searches for users in the "users" table by username. :param username: str, the username of the user to search for. :return:list of tuples, the rows from the "users" table that match the search criteria. >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> result = user_db.search_user_by_username('user1') len(result) = 1 """ def delete_user_by_username(self, username): """ Deletes a user from the "users" table by username. :param username: str, the username of the user to delete. :return: None >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> user_db.delete_user_by_username('user1') """ def validate_user_login(self, username, password): """ Determine whether the user can log in, that is, the user is in the database and the password is correct :param username:str, the username of the user to validate. :param password:str, the password of the user to validate. :return:bool, representing whether the user can log in correctly >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> user_db.validate_user_login('user1', 'pass1') True """
def insert_user(self, username, password): self.cursor.execute(''' INSERT INTO users (username, password) VALUES (?, ?) ''', (username, password)) self.connection.commit()
Inserts a new user into the "users" table.
ClassEval_92_sum
import sqlite3 class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() def insert_user(self, username, password): """ Inserts a new user into the "users" table. :param username: str, the username of the user. :param password: str, the password of the user. :return: None >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') """ self.cursor.execute(''' INSERT INTO users (username, password) VALUES (?, ?) ''', (username, password)) self.connection.commit() def delete_user_by_username(self, username): """ Deletes a user from the "users" table by username. :param username: str, the username of the user to delete. :return: None >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> user_db.delete_user_by_username('user1') """ self.cursor.execute(''' DELETE FROM users WHERE username = ? ''', (username,)) self.connection.commit() def validate_user_login(self, username, password): """ Determine whether the user can log in, that is, the user is in the database and the password is correct :param username:str, the username of the user to validate. :param password:str, the password of the user to validate. :return:bool, representing whether the user can log in correctly >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> user_db.validate_user_login('user1', 'pass1') True """ user = self.search_user_by_username(username) if user is not None and user[1] == password: return True return False
class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): """ Initializes the UserLoginDB object with the specified database name. :param db_name: str, the name of the SQLite database. """ self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() def insert_user(self, username, password): """ Inserts a new user into the "users" table. :param username: str, the username of the user. :param password: str, the password of the user. :return: None >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') """ def delete_user_by_username(self, username): """ Deletes a user from the "users" table by username. :param username: str, the username of the user to delete. :return: None >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> user_db.delete_user_by_username('user1') """ def validate_user_login(self, username, password): """ Determine whether the user can log in, that is, the user is in the database and the password is correct :param username:str, the username of the user to validate. :param password:str, the password of the user to validate. :return:bool, representing whether the user can log in correctly >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> user_db.validate_user_login('user1', 'pass1') True """
def search_user_by_username(self, username): self.cursor.execute(''' SELECT * FROM users WHERE username = ? ''', (username,)) user = self.cursor.fetchone() return user
Searches for users in the "users" table by username.
ClassEval_92_sum
import sqlite3 class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() def insert_user(self, username, password): """ Inserts a new user into the "users" table. :param username: str, the username of the user. :param password: str, the password of the user. :return: None >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') """ self.cursor.execute(''' INSERT INTO users (username, password) VALUES (?, ?) ''', (username, password)) self.connection.commit() def search_user_by_username(self, username): """ Searches for users in the "users" table by username. :param username: str, the username of the user to search for. :return:list of tuples, the rows from the "users" table that match the search criteria. >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> result = user_db.search_user_by_username('user1') len(result) = 1 """ self.cursor.execute(''' SELECT * FROM users WHERE username = ? ''', (username,)) user = self.cursor.fetchone() return user def validate_user_login(self, username, password): """ Determine whether the user can log in, that is, the user is in the database and the password is correct :param username:str, the username of the user to validate. :param password:str, the password of the user to validate. :return:bool, representing whether the user can log in correctly >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> user_db.validate_user_login('user1', 'pass1') True """ user = self.search_user_by_username(username) if user is not None and user[1] == password: return True return False
class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): """ Initializes the UserLoginDB object with the specified database name. :param db_name: str, the name of the SQLite database. """ self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() def insert_user(self, username, password): """ Inserts a new user into the "users" table. :param username: str, the username of the user. :param password: str, the password of the user. :return: None >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') """ def search_user_by_username(self, username): """ Searches for users in the "users" table by username. :param username: str, the username of the user to search for. :return:list of tuples, the rows from the "users" table that match the search criteria. >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> result = user_db.search_user_by_username('user1') len(result) = 1 """ def validate_user_login(self, username, password): """ Determine whether the user can log in, that is, the user is in the database and the password is correct :param username:str, the username of the user to validate. :param password:str, the password of the user to validate. :return:bool, representing whether the user can log in correctly >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> user_db.validate_user_login('user1', 'pass1') True """
def delete_user_by_username(self, username): self.cursor.execute(''' DELETE FROM users WHERE username = ? ''', (username,)) self.connection.commit()
Deletes a user from the "users" table by username.
ClassEval_92_sum
import sqlite3 class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() def insert_user(self, username, password): """ Inserts a new user into the "users" table. :param username: str, the username of the user. :param password: str, the password of the user. :return: None >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') """ self.cursor.execute(''' INSERT INTO users (username, password) VALUES (?, ?) ''', (username, password)) self.connection.commit() def search_user_by_username(self, username): """ Searches for users in the "users" table by username. :param username: str, the username of the user to search for. :return:list of tuples, the rows from the "users" table that match the search criteria. >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> result = user_db.search_user_by_username('user1') len(result) = 1 """ self.cursor.execute(''' SELECT * FROM users WHERE username = ? ''', (username,)) user = self.cursor.fetchone() return user def delete_user_by_username(self, username): """ Deletes a user from the "users" table by username. :param username: str, the username of the user to delete. :return: None >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> user_db.delete_user_by_username('user1') """ self.cursor.execute(''' DELETE FROM users WHERE username = ? ''', (username,)) self.connection.commit() def validate_user_login(self, username, password): user = self.search_user_by_username(username) if user is not None and user[1] == password: return True return False
class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): """ Initializes the UserLoginDB object with the specified database name. :param db_name: str, the name of the SQLite database. """ self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() def insert_user(self, username, password): """ Inserts a new user into the "users" table. :param username: str, the username of the user. :param password: str, the password of the user. :return: None >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') """ def search_user_by_username(self, username): """ Searches for users in the "users" table by username. :param username: str, the username of the user to search for. :return:list of tuples, the rows from the "users" table that match the search criteria. >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> result = user_db.search_user_by_username('user1') len(result) = 1 """ def delete_user_by_username(self, username): """ Deletes a user from the "users" table by username. :param username: str, the username of the user to delete. :return: None >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> user_db.delete_user_by_username('user1') """ def validate_user_login(self, username, password): """ Determine whether the user can log in, that is, the user is in the database and the password is correct :param username:str, the username of the user to validate. :param password:str, the password of the user to validate. :return:bool, representing whether the user can log in correctly >>> user_db = UserLoginDB("user_database.db") >>> user_db.create_table() >>> user_db.insert_user('user1', 'pass1') >>> user_db.validate_user_login('user1', 'pass1') True """
def validate_user_login(self, username, password): user = self.search_user_by_username(username) if user is not None and user[1] == password: return True return False
Determine whether the user can log in, that is, the user is in the database and the password is correct
ClassEval_93_sum
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod @staticmethod def cosine_similarities(vector_1, vectors_all): """ Compute cosine similarities between one vector and a set of other vectors. :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :param vectors_all: list of numpy.ndarray, For each row in vectors_all, distance from vector_1 is computed, expected shape (num_vectors, dim). :return: numpy.ndarray, Contains cosine distance between `vector_1` and each row in `vectors_all`, shape (num_vectors,). >>> vector1 = np.array([1, 2, 3]) >>> vectors_all = [np.array([4, 5, 6]), np.array([7, 8, 9])] >>> VectorUtil.cosine_similarities(vector1, vectors_all) [0.97463185 0.95941195] """ norm = np.linalg.norm(vector_1) all_norms = np.linalg.norm(vectors_all, axis=1) dot_products = dot(vectors_all, vector_1) similarities = dot_products / (norm * all_norms) return similarities @staticmethod def n_similarity(vector_list_1, vector_list_2): """ Compute cosine similarity between two sets of vectors. :param vector_list_1: list of numpy vector :param vector_list_2: list of numpy vector :return: numpy.ndarray, Similarities between vector_list_1 and vector_list_2. >>> vector_list1 = [np.array([1, 2, 3]), np.array([4, 5, 6])] >>> vector_list2 = [np.array([7, 8, 9]), np.array([10, 11, 12])] >>> VectorUtil.n_similarity(vector_list1, vector_list2) 0.9897287473881233 """ if not (len(vector_list_1) and len(vector_list_2)): raise ZeroDivisionError('At least one of the passed list is empty.') return dot(matutils.unitvec(array(vector_list_1).mean(axis=0)), matutils.unitvec(array(vector_list_2).mean(axis=0))) @staticmethod def compute_idf_weight_dict(total_num, number_dict): """ Calculate log(total_num+1/count+1) for each count in number_dict :param total_num: int :param number_dict: dict :return: dict >>> num_dict = {'key1':0.1, 'key2':0.5} >>> VectorUtil.compute_idf_weight_dict(2, num_dict) {'key1': 1.0033021088637848, 'key2': 0.6931471805599453} """ index_2_key_map = {} index = 0 count_list = [] for key, count in number_dict.items(): index_2_key_map[index] = key count_list.append(count) index = index + 1 a = np.array(count_list) ## smooth, in case the divide by zero error a = np.log((total_num + 1) / (a + 1)) result = {} for index, w in enumerate(a): key = index_2_key_map[index] result[key] = w return result
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod @staticmethod def cosine_similarities(vector_1, vectors_all): """ Compute cosine similarities between one vector and a set of other vectors. :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :param vectors_all: list of numpy.ndarray, For each row in vectors_all, distance from vector_1 is computed, expected shape (num_vectors, dim). :return: numpy.ndarray, Contains cosine distance between `vector_1` and each row in `vectors_all`, shape (num_vectors,). >>> vector1 = np.array([1, 2, 3]) >>> vectors_all = [np.array([4, 5, 6]), np.array([7, 8, 9])] >>> VectorUtil.cosine_similarities(vector1, vectors_all) [0.97463185 0.95941195] """ @staticmethod def n_similarity(vector_list_1, vector_list_2): """ Compute cosine similarity between two sets of vectors. :param vector_list_1: list of numpy vector :param vector_list_2: list of numpy vector :return: numpy.ndarray, Similarities between vector_list_1 and vector_list_2. >>> vector_list1 = [np.array([1, 2, 3]), np.array([4, 5, 6])] >>> vector_list2 = [np.array([7, 8, 9]), np.array([10, 11, 12])] >>> VectorUtil.n_similarity(vector_list1, vector_list2) 0.9897287473881233 """ @staticmethod def compute_idf_weight_dict(total_num, number_dict): """ Calculate log(total_num+1/count+1) for each count in number_dict :param total_num: int :param number_dict: dict :return: dict >>> num_dict = {'key1':0.1, 'key2':0.5} >>> VectorUtil.compute_idf_weight_dict(2, num_dict) {'key1': 1.0033021088637848, 'key2': 0.6931471805599453} """
def similarity(vector_1, vector_2): return dot(matutils.unitvec(vector_1), matutils.unitvec(vector_2))
Compute the cosine similarity between one vector and another vector.
ClassEval_93_sum
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod def similarity(vector_1, vector_2): """ Compute the cosine similarity between one vector and another vector. :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :param vector_2: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :return: numpy.ndarray, Contains cosine distance between `vector_1` and `vector_2` >>> vector_1 = np.array([1, 1]) >>> vector_2 = np.array([1, 0]) >>> VectorUtil.similarity(vector_1, vector_2) 0.7071067811865475 """ return dot(matutils.unitvec(vector_1), matutils.unitvec(vector_2)) @staticmethod def n_similarity(vector_list_1, vector_list_2): """ Compute cosine similarity between two sets of vectors. :param vector_list_1: list of numpy vector :param vector_list_2: list of numpy vector :return: numpy.ndarray, Similarities between vector_list_1 and vector_list_2. >>> vector_list1 = [np.array([1, 2, 3]), np.array([4, 5, 6])] >>> vector_list2 = [np.array([7, 8, 9]), np.array([10, 11, 12])] >>> VectorUtil.n_similarity(vector_list1, vector_list2) 0.9897287473881233 """ if not (len(vector_list_1) and len(vector_list_2)): raise ZeroDivisionError('At least one of the passed list is empty.') return dot(matutils.unitvec(array(vector_list_1).mean(axis=0)), matutils.unitvec(array(vector_list_2).mean(axis=0))) @staticmethod def compute_idf_weight_dict(total_num, number_dict): """ Calculate log(total_num+1/count+1) for each count in number_dict :param total_num: int :param number_dict: dict :return: dict >>> num_dict = {'key1':0.1, 'key2':0.5} >>> VectorUtil.compute_idf_weight_dict(2, num_dict) {'key1': 1.0033021088637848, 'key2': 0.6931471805599453} """ index_2_key_map = {} index = 0 count_list = [] for key, count in number_dict.items(): index_2_key_map[index] = key count_list.append(count) index = index + 1 a = np.array(count_list) ## smooth, in case the divide by zero error a = np.log((total_num + 1) / (a + 1)) result = {} for index, w in enumerate(a): key = index_2_key_map[index] result[key] = w return result
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod def similarity(vector_1, vector_2): """ Compute the cosine similarity between one vector and another vector. :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :param vector_2: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :return: numpy.ndarray, Contains cosine distance between `vector_1` and `vector_2` >>> vector_1 = np.array([1, 1]) >>> vector_2 = np.array([1, 0]) >>> VectorUtil.similarity(vector_1, vector_2) 0.7071067811865475 """ @staticmethod def n_similarity(vector_list_1, vector_list_2): """ Compute cosine similarity between two sets of vectors. :param vector_list_1: list of numpy vector :param vector_list_2: list of numpy vector :return: numpy.ndarray, Similarities between vector_list_1 and vector_list_2. >>> vector_list1 = [np.array([1, 2, 3]), np.array([4, 5, 6])] >>> vector_list2 = [np.array([7, 8, 9]), np.array([10, 11, 12])] >>> VectorUtil.n_similarity(vector_list1, vector_list2) 0.9897287473881233 """ @staticmethod def compute_idf_weight_dict(total_num, number_dict): """ Calculate log(total_num+1/count+1) for each count in number_dict :param total_num: int :param number_dict: dict :return: dict >>> num_dict = {'key1':0.1, 'key2':0.5} >>> VectorUtil.compute_idf_weight_dict(2, num_dict) {'key1': 1.0033021088637848, 'key2': 0.6931471805599453} """
@staticmethod def cosine_similarities(vector_1, vectors_all): norm = np.linalg.norm(vector_1) all_norms = np.linalg.norm(vectors_all, axis=1) dot_products = dot(vectors_all, vector_1) similarities = dot_products / (norm * all_norms) return similarities
Compute cosine similarities between one vector and a set of other vectors.
ClassEval_93_sum
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod def similarity(vector_1, vector_2): """ Compute the cosine similarity between one vector and another vector. :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :param vector_2: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :return: numpy.ndarray, Contains cosine distance between `vector_1` and `vector_2` >>> vector_1 = np.array([1, 1]) >>> vector_2 = np.array([1, 0]) >>> VectorUtil.similarity(vector_1, vector_2) 0.7071067811865475 """ return dot(matutils.unitvec(vector_1), matutils.unitvec(vector_2)) @staticmethod def cosine_similarities(vector_1, vectors_all): """ Compute cosine similarities between one vector and a set of other vectors. :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :param vectors_all: list of numpy.ndarray, For each row in vectors_all, distance from vector_1 is computed, expected shape (num_vectors, dim). :return: numpy.ndarray, Contains cosine distance between `vector_1` and each row in `vectors_all`, shape (num_vectors,). >>> vector1 = np.array([1, 2, 3]) >>> vectors_all = [np.array([4, 5, 6]), np.array([7, 8, 9])] >>> VectorUtil.cosine_similarities(vector1, vectors_all) [0.97463185 0.95941195] """ norm = np.linalg.norm(vector_1) all_norms = np.linalg.norm(vectors_all, axis=1) dot_products = dot(vectors_all, vector_1) similarities = dot_products / (norm * all_norms) return similarities @staticmethod def compute_idf_weight_dict(total_num, number_dict): """ Calculate log(total_num+1/count+1) for each count in number_dict :param total_num: int :param number_dict: dict :return: dict >>> num_dict = {'key1':0.1, 'key2':0.5} >>> VectorUtil.compute_idf_weight_dict(2, num_dict) {'key1': 1.0033021088637848, 'key2': 0.6931471805599453} """ index_2_key_map = {} index = 0 count_list = [] for key, count in number_dict.items(): index_2_key_map[index] = key count_list.append(count) index = index + 1 a = np.array(count_list) ## smooth, in case the divide by zero error a = np.log((total_num + 1) / (a + 1)) result = {} for index, w in enumerate(a): key = index_2_key_map[index] result[key] = w return result
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod def similarity(vector_1, vector_2): """ Compute the cosine similarity between one vector and another vector. :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :param vector_2: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :return: numpy.ndarray, Contains cosine distance between `vector_1` and `vector_2` >>> vector_1 = np.array([1, 1]) >>> vector_2 = np.array([1, 0]) >>> VectorUtil.similarity(vector_1, vector_2) 0.7071067811865475 """ @staticmethod def cosine_similarities(vector_1, vectors_all): """ Compute cosine similarities between one vector and a set of other vectors. :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :param vectors_all: list of numpy.ndarray, For each row in vectors_all, distance from vector_1 is computed, expected shape (num_vectors, dim). :return: numpy.ndarray, Contains cosine distance between `vector_1` and each row in `vectors_all`, shape (num_vectors,). >>> vector1 = np.array([1, 2, 3]) >>> vectors_all = [np.array([4, 5, 6]), np.array([7, 8, 9])] >>> VectorUtil.cosine_similarities(vector1, vectors_all) [0.97463185 0.95941195] """ @staticmethod def compute_idf_weight_dict(total_num, number_dict): """ Calculate log(total_num+1/count+1) for each count in number_dict :param total_num: int :param number_dict: dict :return: dict >>> num_dict = {'key1':0.1, 'key2':0.5} >>> VectorUtil.compute_idf_weight_dict(2, num_dict) {'key1': 1.0033021088637848, 'key2': 0.6931471805599453} """
@staticmethod def n_similarity(vector_list_1, vector_list_2): if not (len(vector_list_1) and len(vector_list_2)): raise ZeroDivisionError('At least one of the passed list is empty.') return dot(matutils.unitvec(array(vector_list_1).mean(axis=0)), matutils.unitvec(array(vector_list_2).mean(axis=0)))
Compute cosine similarity between two sets of vectors.
ClassEval_93_sum
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod def similarity(vector_1, vector_2): """ Compute the cosine similarity between one vector and another vector. :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :param vector_2: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :return: numpy.ndarray, Contains cosine distance between `vector_1` and `vector_2` >>> vector_1 = np.array([1, 1]) >>> vector_2 = np.array([1, 0]) >>> VectorUtil.similarity(vector_1, vector_2) 0.7071067811865475 """ return dot(matutils.unitvec(vector_1), matutils.unitvec(vector_2)) @staticmethod def cosine_similarities(vector_1, vectors_all): """ Compute cosine similarities between one vector and a set of other vectors. :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :param vectors_all: list of numpy.ndarray, For each row in vectors_all, distance from vector_1 is computed, expected shape (num_vectors, dim). :return: numpy.ndarray, Contains cosine distance between `vector_1` and each row in `vectors_all`, shape (num_vectors,). >>> vector1 = np.array([1, 2, 3]) >>> vectors_all = [np.array([4, 5, 6]), np.array([7, 8, 9])] >>> VectorUtil.cosine_similarities(vector1, vectors_all) [0.97463185 0.95941195] """ norm = np.linalg.norm(vector_1) all_norms = np.linalg.norm(vectors_all, axis=1) dot_products = dot(vectors_all, vector_1) similarities = dot_products / (norm * all_norms) return similarities @staticmethod def n_similarity(vector_list_1, vector_list_2): """ Compute cosine similarity between two sets of vectors. :param vector_list_1: list of numpy vector :param vector_list_2: list of numpy vector :return: numpy.ndarray, Similarities between vector_list_1 and vector_list_2. >>> vector_list1 = [np.array([1, 2, 3]), np.array([4, 5, 6])] >>> vector_list2 = [np.array([7, 8, 9]), np.array([10, 11, 12])] >>> VectorUtil.n_similarity(vector_list1, vector_list2) 0.9897287473881233 """ if not (len(vector_list_1) and len(vector_list_2)): raise ZeroDivisionError('At least one of the passed list is empty.') return dot(matutils.unitvec(array(vector_list_1).mean(axis=0)), matutils.unitvec(array(vector_list_2).mean(axis=0))) @staticmethod def compute_idf_weight_dict(total_num, number_dict): index_2_key_map = {} index = 0 count_list = [] for key, count in number_dict.items(): index_2_key_map[index] = key count_list.append(count) index = index + 1 a = np.array(count_list) ## smooth, in case the divide by zero error a = np.log((total_num + 1) / (a + 1)) result = {} for index, w in enumerate(a): key = index_2_key_map[index] result[key] = w return result
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod def similarity(vector_1, vector_2): """ Compute the cosine similarity between one vector and another vector. :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :param vector_2: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :return: numpy.ndarray, Contains cosine distance between `vector_1` and `vector_2` >>> vector_1 = np.array([1, 1]) >>> vector_2 = np.array([1, 0]) >>> VectorUtil.similarity(vector_1, vector_2) 0.7071067811865475 """ @staticmethod def cosine_similarities(vector_1, vectors_all): """ Compute cosine similarities between one vector and a set of other vectors. :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,). :param vectors_all: list of numpy.ndarray, For each row in vectors_all, distance from vector_1 is computed, expected shape (num_vectors, dim). :return: numpy.ndarray, Contains cosine distance between `vector_1` and each row in `vectors_all`, shape (num_vectors,). >>> vector1 = np.array([1, 2, 3]) >>> vectors_all = [np.array([4, 5, 6]), np.array([7, 8, 9])] >>> VectorUtil.cosine_similarities(vector1, vectors_all) [0.97463185 0.95941195] """ @staticmethod def n_similarity(vector_list_1, vector_list_2): """ Compute cosine similarity between two sets of vectors. :param vector_list_1: list of numpy vector :param vector_list_2: list of numpy vector :return: numpy.ndarray, Similarities between vector_list_1 and vector_list_2. >>> vector_list1 = [np.array([1, 2, 3]), np.array([4, 5, 6])] >>> vector_list2 = [np.array([7, 8, 9]), np.array([10, 11, 12])] >>> VectorUtil.n_similarity(vector_list1, vector_list2) 0.9897287473881233 """ @staticmethod def compute_idf_weight_dict(total_num, number_dict): """ Calculate log(total_num+1/count+1) for each count in number_dict :param total_num: int :param number_dict: dict :return: dict >>> num_dict = {'key1':0.1, 'key2':0.5} >>> VectorUtil.compute_idf_weight_dict(2, num_dict) {'key1': 1.0033021088637848, 'key2': 0.6931471805599453} """
@staticmethod def compute_idf_weight_dict(total_num, number_dict): index_2_key_map = {} index = 0 count_list = [] for key, count in number_dict.items(): index_2_key_map[index] = key count_list.append(count) index = index + 1 a = np.array(count_list) ## smooth, in case the divide by zero error a = np.log((total_num + 1) / (a + 1)) result = {} for index, w in enumerate(a): key = index_2_key_map[index] result[key] = w return result
Calculate log(total_num+1/count+1) for each count in number_dict
ClassEval_94_sum
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): self.inventory = {} self.balance = 0 def insert_coin(self, amount): """ Inserts coins into the vending machine. :param amount: The amount of coins to be inserted, float. :return: The balance of the vending machine after the coins are inserted, float. >>> vendingMachine = VendingMachine() >>> vendingMachine.insert_coin(1.25) 1.25 """ self.balance += amount return self.balance def purchase_item(self, item_name): """ Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock. :param item_name: The name of the product to be purchased, str. :return: If successful, returns the balance of the vending machine after the product is purchased, float,otherwise,returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.balance = 1.25 >>> vendingMachine.purchase_item('Coke') 0.0 >>> vendingMachine.purchase_item('Pizza') False """ if item_name in self.inventory: item = self.inventory[item_name] if item['quantity'] > 0 and self.balance >= item['price']: self.balance -= item['price'] item['quantity'] -= 1 return self.balance else: return False else: return False def restock_item(self, item_name, quantity): """ Replenishes the inventory of a product already in the vending machine. :param item_name: The name of the product to be replenished, str. :param quantity: The quantity of the product to be replenished, int. :return: If the product is already in the vending machine, returns True, otherwise, returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.restock_item('Coke', 10) True >>> vendingMachine.restock_item('Pizza', 10) False """ if item_name in self.inventory: self.inventory[item_name]['quantity'] += quantity return True else: return False def display_items(self): """ Displays the products in the vending machine. :return: If the vending machine is empty, returns False, otherwise, returns a list of the products in the vending machine, str. >>> vendingMachine = VendingMachine() >>> vendingMachine.display_items() False >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10} } >>> vendingMachine.display_items() 'Coke - $1.25 [10]' """ if not self.inventory: return False else: items = [] for item_name, item_info in self.inventory.items(): items.append(f"{item_name} - ${item_info['price']} [{item_info['quantity']}]") return "\n".join(items)
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): """ Initializes the vending machine's inventory and balance. """ self.inventory = {} self.balance = 0 def insert_coin(self, amount): """ Inserts coins into the vending machine. :param amount: The amount of coins to be inserted, float. :return: The balance of the vending machine after the coins are inserted, float. >>> vendingMachine = VendingMachine() >>> vendingMachine.insert_coin(1.25) 1.25 """ def purchase_item(self, item_name): """ Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock. :param item_name: The name of the product to be purchased, str. :return: If successful, returns the balance of the vending machine after the product is purchased, float,otherwise,returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.balance = 1.25 >>> vendingMachine.purchase_item('Coke') 0.0 >>> vendingMachine.purchase_item('Pizza') False """ def restock_item(self, item_name, quantity): """ Replenishes the inventory of a product already in the vending machine. :param item_name: The name of the product to be replenished, str. :param quantity: The quantity of the product to be replenished, int. :return: If the product is already in the vending machine, returns True, otherwise, returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.restock_item('Coke', 10) True >>> vendingMachine.restock_item('Pizza', 10) False """ def display_items(self): """ Displays the products in the vending machine. :return: If the vending machine is empty, returns False, otherwise, returns a list of the products in the vending machine, str. >>> vendingMachine = VendingMachine() >>> vendingMachine.display_items() False >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10} } >>> vendingMachine.display_items() 'Coke - $1.25 [10]' """
def add_item(self, item_name, price, quantity): if not self.restock_item(item_name, quantity): self.inventory[item_name] = {'price': price, 'quantity': quantity}
Adds a product to the vending machine's inventory.
ClassEval_94_sum
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): self.inventory = {} self.balance = 0 def add_item(self, item_name, price, quantity): """ Adds a product to the vending machine's inventory. :param item_name: The name of the product to be added, str. :param price: The price of the product to be added, float. :param quantity: The quantity of the product to be added, int. :return: None >>> vendingMachine = VendingMachine() >>> vendingMachine.add_item('Coke', 1.25, 10) >>> vendingMachine.inventory {'Coke': {'price': 1.25, 'quantity': 10}} """ if not self.restock_item(item_name, quantity): self.inventory[item_name] = {'price': price, 'quantity': quantity} def purchase_item(self, item_name): """ Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock. :param item_name: The name of the product to be purchased, str. :return: If successful, returns the balance of the vending machine after the product is purchased, float,otherwise,returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.balance = 1.25 >>> vendingMachine.purchase_item('Coke') 0.0 >>> vendingMachine.purchase_item('Pizza') False """ if item_name in self.inventory: item = self.inventory[item_name] if item['quantity'] > 0 and self.balance >= item['price']: self.balance -= item['price'] item['quantity'] -= 1 return self.balance else: return False else: return False def restock_item(self, item_name, quantity): """ Replenishes the inventory of a product already in the vending machine. :param item_name: The name of the product to be replenished, str. :param quantity: The quantity of the product to be replenished, int. :return: If the product is already in the vending machine, returns True, otherwise, returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.restock_item('Coke', 10) True >>> vendingMachine.restock_item('Pizza', 10) False """ if item_name in self.inventory: self.inventory[item_name]['quantity'] += quantity return True else: return False def display_items(self): """ Displays the products in the vending machine. :return: If the vending machine is empty, returns False, otherwise, returns a list of the products in the vending machine, str. >>> vendingMachine = VendingMachine() >>> vendingMachine.display_items() False >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10} } >>> vendingMachine.display_items() 'Coke - $1.25 [10]' """ if not self.inventory: return False else: items = [] for item_name, item_info in self.inventory.items(): items.append(f"{item_name} - ${item_info['price']} [{item_info['quantity']}]") return "\n".join(items)
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): """ Initializes the vending machine's inventory and balance. """ self.inventory = {} self.balance = 0 def add_item(self, item_name, price, quantity): """ Adds a product to the vending machine's inventory. :param item_name: The name of the product to be added, str. :param price: The price of the product to be added, float. :param quantity: The quantity of the product to be added, int. :return: None >>> vendingMachine = VendingMachine() >>> vendingMachine.add_item('Coke', 1.25, 10) >>> vendingMachine.inventory {'Coke': {'price': 1.25, 'quantity': 10}} """ def purchase_item(self, item_name): """ Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock. :param item_name: The name of the product to be purchased, str. :return: If successful, returns the balance of the vending machine after the product is purchased, float,otherwise,returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.balance = 1.25 >>> vendingMachine.purchase_item('Coke') 0.0 >>> vendingMachine.purchase_item('Pizza') False """ def restock_item(self, item_name, quantity): """ Replenishes the inventory of a product already in the vending machine. :param item_name: The name of the product to be replenished, str. :param quantity: The quantity of the product to be replenished, int. :return: If the product is already in the vending machine, returns True, otherwise, returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.restock_item('Coke', 10) True >>> vendingMachine.restock_item('Pizza', 10) False """ def display_items(self): """ Displays the products in the vending machine. :return: If the vending machine is empty, returns False, otherwise, returns a list of the products in the vending machine, str. >>> vendingMachine = VendingMachine() >>> vendingMachine.display_items() False >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10} } >>> vendingMachine.display_items() 'Coke - $1.25 [10]' """
def insert_coin(self, amount): self.balance += amount return self.balance
Inserts coins into the vending machine.
ClassEval_94_sum
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): self.inventory = {} self.balance = 0 def add_item(self, item_name, price, quantity): """ Adds a product to the vending machine's inventory. :param item_name: The name of the product to be added, str. :param price: The price of the product to be added, float. :param quantity: The quantity of the product to be added, int. :return: None >>> vendingMachine = VendingMachine() >>> vendingMachine.add_item('Coke', 1.25, 10) >>> vendingMachine.inventory {'Coke': {'price': 1.25, 'quantity': 10}} """ if not self.restock_item(item_name, quantity): self.inventory[item_name] = {'price': price, 'quantity': quantity} def insert_coin(self, amount): """ Inserts coins into the vending machine. :param amount: The amount of coins to be inserted, float. :return: The balance of the vending machine after the coins are inserted, float. >>> vendingMachine = VendingMachine() >>> vendingMachine.insert_coin(1.25) 1.25 """ self.balance += amount return self.balance def restock_item(self, item_name, quantity): """ Replenishes the inventory of a product already in the vending machine. :param item_name: The name of the product to be replenished, str. :param quantity: The quantity of the product to be replenished, int. :return: If the product is already in the vending machine, returns True, otherwise, returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.restock_item('Coke', 10) True >>> vendingMachine.restock_item('Pizza', 10) False """ if item_name in self.inventory: self.inventory[item_name]['quantity'] += quantity return True else: return False def display_items(self): """ Displays the products in the vending machine. :return: If the vending machine is empty, returns False, otherwise, returns a list of the products in the vending machine, str. >>> vendingMachine = VendingMachine() >>> vendingMachine.display_items() False >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10} } >>> vendingMachine.display_items() 'Coke - $1.25 [10]' """ if not self.inventory: return False else: items = [] for item_name, item_info in self.inventory.items(): items.append(f"{item_name} - ${item_info['price']} [{item_info['quantity']}]") return "\n".join(items)
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): """ Initializes the vending machine's inventory and balance. """ self.inventory = {} self.balance = 0 def add_item(self, item_name, price, quantity): """ Adds a product to the vending machine's inventory. :param item_name: The name of the product to be added, str. :param price: The price of the product to be added, float. :param quantity: The quantity of the product to be added, int. :return: None >>> vendingMachine = VendingMachine() >>> vendingMachine.add_item('Coke', 1.25, 10) >>> vendingMachine.inventory {'Coke': {'price': 1.25, 'quantity': 10}} """ def insert_coin(self, amount): """ Inserts coins into the vending machine. :param amount: The amount of coins to be inserted, float. :return: The balance of the vending machine after the coins are inserted, float. >>> vendingMachine = VendingMachine() >>> vendingMachine.insert_coin(1.25) 1.25 """ def restock_item(self, item_name, quantity): """ Replenishes the inventory of a product already in the vending machine. :param item_name: The name of the product to be replenished, str. :param quantity: The quantity of the product to be replenished, int. :return: If the product is already in the vending machine, returns True, otherwise, returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.restock_item('Coke', 10) True >>> vendingMachine.restock_item('Pizza', 10) False """ def display_items(self): """ Displays the products in the vending machine. :return: If the vending machine is empty, returns False, otherwise, returns a list of the products in the vending machine, str. >>> vendingMachine = VendingMachine() >>> vendingMachine.display_items() False >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10} } >>> vendingMachine.display_items() 'Coke - $1.25 [10]' """
def purchase_item(self, item_name): if item_name in self.inventory: item = self.inventory[item_name] if item['quantity'] > 0 and self.balance >= item['price']: self.balance -= item['price'] item['quantity'] -= 1 return self.balance else: return False else: return False
Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock.
ClassEval_94_sum
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): self.inventory = {} self.balance = 0 def add_item(self, item_name, price, quantity): """ Adds a product to the vending machine's inventory. :param item_name: The name of the product to be added, str. :param price: The price of the product to be added, float. :param quantity: The quantity of the product to be added, int. :return: None >>> vendingMachine = VendingMachine() >>> vendingMachine.add_item('Coke', 1.25, 10) >>> vendingMachine.inventory {'Coke': {'price': 1.25, 'quantity': 10}} """ if not self.restock_item(item_name, quantity): self.inventory[item_name] = {'price': price, 'quantity': quantity} def insert_coin(self, amount): """ Inserts coins into the vending machine. :param amount: The amount of coins to be inserted, float. :return: The balance of the vending machine after the coins are inserted, float. >>> vendingMachine = VendingMachine() >>> vendingMachine.insert_coin(1.25) 1.25 """ self.balance += amount return self.balance def purchase_item(self, item_name): """ Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock. :param item_name: The name of the product to be purchased, str. :return: If successful, returns the balance of the vending machine after the product is purchased, float,otherwise,returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.balance = 1.25 >>> vendingMachine.purchase_item('Coke') 0.0 >>> vendingMachine.purchase_item('Pizza') False """ if item_name in self.inventory: item = self.inventory[item_name] if item['quantity'] > 0 and self.balance >= item['price']: self.balance -= item['price'] item['quantity'] -= 1 return self.balance else: return False else: return False def display_items(self): """ Displays the products in the vending machine. :return: If the vending machine is empty, returns False, otherwise, returns a list of the products in the vending machine, str. >>> vendingMachine = VendingMachine() >>> vendingMachine.display_items() False >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10} } >>> vendingMachine.display_items() 'Coke - $1.25 [10]' """ if not self.inventory: return False else: items = [] for item_name, item_info in self.inventory.items(): items.append(f"{item_name} - ${item_info['price']} [{item_info['quantity']}]") return "\n".join(items)
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): """ Initializes the vending machine's inventory and balance. """ self.inventory = {} self.balance = 0 def add_item(self, item_name, price, quantity): """ Adds a product to the vending machine's inventory. :param item_name: The name of the product to be added, str. :param price: The price of the product to be added, float. :param quantity: The quantity of the product to be added, int. :return: None >>> vendingMachine = VendingMachine() >>> vendingMachine.add_item('Coke', 1.25, 10) >>> vendingMachine.inventory {'Coke': {'price': 1.25, 'quantity': 10}} """ def insert_coin(self, amount): """ Inserts coins into the vending machine. :param amount: The amount of coins to be inserted, float. :return: The balance of the vending machine after the coins are inserted, float. >>> vendingMachine = VendingMachine() >>> vendingMachine.insert_coin(1.25) 1.25 """ def purchase_item(self, item_name): """ Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock. :param item_name: The name of the product to be purchased, str. :return: If successful, returns the balance of the vending machine after the product is purchased, float,otherwise,returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.balance = 1.25 >>> vendingMachine.purchase_item('Coke') 0.0 >>> vendingMachine.purchase_item('Pizza') False """ def display_items(self): """ Displays the products in the vending machine. :return: If the vending machine is empty, returns False, otherwise, returns a list of the products in the vending machine, str. >>> vendingMachine = VendingMachine() >>> vendingMachine.display_items() False >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10} } >>> vendingMachine.display_items() 'Coke - $1.25 [10]' """
def restock_item(self, item_name, quantity): if item_name in self.inventory: self.inventory[item_name]['quantity'] += quantity return True else: return False
Replenishes the inventory of a product already in the vending machine.
ClassEval_94_sum
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): self.inventory = {} self.balance = 0 def add_item(self, item_name, price, quantity): """ Adds a product to the vending machine's inventory. :param item_name: The name of the product to be added, str. :param price: The price of the product to be added, float. :param quantity: The quantity of the product to be added, int. :return: None >>> vendingMachine = VendingMachine() >>> vendingMachine.add_item('Coke', 1.25, 10) >>> vendingMachine.inventory {'Coke': {'price': 1.25, 'quantity': 10}} """ if not self.restock_item(item_name, quantity): self.inventory[item_name] = {'price': price, 'quantity': quantity} def insert_coin(self, amount): """ Inserts coins into the vending machine. :param amount: The amount of coins to be inserted, float. :return: The balance of the vending machine after the coins are inserted, float. >>> vendingMachine = VendingMachine() >>> vendingMachine.insert_coin(1.25) 1.25 """ self.balance += amount return self.balance def purchase_item(self, item_name): """ Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock. :param item_name: The name of the product to be purchased, str. :return: If successful, returns the balance of the vending machine after the product is purchased, float,otherwise,returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.balance = 1.25 >>> vendingMachine.purchase_item('Coke') 0.0 >>> vendingMachine.purchase_item('Pizza') False """ if item_name in self.inventory: item = self.inventory[item_name] if item['quantity'] > 0 and self.balance >= item['price']: self.balance -= item['price'] item['quantity'] -= 1 return self.balance else: return False else: return False def restock_item(self, item_name, quantity): """ Replenishes the inventory of a product already in the vending machine. :param item_name: The name of the product to be replenished, str. :param quantity: The quantity of the product to be replenished, int. :return: If the product is already in the vending machine, returns True, otherwise, returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.restock_item('Coke', 10) True >>> vendingMachine.restock_item('Pizza', 10) False """ if item_name in self.inventory: self.inventory[item_name]['quantity'] += quantity return True else: return False def display_items(self): if not self.inventory: return False else: items = [] for item_name, item_info in self.inventory.items(): items.append(f"{item_name} - ${item_info['price']} [{item_info['quantity']}]") return "\n".join(items)
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): """ Initializes the vending machine's inventory and balance. """ self.inventory = {} self.balance = 0 def add_item(self, item_name, price, quantity): """ Adds a product to the vending machine's inventory. :param item_name: The name of the product to be added, str. :param price: The price of the product to be added, float. :param quantity: The quantity of the product to be added, int. :return: None >>> vendingMachine = VendingMachine() >>> vendingMachine.add_item('Coke', 1.25, 10) >>> vendingMachine.inventory {'Coke': {'price': 1.25, 'quantity': 10}} """ def insert_coin(self, amount): """ Inserts coins into the vending machine. :param amount: The amount of coins to be inserted, float. :return: The balance of the vending machine after the coins are inserted, float. >>> vendingMachine = VendingMachine() >>> vendingMachine.insert_coin(1.25) 1.25 """ def purchase_item(self, item_name): """ Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock. :param item_name: The name of the product to be purchased, str. :return: If successful, returns the balance of the vending machine after the product is purchased, float,otherwise,returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.balance = 1.25 >>> vendingMachine.purchase_item('Coke') 0.0 >>> vendingMachine.purchase_item('Pizza') False """ def restock_item(self, item_name, quantity): """ Replenishes the inventory of a product already in the vending machine. :param item_name: The name of the product to be replenished, str. :param quantity: The quantity of the product to be replenished, int. :return: If the product is already in the vending machine, returns True, otherwise, returns False. >>> vendingMachine = VendingMachine() >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}} >>> vendingMachine.restock_item('Coke', 10) True >>> vendingMachine.restock_item('Pizza', 10) False """ def display_items(self): """ Displays the products in the vending machine. :return: If the vending machine is empty, returns False, otherwise, returns a list of the products in the vending machine, str. >>> vendingMachine = VendingMachine() >>> vendingMachine.display_items() False >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10} } >>> vendingMachine.display_items() 'Coke - $1.25 [10]' """
def display_items(self): if not self.inventory: return False else: items = [] for item_name, item_info in self.inventory.items(): items.append(f"{item_name} - ${item_info['price']} [{item_info['quantity']}]") return "\n".join(items)
Displays the products in the vending machine.
ClassEval_95_sum
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): self.inventory = {} # Product ID: Product self.orders = {} # Order ID: Order def update_product_quantity(self, product_id, quantity): """ According to product_id, add the quantity to the corresponding product in inventory. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.update_product_quantity(1, -1) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 2}} """ if product_id in self.inventory: self.inventory[product_id]['quantity'] += quantity def get_product_quantity(self, product_id): """ Get the quantity of specific product by product_id. :param product_id, int :return: if the product_id is in inventory then return the corresponding quantity, or False otherwise. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.get_product_quantity(1) 3 >>> warehouse.get_product_quantity(2) False """ if product_id in self.inventory: return self.inventory[product_id]['quantity'] else: return False def create_order(self, order_id, product_id, quantity): """ Create a order which includes the infomation of product, like id and quantity. And put the new order into self.orders. The default value of status is 'Shipped'. :param order_id: int :param product_id: int :param quantity: the quantity of product that be selected. :return False: only if product_id is not in inventory or the quantity is not adequate >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}} >>> warehouse.create_order(1, 2, 2) False """ if self.get_product_quantity(product_id) >= quantity: self.update_product_quantity(product_id, -quantity) self.orders[order_id] = {'product_id': product_id, 'quantity': quantity, 'status': 'Shipped'} else: return False def change_order_status(self, order_id, status): """ Change the status of order if the input order_id is in self.orders. :param order_id: int :param status: str, the state that is going to change to :return False: only if the order_id is not in self.orders >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.change_order_status(1, "done") >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'done'}} """ if order_id in self.orders: self.orders[order_id]['status'] = status else: return False def track_order(self, order_id): """ Get the status of specific order. :param order_id: int :return False: only if the order_id is not in self.orders. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.track_order(1) 'Shipped' """ if order_id in self.orders: return self.orders[order_id]['status'] else: return False
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): """ Initialize two fields. self.inventory is a dict that stores the products. self.inventory = {Product ID: Product} self.orders is a dict that stores the products in a order. self.orders = {Order ID: Order} """ self.inventory = {} # Product ID: Product self.orders = {} # Order ID: Order def update_product_quantity(self, product_id, quantity): """ According to product_id, add the quantity to the corresponding product in inventory. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.update_product_quantity(1, -1) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 2}} """ def get_product_quantity(self, product_id): """ Get the quantity of specific product by product_id. :param product_id, int :return: if the product_id is in inventory then return the corresponding quantity, or False otherwise. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.get_product_quantity(1) 3 >>> warehouse.get_product_quantity(2) False """ def create_order(self, order_id, product_id, quantity): """ Create a order which includes the infomation of product, like id and quantity. And put the new order into self.orders. The default value of status is 'Shipped'. :param order_id: int :param product_id: int :param quantity: the quantity of product that be selected. :return False: only if product_id is not in inventory or the quantity is not adequate >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}} >>> warehouse.create_order(1, 2, 2) False """ def change_order_status(self, order_id, status): """ Change the status of order if the input order_id is in self.orders. :param order_id: int :param status: str, the state that is going to change to :return False: only if the order_id is not in self.orders >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.change_order_status(1, "done") >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'done'}} """ def track_order(self, order_id): """ Get the status of specific order. :param order_id: int :return False: only if the order_id is not in self.orders. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.track_order(1) 'Shipped' """
def add_product(self, product_id, name, quantity): if product_id not in self.inventory: self.inventory[product_id] = {'name': name, 'quantity': quantity} else: self.inventory[product_id]['quantity'] += quantity
Add product to inventory and plus the quantity if it has existed in inventory. Or just add new product to dict otherwise.
ClassEval_95_sum
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): self.inventory = {} # Product ID: Product self.orders = {} # Order ID: Order def add_product(self, product_id, name, quantity): """ Add product to inventory and plus the quantity if it has existed in inventory. Or just add new product to dict otherwise. :param product_id: int :param name: str, product name :param quantity: int, product quantity >>> warehouse.add_product(1, "product1", 3) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 3}} """ if product_id not in self.inventory: self.inventory[product_id] = {'name': name, 'quantity': quantity} else: self.inventory[product_id]['quantity'] += quantity def get_product_quantity(self, product_id): """ Get the quantity of specific product by product_id. :param product_id, int :return: if the product_id is in inventory then return the corresponding quantity, or False otherwise. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.get_product_quantity(1) 3 >>> warehouse.get_product_quantity(2) False """ if product_id in self.inventory: return self.inventory[product_id]['quantity'] else: return False def create_order(self, order_id, product_id, quantity): """ Create a order which includes the infomation of product, like id and quantity. And put the new order into self.orders. The default value of status is 'Shipped'. :param order_id: int :param product_id: int :param quantity: the quantity of product that be selected. :return False: only if product_id is not in inventory or the quantity is not adequate >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}} >>> warehouse.create_order(1, 2, 2) False """ if self.get_product_quantity(product_id) >= quantity: self.update_product_quantity(product_id, -quantity) self.orders[order_id] = {'product_id': product_id, 'quantity': quantity, 'status': 'Shipped'} else: return False def change_order_status(self, order_id, status): """ Change the status of order if the input order_id is in self.orders. :param order_id: int :param status: str, the state that is going to change to :return False: only if the order_id is not in self.orders >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.change_order_status(1, "done") >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'done'}} """ if order_id in self.orders: self.orders[order_id]['status'] = status else: return False def track_order(self, order_id): """ Get the status of specific order. :param order_id: int :return False: only if the order_id is not in self.orders. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.track_order(1) 'Shipped' """ if order_id in self.orders: return self.orders[order_id]['status'] else: return False
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): """ Initialize two fields. self.inventory is a dict that stores the products. self.inventory = {Product ID: Product} self.orders is a dict that stores the products in a order. self.orders = {Order ID: Order} """ self.inventory = {} # Product ID: Product self.orders = {} # Order ID: Order def add_product(self, product_id, name, quantity): """ Add product to inventory and plus the quantity if it has existed in inventory. Or just add new product to dict otherwise. :param product_id: int :param name: str, product name :param quantity: int, product quantity >>> warehouse.add_product(1, "product1", 3) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 3}} """ def get_product_quantity(self, product_id): """ Get the quantity of specific product by product_id. :param product_id, int :return: if the product_id is in inventory then return the corresponding quantity, or False otherwise. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.get_product_quantity(1) 3 >>> warehouse.get_product_quantity(2) False """ def create_order(self, order_id, product_id, quantity): """ Create a order which includes the infomation of product, like id and quantity. And put the new order into self.orders. The default value of status is 'Shipped'. :param order_id: int :param product_id: int :param quantity: the quantity of product that be selected. :return False: only if product_id is not in inventory or the quantity is not adequate >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}} >>> warehouse.create_order(1, 2, 2) False """ def change_order_status(self, order_id, status): """ Change the status of order if the input order_id is in self.orders. :param order_id: int :param status: str, the state that is going to change to :return False: only if the order_id is not in self.orders >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.change_order_status(1, "done") >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'done'}} """ def track_order(self, order_id): """ Get the status of specific order. :param order_id: int :return False: only if the order_id is not in self.orders. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.track_order(1) 'Shipped' """
def update_product_quantity(self, product_id, quantity): if product_id in self.inventory: self.inventory[product_id]['quantity'] += quantity
According to product_id, add the quantity to the corresponding product in inventory.
ClassEval_95_sum
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): self.inventory = {} # Product ID: Product self.orders = {} # Order ID: Order def add_product(self, product_id, name, quantity): """ Add product to inventory and plus the quantity if it has existed in inventory. Or just add new product to dict otherwise. :param product_id: int :param name: str, product name :param quantity: int, product quantity >>> warehouse.add_product(1, "product1", 3) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 3}} """ if product_id not in self.inventory: self.inventory[product_id] = {'name': name, 'quantity': quantity} else: self.inventory[product_id]['quantity'] += quantity def update_product_quantity(self, product_id, quantity): """ According to product_id, add the quantity to the corresponding product in inventory. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.update_product_quantity(1, -1) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 2}} """ if product_id in self.inventory: self.inventory[product_id]['quantity'] += quantity def create_order(self, order_id, product_id, quantity): """ Create a order which includes the infomation of product, like id and quantity. And put the new order into self.orders. The default value of status is 'Shipped'. :param order_id: int :param product_id: int :param quantity: the quantity of product that be selected. :return False: only if product_id is not in inventory or the quantity is not adequate >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}} >>> warehouse.create_order(1, 2, 2) False """ if self.get_product_quantity(product_id) >= quantity: self.update_product_quantity(product_id, -quantity) self.orders[order_id] = {'product_id': product_id, 'quantity': quantity, 'status': 'Shipped'} else: return False def change_order_status(self, order_id, status): """ Change the status of order if the input order_id is in self.orders. :param order_id: int :param status: str, the state that is going to change to :return False: only if the order_id is not in self.orders >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.change_order_status(1, "done") >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'done'}} """ if order_id in self.orders: self.orders[order_id]['status'] = status else: return False def track_order(self, order_id): """ Get the status of specific order. :param order_id: int :return False: only if the order_id is not in self.orders. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.track_order(1) 'Shipped' """ if order_id in self.orders: return self.orders[order_id]['status'] else: return False
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): """ Initialize two fields. self.inventory is a dict that stores the products. self.inventory = {Product ID: Product} self.orders is a dict that stores the products in a order. self.orders = {Order ID: Order} """ self.inventory = {} # Product ID: Product self.orders = {} # Order ID: Order def add_product(self, product_id, name, quantity): """ Add product to inventory and plus the quantity if it has existed in inventory. Or just add new product to dict otherwise. :param product_id: int :param name: str, product name :param quantity: int, product quantity >>> warehouse.add_product(1, "product1", 3) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 3}} """ def update_product_quantity(self, product_id, quantity): """ According to product_id, add the quantity to the corresponding product in inventory. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.update_product_quantity(1, -1) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 2}} """ def create_order(self, order_id, product_id, quantity): """ Create a order which includes the infomation of product, like id and quantity. And put the new order into self.orders. The default value of status is 'Shipped'. :param order_id: int :param product_id: int :param quantity: the quantity of product that be selected. :return False: only if product_id is not in inventory or the quantity is not adequate >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}} >>> warehouse.create_order(1, 2, 2) False """ def change_order_status(self, order_id, status): """ Change the status of order if the input order_id is in self.orders. :param order_id: int :param status: str, the state that is going to change to :return False: only if the order_id is not in self.orders >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.change_order_status(1, "done") >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'done'}} """ def track_order(self, order_id): """ Get the status of specific order. :param order_id: int :return False: only if the order_id is not in self.orders. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.track_order(1) 'Shipped' """
def get_product_quantity(self, product_id): if product_id in self.inventory: return self.inventory[product_id]['quantity'] else: return False
Get the quantity of specific product by product_id.
ClassEval_95_sum
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): self.inventory = {} # Product ID: Product self.orders = {} # Order ID: Order def add_product(self, product_id, name, quantity): """ Add product to inventory and plus the quantity if it has existed in inventory. Or just add new product to dict otherwise. :param product_id: int :param name: str, product name :param quantity: int, product quantity >>> warehouse.add_product(1, "product1", 3) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 3}} """ if product_id not in self.inventory: self.inventory[product_id] = {'name': name, 'quantity': quantity} else: self.inventory[product_id]['quantity'] += quantity def update_product_quantity(self, product_id, quantity): """ According to product_id, add the quantity to the corresponding product in inventory. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.update_product_quantity(1, -1) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 2}} """ if product_id in self.inventory: self.inventory[product_id]['quantity'] += quantity def get_product_quantity(self, product_id): """ Get the quantity of specific product by product_id. :param product_id, int :return: if the product_id is in inventory then return the corresponding quantity, or False otherwise. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.get_product_quantity(1) 3 >>> warehouse.get_product_quantity(2) False """ if product_id in self.inventory: return self.inventory[product_id]['quantity'] else: return False def change_order_status(self, order_id, status): """ Change the status of order if the input order_id is in self.orders. :param order_id: int :param status: str, the state that is going to change to :return False: only if the order_id is not in self.orders >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.change_order_status(1, "done") >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'done'}} """ if order_id in self.orders: self.orders[order_id]['status'] = status else: return False def track_order(self, order_id): """ Get the status of specific order. :param order_id: int :return False: only if the order_id is not in self.orders. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.track_order(1) 'Shipped' """ if order_id in self.orders: return self.orders[order_id]['status'] else: return False
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): """ Initialize two fields. self.inventory is a dict that stores the products. self.inventory = {Product ID: Product} self.orders is a dict that stores the products in a order. self.orders = {Order ID: Order} """ self.inventory = {} # Product ID: Product self.orders = {} # Order ID: Order def add_product(self, product_id, name, quantity): """ Add product to inventory and plus the quantity if it has existed in inventory. Or just add new product to dict otherwise. :param product_id: int :param name: str, product name :param quantity: int, product quantity >>> warehouse.add_product(1, "product1", 3) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 3}} """ def update_product_quantity(self, product_id, quantity): """ According to product_id, add the quantity to the corresponding product in inventory. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.update_product_quantity(1, -1) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 2}} """ def get_product_quantity(self, product_id): """ Get the quantity of specific product by product_id. :param product_id, int :return: if the product_id is in inventory then return the corresponding quantity, or False otherwise. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.get_product_quantity(1) 3 >>> warehouse.get_product_quantity(2) False """ def change_order_status(self, order_id, status): """ Change the status of order if the input order_id is in self.orders. :param order_id: int :param status: str, the state that is going to change to :return False: only if the order_id is not in self.orders >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.change_order_status(1, "done") >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'done'}} """ def track_order(self, order_id): """ Get the status of specific order. :param order_id: int :return False: only if the order_id is not in self.orders. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.track_order(1) 'Shipped' """
def create_order(self, order_id, product_id, quantity): if self.get_product_quantity(product_id) >= quantity: self.update_product_quantity(product_id, -quantity) self.orders[order_id] = {'product_id': product_id, 'quantity': quantity, 'status': 'Shipped'} else: return False
Create a order which includes the infomation of product, like id and quantity. And put the new order into self.orders. The default value of status is 'Shipped'.
ClassEval_95_sum
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): self.inventory = {} # Product ID: Product self.orders = {} # Order ID: Order def add_product(self, product_id, name, quantity): """ Add product to inventory and plus the quantity if it has existed in inventory. Or just add new product to dict otherwise. :param product_id: int :param name: str, product name :param quantity: int, product quantity >>> warehouse.add_product(1, "product1", 3) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 3}} """ if product_id not in self.inventory: self.inventory[product_id] = {'name': name, 'quantity': quantity} else: self.inventory[product_id]['quantity'] += quantity def update_product_quantity(self, product_id, quantity): """ According to product_id, add the quantity to the corresponding product in inventory. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.update_product_quantity(1, -1) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 2}} """ if product_id in self.inventory: self.inventory[product_id]['quantity'] += quantity def get_product_quantity(self, product_id): """ Get the quantity of specific product by product_id. :param product_id, int :return: if the product_id is in inventory then return the corresponding quantity, or False otherwise. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.get_product_quantity(1) 3 >>> warehouse.get_product_quantity(2) False """ if product_id in self.inventory: return self.inventory[product_id]['quantity'] else: return False def create_order(self, order_id, product_id, quantity): """ Create a order which includes the infomation of product, like id and quantity. And put the new order into self.orders. The default value of status is 'Shipped'. :param order_id: int :param product_id: int :param quantity: the quantity of product that be selected. :return False: only if product_id is not in inventory or the quantity is not adequate >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}} >>> warehouse.create_order(1, 2, 2) False """ if self.get_product_quantity(product_id) >= quantity: self.update_product_quantity(product_id, -quantity) self.orders[order_id] = {'product_id': product_id, 'quantity': quantity, 'status': 'Shipped'} else: return False def track_order(self, order_id): """ Get the status of specific order. :param order_id: int :return False: only if the order_id is not in self.orders. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.track_order(1) 'Shipped' """ if order_id in self.orders: return self.orders[order_id]['status'] else: return False
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): """ Initialize two fields. self.inventory is a dict that stores the products. self.inventory = {Product ID: Product} self.orders is a dict that stores the products in a order. self.orders = {Order ID: Order} """ self.inventory = {} # Product ID: Product self.orders = {} # Order ID: Order def add_product(self, product_id, name, quantity): """ Add product to inventory and plus the quantity if it has existed in inventory. Or just add new product to dict otherwise. :param product_id: int :param name: str, product name :param quantity: int, product quantity >>> warehouse.add_product(1, "product1", 3) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 3}} """ def update_product_quantity(self, product_id, quantity): """ According to product_id, add the quantity to the corresponding product in inventory. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.update_product_quantity(1, -1) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 2}} """ def get_product_quantity(self, product_id): """ Get the quantity of specific product by product_id. :param product_id, int :return: if the product_id is in inventory then return the corresponding quantity, or False otherwise. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.get_product_quantity(1) 3 >>> warehouse.get_product_quantity(2) False """ def create_order(self, order_id, product_id, quantity): """ Create a order which includes the infomation of product, like id and quantity. And put the new order into self.orders. The default value of status is 'Shipped'. :param order_id: int :param product_id: int :param quantity: the quantity of product that be selected. :return False: only if product_id is not in inventory or the quantity is not adequate >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}} >>> warehouse.create_order(1, 2, 2) False """ def track_order(self, order_id): """ Get the status of specific order. :param order_id: int :return False: only if the order_id is not in self.orders. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.track_order(1) 'Shipped' """
def change_order_status(self, order_id, status): if order_id in self.orders: self.orders[order_id]['status'] = status else: return False
Change the status of order if the input order_id is in self.orders.
ClassEval_95_sum
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): self.inventory = {} # Product ID: Product self.orders = {} # Order ID: Order def add_product(self, product_id, name, quantity): """ Add product to inventory and plus the quantity if it has existed in inventory. Or just add new product to dict otherwise. :param product_id: int :param name: str, product name :param quantity: int, product quantity >>> warehouse.add_product(1, "product1", 3) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 3}} """ if product_id not in self.inventory: self.inventory[product_id] = {'name': name, 'quantity': quantity} else: self.inventory[product_id]['quantity'] += quantity def update_product_quantity(self, product_id, quantity): """ According to product_id, add the quantity to the corresponding product in inventory. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.update_product_quantity(1, -1) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 2}} """ if product_id in self.inventory: self.inventory[product_id]['quantity'] += quantity def get_product_quantity(self, product_id): """ Get the quantity of specific product by product_id. :param product_id, int :return: if the product_id is in inventory then return the corresponding quantity, or False otherwise. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.get_product_quantity(1) 3 >>> warehouse.get_product_quantity(2) False """ if product_id in self.inventory: return self.inventory[product_id]['quantity'] else: return False def create_order(self, order_id, product_id, quantity): """ Create a order which includes the infomation of product, like id and quantity. And put the new order into self.orders. The default value of status is 'Shipped'. :param order_id: int :param product_id: int :param quantity: the quantity of product that be selected. :return False: only if product_id is not in inventory or the quantity is not adequate >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}} >>> warehouse.create_order(1, 2, 2) False """ if self.get_product_quantity(product_id) >= quantity: self.update_product_quantity(product_id, -quantity) self.orders[order_id] = {'product_id': product_id, 'quantity': quantity, 'status': 'Shipped'} else: return False def change_order_status(self, order_id, status): """ Change the status of order if the input order_id is in self.orders. :param order_id: int :param status: str, the state that is going to change to :return False: only if the order_id is not in self.orders >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.change_order_status(1, "done") >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'done'}} """ if order_id in self.orders: self.orders[order_id]['status'] = status else: return False def track_order(self, order_id): if order_id in self.orders: return self.orders[order_id]['status'] else: return False
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): """ Initialize two fields. self.inventory is a dict that stores the products. self.inventory = {Product ID: Product} self.orders is a dict that stores the products in a order. self.orders = {Order ID: Order} """ self.inventory = {} # Product ID: Product self.orders = {} # Order ID: Order def add_product(self, product_id, name, quantity): """ Add product to inventory and plus the quantity if it has existed in inventory. Or just add new product to dict otherwise. :param product_id: int :param name: str, product name :param quantity: int, product quantity >>> warehouse.add_product(1, "product1", 3) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 3}} """ def update_product_quantity(self, product_id, quantity): """ According to product_id, add the quantity to the corresponding product in inventory. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.update_product_quantity(1, -1) >>> warehouse.inventory {1: {'name': 'product1', 'quantity': 2}} """ def get_product_quantity(self, product_id): """ Get the quantity of specific product by product_id. :param product_id, int :return: if the product_id is in inventory then return the corresponding quantity, or False otherwise. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.get_product_quantity(1) 3 >>> warehouse.get_product_quantity(2) False """ def create_order(self, order_id, product_id, quantity): """ Create a order which includes the infomation of product, like id and quantity. And put the new order into self.orders. The default value of status is 'Shipped'. :param order_id: int :param product_id: int :param quantity: the quantity of product that be selected. :return False: only if product_id is not in inventory or the quantity is not adequate >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}} >>> warehouse.create_order(1, 2, 2) False """ def change_order_status(self, order_id, status): """ Change the status of order if the input order_id is in self.orders. :param order_id: int :param status: str, the state that is going to change to :return False: only if the order_id is not in self.orders >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.change_order_status(1, "done") >>> warehouse.orders {1: {'product_id': 1, 'quantity': 2, 'status': 'done'}} """ def track_order(self, order_id): """ Get the status of specific order. :param order_id: int :return False: only if the order_id is not in self.orders. >>> warehouse.add_product(1, "product1", 3) >>> warehouse.create_order(1, 1, 2) >>> warehouse.track_order(1) 'Shipped' """
def track_order(self, order_id): if order_id in self.orders: return self.orders[order_id]['status'] else: return False
Get the status of specific order.
ClassEval_96_sum
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: self.temperature = None self.weather = None self.city = city self.weather_list = {} def query(self, weather_list, tmp_units = 'celsius'): self.weather_list = weather_list if self.city not in weather_list: return False else: self.temperature = self.weather_list[self.city]['temperature'] self.weather = self.weather_list[self.city]['weather'] if self.weather_list[self.city]['temperature units'] != tmp_units: if tmp_units == 'celsius': return self.fahrenheit_to_celsius(), self.weather elif tmp_units == 'fahrenheit': return self.celsius_to_fahrenheit(), self.weather else: return self.temperature, self.weather def set_city(self, city): """ Set the city of the weather system. :param city: the city to set, str. :return: None >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.set_city('Beijing') >>> weatherSystem.city 'Beijing' """ self.city = city def celsius_to_fahrenheit(self): """ Convert the temperature from Celsius to Fahrenheit. :return: the temperature in Fahrenheit, float. >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.temperature = 27 >>> weatherSystem.celsius_to_fahrenheit() 80.6 """ return (self.temperature * 9/5) + 32 def fahrenheit_to_celsius(self): """ Convert the temperature from Fahrenheit to Celsius. :return: the temperature in Celsius, float. >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.temperature = 80.6 >>> weatherSystem.fahrenheit_to_celsius() 26.999999999999996 """ return (self.temperature - 32) * 5/9
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: """ Initialize the weather system with a city name. """ self.temperature = None self.weather = None self.city = city self.weather_list = {} def set_city(self, city): """ Set the city of the weather system. :param city: the city to set, str. :return: None >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.set_city('Beijing') >>> weatherSystem.city 'Beijing' """ def celsius_to_fahrenheit(self): """ Convert the temperature from Celsius to Fahrenheit. :return: the temperature in Fahrenheit, float. >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.temperature = 27 >>> weatherSystem.celsius_to_fahrenheit() 80.6 """ def fahrenheit_to_celsius(self): """ Convert the temperature from Fahrenheit to Celsius. :return: the temperature in Celsius, float. >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.temperature = 80.6 >>> weatherSystem.fahrenheit_to_celsius() 26.999999999999996 """
def query(self, weather_list, tmp_units = 'celsius'): self.weather_list = weather_list if self.city not in weather_list: return False else: self.temperature = self.weather_list[self.city]['temperature'] self.weather = self.weather_list[self.city]['weather'] if self.weather_list[self.city]['temperature units'] != tmp_units: if tmp_units == 'celsius': return self.fahrenheit_to_celsius(), self.weather elif tmp_units == 'fahrenheit': return self.celsius_to_fahrenheit(), self.weather else: return self.temperature, self.weather
Query the weather system for the weather and temperature of the city,and convert the temperature units based on the input parameter.
ClassEval_96_sum
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: self.temperature = None self.weather = None self.city = city self.weather_list = {} def query(self, weather_list, tmp_units = 'celsius'): """ Query the weather system for the weather and temperature of the city,and convert the temperature units based on the input parameter. :param weather_list: a dictionary of weather information for different cities,dict. :param tmp_units: the temperature units to convert to, str. :return: the temperature and weather of the city, tuple. >>> weatherSystem = WeatherSystem('New York') >>> weather_list = {'New York': {'weather': 'sunny','temperature': 27,'temperature units': 'celsius'},'Beijing': {'weather': 'cloudy','temperature': 23,'temperature units': 'celsius'}} >>> weatherSystem.query(weather_list) (27, 'sunny') """ self.weather_list = weather_list if self.city not in weather_list: return False else: self.temperature = self.weather_list[self.city]['temperature'] self.weather = self.weather_list[self.city]['weather'] if self.weather_list[self.city]['temperature units'] != tmp_units: if tmp_units == 'celsius': return self.fahrenheit_to_celsius(), self.weather elif tmp_units == 'fahrenheit': return self.celsius_to_fahrenheit(), self.weather else: return self.temperature, self.weather def celsius_to_fahrenheit(self): """ Convert the temperature from Celsius to Fahrenheit. :return: the temperature in Fahrenheit, float. >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.temperature = 27 >>> weatherSystem.celsius_to_fahrenheit() 80.6 """ return (self.temperature * 9/5) + 32 def fahrenheit_to_celsius(self): """ Convert the temperature from Fahrenheit to Celsius. :return: the temperature in Celsius, float. >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.temperature = 80.6 >>> weatherSystem.fahrenheit_to_celsius() 26.999999999999996 """ return (self.temperature - 32) * 5/9
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: """ Initialize the weather system with a city name. """ self.temperature = None self.weather = None self.city = city self.weather_list = {} def query(self, weather_list, tmp_units = 'celsius'): """ Query the weather system for the weather and temperature of the city,and convert the temperature units based on the input parameter. :param weather_list: a dictionary of weather information for different cities,dict. :param tmp_units: the temperature units to convert to, str. :return: the temperature and weather of the city, tuple. >>> weatherSystem = WeatherSystem('New York') >>> weather_list = {'New York': {'weather': 'sunny','temperature': 27,'temperature units': 'celsius'},'Beijing': {'weather': 'cloudy','temperature': 23,'temperature units': 'celsius'}} >>> weatherSystem.query(weather_list) (27, 'sunny') """ def celsius_to_fahrenheit(self): """ Convert the temperature from Celsius to Fahrenheit. :return: the temperature in Fahrenheit, float. >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.temperature = 27 >>> weatherSystem.celsius_to_fahrenheit() 80.6 """ def fahrenheit_to_celsius(self): """ Convert the temperature from Fahrenheit to Celsius. :return: the temperature in Celsius, float. >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.temperature = 80.6 >>> weatherSystem.fahrenheit_to_celsius() 26.999999999999996 """
def set_city(self, city): self.city = city
Set the city of the weather system.
ClassEval_96_sum
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: self.temperature = None self.weather = None self.city = city self.weather_list = {} def query(self, weather_list, tmp_units = 'celsius'): """ Query the weather system for the weather and temperature of the city,and convert the temperature units based on the input parameter. :param weather_list: a dictionary of weather information for different cities,dict. :param tmp_units: the temperature units to convert to, str. :return: the temperature and weather of the city, tuple. >>> weatherSystem = WeatherSystem('New York') >>> weather_list = {'New York': {'weather': 'sunny','temperature': 27,'temperature units': 'celsius'},'Beijing': {'weather': 'cloudy','temperature': 23,'temperature units': 'celsius'}} >>> weatherSystem.query(weather_list) (27, 'sunny') """ self.weather_list = weather_list if self.city not in weather_list: return False else: self.temperature = self.weather_list[self.city]['temperature'] self.weather = self.weather_list[self.city]['weather'] if self.weather_list[self.city]['temperature units'] != tmp_units: if tmp_units == 'celsius': return self.fahrenheit_to_celsius(), self.weather elif tmp_units == 'fahrenheit': return self.celsius_to_fahrenheit(), self.weather else: return self.temperature, self.weather def set_city(self, city): """ Set the city of the weather system. :param city: the city to set, str. :return: None >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.set_city('Beijing') >>> weatherSystem.city 'Beijing' """ self.city = city def fahrenheit_to_celsius(self): """ Convert the temperature from Fahrenheit to Celsius. :return: the temperature in Celsius, float. >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.temperature = 80.6 >>> weatherSystem.fahrenheit_to_celsius() 26.999999999999996 """ return (self.temperature - 32) * 5/9
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: """ Initialize the weather system with a city name. """ self.temperature = None self.weather = None self.city = city self.weather_list = {} def query(self, weather_list, tmp_units = 'celsius'): """ Query the weather system for the weather and temperature of the city,and convert the temperature units based on the input parameter. :param weather_list: a dictionary of weather information for different cities,dict. :param tmp_units: the temperature units to convert to, str. :return: the temperature and weather of the city, tuple. >>> weatherSystem = WeatherSystem('New York') >>> weather_list = {'New York': {'weather': 'sunny','temperature': 27,'temperature units': 'celsius'},'Beijing': {'weather': 'cloudy','temperature': 23,'temperature units': 'celsius'}} >>> weatherSystem.query(weather_list) (27, 'sunny') """ def set_city(self, city): """ Set the city of the weather system. :param city: the city to set, str. :return: None >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.set_city('Beijing') >>> weatherSystem.city 'Beijing' """ def fahrenheit_to_celsius(self): """ Convert the temperature from Fahrenheit to Celsius. :return: the temperature in Celsius, float. >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.temperature = 80.6 >>> weatherSystem.fahrenheit_to_celsius() 26.999999999999996 """
def celsius_to_fahrenheit(self): return (self.temperature * 9/5) + 32
Convert the temperature from Celsius to Fahrenheit.
ClassEval_96_sum
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: self.temperature = None self.weather = None self.city = city self.weather_list = {} def query(self, weather_list, tmp_units = 'celsius'): """ Query the weather system for the weather and temperature of the city,and convert the temperature units based on the input parameter. :param weather_list: a dictionary of weather information for different cities,dict. :param tmp_units: the temperature units to convert to, str. :return: the temperature and weather of the city, tuple. >>> weatherSystem = WeatherSystem('New York') >>> weather_list = {'New York': {'weather': 'sunny','temperature': 27,'temperature units': 'celsius'},'Beijing': {'weather': 'cloudy','temperature': 23,'temperature units': 'celsius'}} >>> weatherSystem.query(weather_list) (27, 'sunny') """ self.weather_list = weather_list if self.city not in weather_list: return False else: self.temperature = self.weather_list[self.city]['temperature'] self.weather = self.weather_list[self.city]['weather'] if self.weather_list[self.city]['temperature units'] != tmp_units: if tmp_units == 'celsius': return self.fahrenheit_to_celsius(), self.weather elif tmp_units == 'fahrenheit': return self.celsius_to_fahrenheit(), self.weather else: return self.temperature, self.weather def set_city(self, city): """ Set the city of the weather system. :param city: the city to set, str. :return: None >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.set_city('Beijing') >>> weatherSystem.city 'Beijing' """ self.city = city def celsius_to_fahrenheit(self): """ Convert the temperature from Celsius to Fahrenheit. :return: the temperature in Fahrenheit, float. >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.temperature = 27 >>> weatherSystem.celsius_to_fahrenheit() 80.6 """ return (self.temperature * 9/5) + 32 def fahrenheit_to_celsius(self): return (self.temperature - 32) * 5/9
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: """ Initialize the weather system with a city name. """ self.temperature = None self.weather = None self.city = city self.weather_list = {} def query(self, weather_list, tmp_units = 'celsius'): """ Query the weather system for the weather and temperature of the city,and convert the temperature units based on the input parameter. :param weather_list: a dictionary of weather information for different cities,dict. :param tmp_units: the temperature units to convert to, str. :return: the temperature and weather of the city, tuple. >>> weatherSystem = WeatherSystem('New York') >>> weather_list = {'New York': {'weather': 'sunny','temperature': 27,'temperature units': 'celsius'},'Beijing': {'weather': 'cloudy','temperature': 23,'temperature units': 'celsius'}} >>> weatherSystem.query(weather_list) (27, 'sunny') """ def set_city(self, city): """ Set the city of the weather system. :param city: the city to set, str. :return: None >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.set_city('Beijing') >>> weatherSystem.city 'Beijing' """ def celsius_to_fahrenheit(self): """ Convert the temperature from Celsius to Fahrenheit. :return: the temperature in Fahrenheit, float. >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.temperature = 27 >>> weatherSystem.celsius_to_fahrenheit() 80.6 """ def fahrenheit_to_celsius(self): """ Convert the temperature from Fahrenheit to Celsius. :return: the temperature in Celsius, float. >>> weatherSystem = WeatherSystem('New York') >>> weatherSystem.temperature = 80.6 >>> weatherSystem.fahrenheit_to_celsius() 26.999999999999996 """
def fahrenheit_to_celsius(self): return (self.temperature - 32) * 5/9
Convert the temperature from Fahrenheit to Celsius.