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_24_sum | class ComplexCalculator:
"""
This is a class that implements addition, subtraction, multiplication, and division operations for complex numbers.
"""
def __init__(self):
pass
@staticmethod
def add(c1, c2):
"""
Adds two complex numbers.
:param c1: The first complex number,complex.
:param c2: The second complex number,complex.
:return: The sum of the two complex numbers,complex.
>>> complexCalculator = ComplexCalculator()
>>> complexCalculator.add(1+2j, 3+4j)
(4+6j)
"""
real = c1.real + c2.real
imaginary = c1.imag + c2.imag
answer = complex(real, imaginary)
return answer
@staticmethod
def subtract(c1, c2):
"""
Subtracts two complex numbers.
:param c1: The first complex number,complex.
:param c2: The second complex number,complex.
:return: The difference of the two complex numbers,complex.
>>> complexCalculator = ComplexCalculator()
>>> complexCalculator.subtract(1+2j, 3+4j)
(-2-2j)
"""
real = c1.real - c2.real
imaginary = c1.imag - c2.imag
return complex(real, imaginary)
@staticmethod
def multiply(c1, c2):
"""
Multiplies two complex numbers.
:param c1: The first complex number,complex.
:param c2: The second complex number,complex.
:return: The product of the two complex numbers,complex.
>>> complexCalculator = ComplexCalculator()
>>> complexCalculator.multiply(1+2j, 3+4j)
(-5+10j)
"""
real = c1.real * c2.real - c1.imag * c2.imag
imaginary = c1.real * c2.imag + c1.imag * c2.real
return complex(real, imaginary)
@staticmethod
def divide(c1, c2):
denominator = c2.real**2 + c2.imag**2
real = (c1.real * c2.real + c1.imag * c2.imag) / denominator
imaginary = (c1.imag * c2.real - c1.real * c2.imag) / denominator
return complex(real, imaginary) | class ComplexCalculator:
"""
This is a class that implements addition, subtraction, multiplication, and division operations for complex numbers.
"""
def __init__(self):
pass
@staticmethod
def add(c1, c2):
"""
Adds two complex numbers.
:param c1: The first complex number,complex.
:param c2: The second complex number,complex.
:return: The sum of the two complex numbers,complex.
>>> complexCalculator = ComplexCalculator()
>>> complexCalculator.add(1+2j, 3+4j)
(4+6j)
"""
@staticmethod
def subtract(c1, c2):
"""
Subtracts two complex numbers.
:param c1: The first complex number,complex.
:param c2: The second complex number,complex.
:return: The difference of the two complex numbers,complex.
>>> complexCalculator = ComplexCalculator()
>>> complexCalculator.subtract(1+2j, 3+4j)
(-2-2j)
"""
@staticmethod
def multiply(c1, c2):
"""
Multiplies two complex numbers.
:param c1: The first complex number,complex.
:param c2: The second complex number,complex.
:return: The product of the two complex numbers,complex.
>>> complexCalculator = ComplexCalculator()
>>> complexCalculator.multiply(1+2j, 3+4j)
(-5+10j)
"""
@staticmethod
def divide(c1, c2):
"""
Divides two complex numbers.
:param c1: The first complex number,complex.
:param c2: The second complex number,complex.
:return: The quotient of the two complex numbers,complex.
>>> complexCalculator = ComplexCalculator()
>>> complexCalculator.divide(1+2j, 3+4j)
(0.44+0.08j)
""" | @staticmethod
def divide(c1, c2):
denominator = c2.real**2 + c2.imag**2
real = (c1.real * c2.real + c1.imag * c2.imag) / denominator
imaginary = (c1.imag * c2.real - c1.real * c2.imag) / denominator
return complex(real, imaginary) | Divides two complex numbers. |
ClassEval_25_sum | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
self.cookies_file = cookies_file
self.cookies = None
def load_cookies(self):
"""
Loads the cookies from the cookies_file to the cookies data.
:return: The cookies data, dict.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.load_cookies()
{'key1': 'value1', 'key2': 'value2'}
"""
try:
with open(self.cookies_file, 'r') as file:
cookies_data = json.load(file)
return cookies_data
except FileNotFoundError:
return {}
def _save_cookies(self):
"""
Saves the cookies to the cookies_file, and returns True if successful, False otherwise.
:return: True if successful, False otherwise.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.cookies = {'key1': 'value1', 'key2': 'value2'}
>>> cookies_util._save_cookies()
True
"""
try:
with open(self.cookies_file, 'w') as file:
json.dump(self.cookies, file)
return True
except:
return False
def set_cookies(self, request):
request['cookies'] = '; '.join([f'{key}={value}' for key, value in self.cookies.items()]) | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
"""
Initializes the CookiesUtil with the specified cookies file.
:param cookies_file: The cookies file to use, str.
"""
self.cookies_file = cookies_file
self.cookies = None
def load_cookies(self):
"""
Loads the cookies from the cookies_file to the cookies data.
:return: The cookies data, dict.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.load_cookies()
{'key1': 'value1', 'key2': 'value2'}
"""
def _save_cookies(self):
"""
Saves the cookies to the cookies_file, and returns True if successful, False otherwise.
:return: True if successful, False otherwise.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.cookies = {'key1': 'value1', 'key2': 'value2'}
>>> cookies_util._save_cookies()
True
""" | def get_cookies(self, reponse):
self.cookies = reponse['cookies']
self._save_cookies() | Gets the cookies from the specified response,and save it to cookies_file. |
ClassEval_25_sum | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
self.cookies_file = cookies_file
self.cookies = None
def get_cookies(self, reponse):
"""
Gets the cookies from the specified response,and save it to cookies_file.
:param reponse: The response to get cookies from, dict.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.get_cookies({'cookies': {'key1': 'value1', 'key2': 'value2'}})
>>> cookies_util.cookies
{'key1': 'value1', 'key2': 'value2'}
"""
self.cookies = reponse['cookies']
self._save_cookies()
def _save_cookies(self):
"""
Saves the cookies to the cookies_file, and returns True if successful, False otherwise.
:return: True if successful, False otherwise.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.cookies = {'key1': 'value1', 'key2': 'value2'}
>>> cookies_util._save_cookies()
True
"""
try:
with open(self.cookies_file, 'w') as file:
json.dump(self.cookies, file)
return True
except:
return False
def set_cookies(self, request):
request['cookies'] = '; '.join([f'{key}={value}' for key, value in self.cookies.items()]) | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
"""
Initializes the CookiesUtil with the specified cookies file.
:param cookies_file: The cookies file to use, str.
"""
self.cookies_file = cookies_file
self.cookies = None
def get_cookies(self, reponse):
"""
Gets the cookies from the specified response,and save it to cookies_file.
:param reponse: The response to get cookies from, dict.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.get_cookies({'cookies': {'key1': 'value1', 'key2': 'value2'}})
>>> cookies_util.cookies
{'key1': 'value1', 'key2': 'value2'}
"""
def _save_cookies(self):
"""
Saves the cookies to the cookies_file, and returns True if successful, False otherwise.
:return: True if successful, False otherwise.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.cookies = {'key1': 'value1', 'key2': 'value2'}
>>> cookies_util._save_cookies()
True
""" | def load_cookies(self):
try:
with open(self.cookies_file, 'r') as file:
cookies_data = json.load(file)
return cookies_data
except FileNotFoundError:
return {} | Loads the cookies from the cookies_file to the cookies data. |
ClassEval_25_sum | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
self.cookies_file = cookies_file
self.cookies = None
def get_cookies(self, reponse):
"""
Gets the cookies from the specified response,and save it to cookies_file.
:param reponse: The response to get cookies from, dict.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.get_cookies({'cookies': {'key1': 'value1', 'key2': 'value2'}})
>>> cookies_util.cookies
{'key1': 'value1', 'key2': 'value2'}
"""
self.cookies = reponse['cookies']
self._save_cookies()
def load_cookies(self):
"""
Loads the cookies from the cookies_file to the cookies data.
:return: The cookies data, dict.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.load_cookies()
{'key1': 'value1', 'key2': 'value2'}
"""
try:
with open(self.cookies_file, 'r') as file:
cookies_data = json.load(file)
return cookies_data
except FileNotFoundError:
return {}
def set_cookies(self, request):
request['cookies'] = '; '.join([f'{key}={value}' for key, value in self.cookies.items()]) | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
"""
Initializes the CookiesUtil with the specified cookies file.
:param cookies_file: The cookies file to use, str.
"""
self.cookies_file = cookies_file
self.cookies = None
def get_cookies(self, reponse):
"""
Gets the cookies from the specified response,and save it to cookies_file.
:param reponse: The response to get cookies from, dict.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.get_cookies({'cookies': {'key1': 'value1', 'key2': 'value2'}})
>>> cookies_util.cookies
{'key1': 'value1', 'key2': 'value2'}
"""
def load_cookies(self):
"""
Loads the cookies from the cookies_file to the cookies data.
:return: The cookies data, dict.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.load_cookies()
{'key1': 'value1', 'key2': 'value2'}
"""
def _save_cookies(self):
"""
Saves the cookies to the cookies_file, and returns True if successful, False otherwise.
:return: True if successful, False otherwise.
>>> cookies_util = CookiesUtil('cookies.json')
>>> cookies_util.cookies = {'key1': 'value1', 'key2': 'value2'}
>>> cookies_util._save_cookies()
True
""" | def _save_cookies(self):
try:
with open(self.cookies_file, 'w') as file:
json.dump(self.cookies, file)
return True
except:
return False | Saves the cookies to the cookies_file, and returns True if successful, False otherwise. |
ClassEval_26_sum | import csv
class CSVProcessor:
"""
This is a class for processing CSV files, including readring and writing CSV data, as well as processing specific operations and saving as a new CSV file.
"""
def __init__(self):
pass
def write_csv(self, data, file_name):
"""
Write data into a csv file.
:param file_name: str, name of the csv file
:return:int, if success return 1, or 0 otherwise
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.write_csv([['a', 'b', 'c', 'd'], ['1', '2', '3', '4']], 'write_test.csv')
1
"""
try:
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
return 1
except:
return 0
def process_csv_data(self, N, save_file_name):
"""
Read a csv file into variable title and data.
Only remain the N th (from 0) column data and Capitalize them, store the title and new data into a new csv file.
Add '_process' suffix after old file name, as a new file name.
:param N: int, the N th column(from 0)
:param save_file_name, the name of file that needs to be processed.
:return:int, if success return 1, or 0 otherwise
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.read_csv('read_test.csv')
(['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])
>>> csvProcessor.process_csv_data(0, 'read_test.csv')
1
>>> csvProcessor.read_csv('read_test_process.csv')
(['a', 'b', 'c', 'd'], [['HELLO']])
"""
title, data = self.read_csv(save_file_name)
column_data = [row[N] for row in data]
column_data = [row.upper() for row in column_data]
new_data = [title, column_data]
return self.write_csv(new_data, save_file_name.split('.')[0] + '_process.csv') | import csv
class CSVProcessor:
"""
This is a class for processing CSV files, including readring and writing CSV data, as well as processing specific operations and saving as a new CSV file.
"""
def __init__(self):
pass
def write_csv(self, data, file_name):
"""
Write data into a csv file.
:param file_name: str, name of the csv file
:return:int, if success return 1, or 0 otherwise
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.write_csv([['a', 'b', 'c', 'd'], ['1', '2', '3', '4']], 'write_test.csv')
1
"""
def process_csv_data(self, N, save_file_name):
"""
Read a csv file into variable title and data.
Only remain the N th (from 0) column data and Capitalize them, store the title and new data into a new csv file.
Add '_process' suffix after old file name, as a new file name.
:param N: int, the N th column(from 0)
:param save_file_name, the name of file that needs to be processed.
:return:int, if success return 1, or 0 otherwise
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.read_csv('read_test.csv')
(['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])
>>> csvProcessor.process_csv_data(0, 'read_test.csv')
1
>>> csvProcessor.read_csv('read_test_process.csv')
(['a', 'b', 'c', 'd'], [['HELLO']])
""" | def read_csv(self, file_name):
data = []
with open(file_name, 'r') as file:
reader = csv.reader(file)
title = next(reader)
for row in reader:
data.append(row)
return title, data | Read the csv file by file_name, get the title and data from it |
ClassEval_26_sum | import csv
class CSVProcessor:
"""
This is a class for processing CSV files, including readring and writing CSV data, as well as processing specific operations and saving as a new CSV file.
"""
def __init__(self):
pass
def read_csv(self, file_name):
"""
Read the csv file by file_name, get the title and data from it
:param file_name: str, name of the csv file
:return title, data: (list, list), first row is title, the rest is data
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.read_csv('read_test.csv')
(['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])
"""
data = []
with open(file_name, 'r') as file:
reader = csv.reader(file)
title = next(reader)
for row in reader:
data.append(row)
return title, data
def process_csv_data(self, N, save_file_name):
"""
Read a csv file into variable title and data.
Only remain the N th (from 0) column data and Capitalize them, store the title and new data into a new csv file.
Add '_process' suffix after old file name, as a new file name.
:param N: int, the N th column(from 0)
:param save_file_name, the name of file that needs to be processed.
:return:int, if success return 1, or 0 otherwise
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.read_csv('read_test.csv')
(['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])
>>> csvProcessor.process_csv_data(0, 'read_test.csv')
1
>>> csvProcessor.read_csv('read_test_process.csv')
(['a', 'b', 'c', 'd'], [['HELLO']])
"""
title, data = self.read_csv(save_file_name)
column_data = [row[N] for row in data]
column_data = [row.upper() for row in column_data]
new_data = [title, column_data]
return self.write_csv(new_data, save_file_name.split('.')[0] + '_process.csv') | import csv
class CSVProcessor:
"""
This is a class for processing CSV files, including readring and writing CSV data, as well as processing specific operations and saving as a new CSV file.
"""
def __init__(self):
pass
def read_csv(self, file_name):
"""
Read the csv file by file_name, get the title and data from it
:param file_name: str, name of the csv file
:return title, data: (list, list), first row is title, the rest is data
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.read_csv('read_test.csv')
(['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])
"""
def process_csv_data(self, N, save_file_name):
"""
Read a csv file into variable title and data.
Only remain the N th (from 0) column data and Capitalize them, store the title and new data into a new csv file.
Add '_process' suffix after old file name, as a new file name.
:param N: int, the N th column(from 0)
:param save_file_name, the name of file that needs to be processed.
:return:int, if success return 1, or 0 otherwise
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.read_csv('read_test.csv')
(['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])
>>> csvProcessor.process_csv_data(0, 'read_test.csv')
1
>>> csvProcessor.read_csv('read_test_process.csv')
(['a', 'b', 'c', 'd'], [['HELLO']])
""" | def write_csv(self, data, file_name):
try:
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
return 1
except:
return 0 | Write data into a csv file. |
ClassEval_26_sum | import csv
class CSVProcessor:
"""
This is a class for processing CSV files, including readring and writing CSV data, as well as processing specific operations and saving as a new CSV file.
"""
def __init__(self):
pass
def read_csv(self, file_name):
"""
Read the csv file by file_name, get the title and data from it
:param file_name: str, name of the csv file
:return title, data: (list, list), first row is title, the rest is data
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.read_csv('read_test.csv')
(['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])
"""
data = []
with open(file_name, 'r') as file:
reader = csv.reader(file)
title = next(reader)
for row in reader:
data.append(row)
return title, data
def write_csv(self, data, file_name):
"""
Write data into a csv file.
:param file_name: str, name of the csv file
:return:int, if success return 1, or 0 otherwise
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.write_csv([['a', 'b', 'c', 'd'], ['1', '2', '3', '4']], 'write_test.csv')
1
"""
try:
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
return 1
except:
return 0
def process_csv_data(self, N, save_file_name):
title, data = self.read_csv(save_file_name)
column_data = [row[N] for row in data]
column_data = [row.upper() for row in column_data]
new_data = [title, column_data]
return self.write_csv(new_data, save_file_name.split('.')[0] + '_process.csv') | import csv
class CSVProcessor:
"""
This is a class for processing CSV files, including readring and writing CSV data, as well as processing specific operations and saving as a new CSV file.
"""
def __init__(self):
pass
def read_csv(self, file_name):
"""
Read the csv file by file_name, get the title and data from it
:param file_name: str, name of the csv file
:return title, data: (list, list), first row is title, the rest is data
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.read_csv('read_test.csv')
(['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])
"""
def write_csv(self, data, file_name):
"""
Write data into a csv file.
:param file_name: str, name of the csv file
:return:int, if success return 1, or 0 otherwise
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.write_csv([['a', 'b', 'c', 'd'], ['1', '2', '3', '4']], 'write_test.csv')
1
"""
def process_csv_data(self, N, save_file_name):
"""
Read a csv file into variable title and data.
Only remain the N th (from 0) column data and Capitalize them, store the title and new data into a new csv file.
Add '_process' suffix after old file name, as a new file name.
:param N: int, the N th column(from 0)
:param save_file_name, the name of file that needs to be processed.
:return:int, if success return 1, or 0 otherwise
>>> csvProcessor = CSVProcessor()
>>> csvProcessor.read_csv('read_test.csv')
(['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])
>>> csvProcessor.process_csv_data(0, 'read_test.csv')
1
>>> csvProcessor.read_csv('read_test_process.csv')
(['a', 'b', 'c', 'd'], [['HELLO']])
""" | def process_csv_data(self, N, save_file_name):
title, data = self.read_csv(save_file_name)
column_data = [row[N] for row in data]
column_data = [row.upper() for row in column_data]
new_data = [title, column_data]
return self.write_csv(new_data, save_file_name.split('.')[0] + '_process.csv') | Read a csv file into variable title and data. Only remain the N th (from 0) column data and Capitalize them, store the title and new data into a new csv file. Add '_process' suffix after old file name, as a new file name. |
ClassEval_27_sum | class CurrencyConverter:
"""
This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.
"""
def __init__(self):
self.rates = {
'USD': 1.0,
'EUR': 0.85,
'GBP': 0.72,
'JPY': 110.15,
'CAD': 1.23,
'AUD': 1.34,
'CNY': 6.40,
}
def get_supported_currencies(self):
"""
Returns a list of supported currency types
:return:list, All supported currency types
>>> cc = CurrencyConverter()
>>> cc.get_supported_currencies()
['USD','EUR','GBP','JPY','CAD','AUD','CNY']
"""
return list(self.rates.keys())
def add_currency_rate(self, currency, rate):
"""
Add a new supported currency type, return False if the currency type is already in the support list
:param currency:string, currency type to be added
:param rate:float, exchange rate for this type of currency
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.add_currency_rate('KRW', 1308.84)
self.rates['KRW'] = 1308.84
"""
if currency in self.rates:
return False
self.rates[currency] = rate
def update_currency_rate(self, currency, new_rate):
"""
Update the exchange rate for a certain currency
:param currency:string
:param new_rate:float
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.update_currency_rate('CNY', 7.18)
self.rates['CNY'] = 7.18
"""
if currency not in self.rates:
return False
self.rates[currency] = new_rate | class CurrencyConverter:
"""
This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.
"""
def __init__(self):
"""
Initialize the exchange rate of the US dollar against various currencies
"""
self.rates = {
'USD': 1.0,
'EUR': 0.85,
'GBP': 0.72,
'JPY': 110.15,
'CAD': 1.23,
'AUD': 1.34,
'CNY': 6.40,
}
def get_supported_currencies(self):
"""
Returns a list of supported currency types
:return:list, All supported currency types
>>> cc = CurrencyConverter()
>>> cc.get_supported_currencies()
['USD','EUR','GBP','JPY','CAD','AUD','CNY']
"""
def add_currency_rate(self, currency, rate):
"""
Add a new supported currency type, return False if the currency type is already in the support list
:param currency:string, currency type to be added
:param rate:float, exchange rate for this type of currency
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.add_currency_rate('KRW', 1308.84)
self.rates['KRW'] = 1308.84
"""
def update_currency_rate(self, currency, new_rate):
"""
Update the exchange rate for a certain currency
:param currency:string
:param new_rate:float
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.update_currency_rate('CNY', 7.18)
self.rates['CNY'] = 7.18
""" | def convert(self, amount, from_currency, to_currency):
if from_currency == to_currency:
return amount
if from_currency not in self.rates or to_currency not in self.rates:
return False
from_rate = self.rates[from_currency]
to_rate = self.rates[to_currency]
converted_amount = (amount / from_rate) * to_rate
return converted_amount | Convert the value of a given currency to another currency type |
ClassEval_27_sum | class CurrencyConverter:
"""
This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.
"""
def __init__(self):
self.rates = {
'USD': 1.0,
'EUR': 0.85,
'GBP': 0.72,
'JPY': 110.15,
'CAD': 1.23,
'AUD': 1.34,
'CNY': 6.40,
}
def convert(self, amount, from_currency, to_currency):
"""
Convert the value of a given currency to another currency type
:param amount: float, The value of a given currency
:param from_currency: string, source currency type
:param to_currency: string, target currency type
:return: float, value converted to another currency type
>>> cc = CurrencyConverter()
>>> cc.convert(64, 'CNY','USD')
10.0
"""
if from_currency == to_currency:
return amount
if from_currency not in self.rates or to_currency not in self.rates:
return False
from_rate = self.rates[from_currency]
to_rate = self.rates[to_currency]
converted_amount = (amount / from_rate) * to_rate
return converted_amount
def add_currency_rate(self, currency, rate):
"""
Add a new supported currency type, return False if the currency type is already in the support list
:param currency:string, currency type to be added
:param rate:float, exchange rate for this type of currency
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.add_currency_rate('KRW', 1308.84)
self.rates['KRW'] = 1308.84
"""
if currency in self.rates:
return False
self.rates[currency] = rate
def update_currency_rate(self, currency, new_rate):
"""
Update the exchange rate for a certain currency
:param currency:string
:param new_rate:float
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.update_currency_rate('CNY', 7.18)
self.rates['CNY'] = 7.18
"""
if currency not in self.rates:
return False
self.rates[currency] = new_rate | class CurrencyConverter:
"""
This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.
"""
def __init__(self):
"""
Initialize the exchange rate of the US dollar against various currencies
"""
self.rates = {
'USD': 1.0,
'EUR': 0.85,
'GBP': 0.72,
'JPY': 110.15,
'CAD': 1.23,
'AUD': 1.34,
'CNY': 6.40,
}
def convert(self, amount, from_currency, to_currency):
"""
Convert the value of a given currency to another currency type
:param amount: float, The value of a given currency
:param from_currency: string, source currency type
:param to_currency: string, target currency type
:return: float, value converted to another currency type
>>> cc = CurrencyConverter()
>>> cc.convert(64, 'CNY','USD')
10.0
"""
def add_currency_rate(self, currency, rate):
"""
Add a new supported currency type, return False if the currency type is already in the support list
:param currency:string, currency type to be added
:param rate:float, exchange rate for this type of currency
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.add_currency_rate('KRW', 1308.84)
self.rates['KRW'] = 1308.84
"""
def update_currency_rate(self, currency, new_rate):
"""
Update the exchange rate for a certain currency
:param currency:string
:param new_rate:float
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.update_currency_rate('CNY', 7.18)
self.rates['CNY'] = 7.18
""" | def get_supported_currencies(self):
return list(self.rates.keys()) | Returns a list of supported currency types |
ClassEval_27_sum | class CurrencyConverter:
"""
This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.
"""
def __init__(self):
self.rates = {
'USD': 1.0,
'EUR': 0.85,
'GBP': 0.72,
'JPY': 110.15,
'CAD': 1.23,
'AUD': 1.34,
'CNY': 6.40,
}
def convert(self, amount, from_currency, to_currency):
"""
Convert the value of a given currency to another currency type
:param amount: float, The value of a given currency
:param from_currency: string, source currency type
:param to_currency: string, target currency type
:return: float, value converted to another currency type
>>> cc = CurrencyConverter()
>>> cc.convert(64, 'CNY','USD')
10.0
"""
if from_currency == to_currency:
return amount
if from_currency not in self.rates or to_currency not in self.rates:
return False
from_rate = self.rates[from_currency]
to_rate = self.rates[to_currency]
converted_amount = (amount / from_rate) * to_rate
return converted_amount
def get_supported_currencies(self):
"""
Returns a list of supported currency types
:return:list, All supported currency types
>>> cc = CurrencyConverter()
>>> cc.get_supported_currencies()
['USD','EUR','GBP','JPY','CAD','AUD','CNY']
"""
return list(self.rates.keys())
def update_currency_rate(self, currency, new_rate):
"""
Update the exchange rate for a certain currency
:param currency:string
:param new_rate:float
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.update_currency_rate('CNY', 7.18)
self.rates['CNY'] = 7.18
"""
if currency not in self.rates:
return False
self.rates[currency] = new_rate | class CurrencyConverter:
"""
This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.
"""
def __init__(self):
"""
Initialize the exchange rate of the US dollar against various currencies
"""
self.rates = {
'USD': 1.0,
'EUR': 0.85,
'GBP': 0.72,
'JPY': 110.15,
'CAD': 1.23,
'AUD': 1.34,
'CNY': 6.40,
}
def convert(self, amount, from_currency, to_currency):
"""
Convert the value of a given currency to another currency type
:param amount: float, The value of a given currency
:param from_currency: string, source currency type
:param to_currency: string, target currency type
:return: float, value converted to another currency type
>>> cc = CurrencyConverter()
>>> cc.convert(64, 'CNY','USD')
10.0
"""
def get_supported_currencies(self):
"""
Returns a list of supported currency types
:return:list, All supported currency types
>>> cc = CurrencyConverter()
>>> cc.get_supported_currencies()
['USD','EUR','GBP','JPY','CAD','AUD','CNY']
"""
def update_currency_rate(self, currency, new_rate):
"""
Update the exchange rate for a certain currency
:param currency:string
:param new_rate:float
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.update_currency_rate('CNY', 7.18)
self.rates['CNY'] = 7.18
""" | def add_currency_rate(self, currency, rate):
if currency in self.rates:
return False
self.rates[currency] = rate | Add a new supported currency type, return False if the currency type is already in the support list |
ClassEval_27_sum | class CurrencyConverter:
"""
This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.
"""
def __init__(self):
self.rates = {
'USD': 1.0,
'EUR': 0.85,
'GBP': 0.72,
'JPY': 110.15,
'CAD': 1.23,
'AUD': 1.34,
'CNY': 6.40,
}
def convert(self, amount, from_currency, to_currency):
"""
Convert the value of a given currency to another currency type
:param amount: float, The value of a given currency
:param from_currency: string, source currency type
:param to_currency: string, target currency type
:return: float, value converted to another currency type
>>> cc = CurrencyConverter()
>>> cc.convert(64, 'CNY','USD')
10.0
"""
if from_currency == to_currency:
return amount
if from_currency not in self.rates or to_currency not in self.rates:
return False
from_rate = self.rates[from_currency]
to_rate = self.rates[to_currency]
converted_amount = (amount / from_rate) * to_rate
return converted_amount
def get_supported_currencies(self):
"""
Returns a list of supported currency types
:return:list, All supported currency types
>>> cc = CurrencyConverter()
>>> cc.get_supported_currencies()
['USD','EUR','GBP','JPY','CAD','AUD','CNY']
"""
return list(self.rates.keys())
def add_currency_rate(self, currency, rate):
"""
Add a new supported currency type, return False if the currency type is already in the support list
:param currency:string, currency type to be added
:param rate:float, exchange rate for this type of currency
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.add_currency_rate('KRW', 1308.84)
self.rates['KRW'] = 1308.84
"""
if currency in self.rates:
return False
self.rates[currency] = rate
def update_currency_rate(self, currency, new_rate):
if currency not in self.rates:
return False
self.rates[currency] = new_rate | class CurrencyConverter:
"""
This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.
"""
def __init__(self):
"""
Initialize the exchange rate of the US dollar against various currencies
"""
self.rates = {
'USD': 1.0,
'EUR': 0.85,
'GBP': 0.72,
'JPY': 110.15,
'CAD': 1.23,
'AUD': 1.34,
'CNY': 6.40,
}
def convert(self, amount, from_currency, to_currency):
"""
Convert the value of a given currency to another currency type
:param amount: float, The value of a given currency
:param from_currency: string, source currency type
:param to_currency: string, target currency type
:return: float, value converted to another currency type
>>> cc = CurrencyConverter()
>>> cc.convert(64, 'CNY','USD')
10.0
"""
def get_supported_currencies(self):
"""
Returns a list of supported currency types
:return:list, All supported currency types
>>> cc = CurrencyConverter()
>>> cc.get_supported_currencies()
['USD','EUR','GBP','JPY','CAD','AUD','CNY']
"""
def add_currency_rate(self, currency, rate):
"""
Add a new supported currency type, return False if the currency type is already in the support list
:param currency:string, currency type to be added
:param rate:float, exchange rate for this type of currency
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.add_currency_rate('KRW', 1308.84)
self.rates['KRW'] = 1308.84
"""
def update_currency_rate(self, currency, new_rate):
"""
Update the exchange rate for a certain currency
:param currency:string
:param new_rate:float
:return:If successful, returns None; if unsuccessful, returns False
>>> cc = CurrencyConverter()
>>> cc.update_currency_rate('CNY', 7.18)
self.rates['CNY'] = 7.18
""" | def update_currency_rate(self, currency, new_rate):
if currency not in self.rates:
return False
self.rates[currency] = new_rate | Update the exchange rate for a certain currency |
ClassEval_28_sum | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.
"""
def __init__(self, database_name):
self.database_name = database_name
def insert_into_database(self, table_name, data):
"""
Insert data into the specified table in the database.
:param table_name: str, the name of the table to insert data into.
:param data: list, a list of dictionaries where each dictionary represents a row of data.
>>> db.insert_into_database('user', [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
])
"""
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
for item in data:
insert_query = f"INSERT INTO {table_name} (name, age) VALUES (?, ?)"
cursor.execute(insert_query, (item['name'], item['age']))
conn.commit()
conn.close()
def search_database(self, table_name, name):
"""
Search the specified table in the database for rows with a matching name.
:param table_name: str, the name of the table to search.
:param name: str, the name to search for.
:return: list, a list of tuples representing the rows with matching name, if any;
otherwise, returns None.
>>> db.search_database('user', 'John')
[(1, 'John', 25)]
"""
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
select_query = f"SELECT * FROM {table_name} WHERE name = ?"
cursor.execute(select_query, (name,))
result = cursor.fetchall()
if result:
return result
else:
return None
def delete_from_database(self, table_name, name):
"""
Delete rows from the specified table in the database with a matching name.
:param table_name: str, the name of the table to delete rows from.
:param name: str, the name to match for deletion.
>>> db.delete_from_database('user', 'John')
"""
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
delete_query = f"DELETE FROM {table_name} WHERE name = ?"
cursor.execute(delete_query, (name,))
conn.commit()
conn.close() | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.
"""
def __init__(self, database_name):
"""
Initialize database name of database processor
"""
self.database_name = database_name
def insert_into_database(self, table_name, data):
"""
Insert data into the specified table in the database.
:param table_name: str, the name of the table to insert data into.
:param data: list, a list of dictionaries where each dictionary represents a row of data.
>>> db.insert_into_database('user', [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
])
"""
def search_database(self, table_name, name):
"""
Search the specified table in the database for rows with a matching name.
:param table_name: str, the name of the table to search.
:param name: str, the name to search for.
:return: list, a list of tuples representing the rows with matching name, if any;
otherwise, returns None.
>>> db.search_database('user', 'John')
[(1, 'John', 25)]
"""
def delete_from_database(self, table_name, name):
"""
Delete rows from the specified table in the database with a matching name.
:param table_name: str, the name of the table to delete rows from.
:param name: str, the name to match for deletion.
>>> db.delete_from_database('user', 'John')
""" | def create_table(self, table_name, key1, key2):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
create_table_query = f"CREATE TABLE IF NOT EXISTS {table_name} (id INTEGER PRIMARY KEY, {key1} TEXT, {key2} INTEGER)"
cursor.execute(create_table_query)
conn.commit()
conn.close() | Create a new table in the database if it doesn't exist. And make id (INTEGER) as PRIMARY KEY, make key1 as TEXT, key2 as INTEGER |
ClassEval_28_sum | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.
"""
def __init__(self, database_name):
self.database_name = database_name
def create_table(self, table_name, key1, key2):
"""
Create a new table in the database if it doesn't exist.
And make id (INTEGER) as PRIMARY KEY, make key1 as TEXT, key2 as INTEGER
:param table_name: str, the name of the table to create.
:param key1: str, the name of the first column in the table.
:param key2: str, the name of the second column in the table.
>>> db.create_table('user', 'name', 'age')
"""
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
create_table_query = f"CREATE TABLE IF NOT EXISTS {table_name} (id INTEGER PRIMARY KEY, {key1} TEXT, {key2} INTEGER)"
cursor.execute(create_table_query)
conn.commit()
conn.close()
def search_database(self, table_name, name):
"""
Search the specified table in the database for rows with a matching name.
:param table_name: str, the name of the table to search.
:param name: str, the name to search for.
:return: list, a list of tuples representing the rows with matching name, if any;
otherwise, returns None.
>>> db.search_database('user', 'John')
[(1, 'John', 25)]
"""
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
select_query = f"SELECT * FROM {table_name} WHERE name = ?"
cursor.execute(select_query, (name,))
result = cursor.fetchall()
if result:
return result
else:
return None
def delete_from_database(self, table_name, name):
"""
Delete rows from the specified table in the database with a matching name.
:param table_name: str, the name of the table to delete rows from.
:param name: str, the name to match for deletion.
>>> db.delete_from_database('user', 'John')
"""
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
delete_query = f"DELETE FROM {table_name} WHERE name = ?"
cursor.execute(delete_query, (name,))
conn.commit()
conn.close() | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.
"""
def __init__(self, database_name):
"""
Initialize database name of database processor
"""
self.database_name = database_name
def create_table(self, table_name, key1, key2):
"""
Create a new table in the database if it doesn't exist.
And make id (INTEGER) as PRIMARY KEY, make key1 as TEXT, key2 as INTEGER
:param table_name: str, the name of the table to create.
:param key1: str, the name of the first column in the table.
:param key2: str, the name of the second column in the table.
>>> db.create_table('user', 'name', 'age')
"""
def search_database(self, table_name, name):
"""
Search the specified table in the database for rows with a matching name.
:param table_name: str, the name of the table to search.
:param name: str, the name to search for.
:return: list, a list of tuples representing the rows with matching name, if any;
otherwise, returns None.
>>> db.search_database('user', 'John')
[(1, 'John', 25)]
"""
def delete_from_database(self, table_name, name):
"""
Delete rows from the specified table in the database with a matching name.
:param table_name: str, the name of the table to delete rows from.
:param name: str, the name to match for deletion.
>>> db.delete_from_database('user', 'John')
""" | def insert_into_database(self, table_name, data):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
for item in data:
insert_query = f"INSERT INTO {table_name} (name, age) VALUES (?, ?)"
cursor.execute(insert_query, (item['name'], item['age']))
conn.commit()
conn.close() | Insert data into the specified table in the database. |
ClassEval_28_sum | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.
"""
def __init__(self, database_name):
self.database_name = database_name
def create_table(self, table_name, key1, key2):
"""
Create a new table in the database if it doesn't exist.
And make id (INTEGER) as PRIMARY KEY, make key1 as TEXT, key2 as INTEGER
:param table_name: str, the name of the table to create.
:param key1: str, the name of the first column in the table.
:param key2: str, the name of the second column in the table.
>>> db.create_table('user', 'name', 'age')
"""
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
create_table_query = f"CREATE TABLE IF NOT EXISTS {table_name} (id INTEGER PRIMARY KEY, {key1} TEXT, {key2} INTEGER)"
cursor.execute(create_table_query)
conn.commit()
conn.close()
def insert_into_database(self, table_name, data):
"""
Insert data into the specified table in the database.
:param table_name: str, the name of the table to insert data into.
:param data: list, a list of dictionaries where each dictionary represents a row of data.
>>> db.insert_into_database('user', [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
])
"""
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
for item in data:
insert_query = f"INSERT INTO {table_name} (name, age) VALUES (?, ?)"
cursor.execute(insert_query, (item['name'], item['age']))
conn.commit()
conn.close()
def delete_from_database(self, table_name, name):
"""
Delete rows from the specified table in the database with a matching name.
:param table_name: str, the name of the table to delete rows from.
:param name: str, the name to match for deletion.
>>> db.delete_from_database('user', 'John')
"""
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
delete_query = f"DELETE FROM {table_name} WHERE name = ?"
cursor.execute(delete_query, (name,))
conn.commit()
conn.close() | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.
"""
def __init__(self, database_name):
"""
Initialize database name of database processor
"""
self.database_name = database_name
def create_table(self, table_name, key1, key2):
"""
Create a new table in the database if it doesn't exist.
And make id (INTEGER) as PRIMARY KEY, make key1 as TEXT, key2 as INTEGER
:param table_name: str, the name of the table to create.
:param key1: str, the name of the first column in the table.
:param key2: str, the name of the second column in the table.
>>> db.create_table('user', 'name', 'age')
"""
def insert_into_database(self, table_name, data):
"""
Insert data into the specified table in the database.
:param table_name: str, the name of the table to insert data into.
:param data: list, a list of dictionaries where each dictionary represents a row of data.
>>> db.insert_into_database('user', [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
])
"""
def delete_from_database(self, table_name, name):
"""
Delete rows from the specified table in the database with a matching name.
:param table_name: str, the name of the table to delete rows from.
:param name: str, the name to match for deletion.
>>> db.delete_from_database('user', 'John')
""" | def search_database(self, table_name, name):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
select_query = f"SELECT * FROM {table_name} WHERE name = ?"
cursor.execute(select_query, (name,))
result = cursor.fetchall()
if result:
return result
else:
return None | Search the specified table in the database for rows with a matching name. |
ClassEval_28_sum | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.
"""
def __init__(self, database_name):
self.database_name = database_name
def create_table(self, table_name, key1, key2):
"""
Create a new table in the database if it doesn't exist.
And make id (INTEGER) as PRIMARY KEY, make key1 as TEXT, key2 as INTEGER
:param table_name: str, the name of the table to create.
:param key1: str, the name of the first column in the table.
:param key2: str, the name of the second column in the table.
>>> db.create_table('user', 'name', 'age')
"""
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
create_table_query = f"CREATE TABLE IF NOT EXISTS {table_name} (id INTEGER PRIMARY KEY, {key1} TEXT, {key2} INTEGER)"
cursor.execute(create_table_query)
conn.commit()
conn.close()
def insert_into_database(self, table_name, data):
"""
Insert data into the specified table in the database.
:param table_name: str, the name of the table to insert data into.
:param data: list, a list of dictionaries where each dictionary represents a row of data.
>>> db.insert_into_database('user', [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
])
"""
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
for item in data:
insert_query = f"INSERT INTO {table_name} (name, age) VALUES (?, ?)"
cursor.execute(insert_query, (item['name'], item['age']))
conn.commit()
conn.close()
def search_database(self, table_name, name):
"""
Search the specified table in the database for rows with a matching name.
:param table_name: str, the name of the table to search.
:param name: str, the name to search for.
:return: list, a list of tuples representing the rows with matching name, if any;
otherwise, returns None.
>>> db.search_database('user', 'John')
[(1, 'John', 25)]
"""
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
select_query = f"SELECT * FROM {table_name} WHERE name = ?"
cursor.execute(select_query, (name,))
result = cursor.fetchall()
if result:
return result
else:
return None
def delete_from_database(self, table_name, name):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
delete_query = f"DELETE FROM {table_name} WHERE name = ?"
cursor.execute(delete_query, (name,))
conn.commit()
conn.close() | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.
"""
def __init__(self, database_name):
"""
Initialize database name of database processor
"""
self.database_name = database_name
def create_table(self, table_name, key1, key2):
"""
Create a new table in the database if it doesn't exist.
And make id (INTEGER) as PRIMARY KEY, make key1 as TEXT, key2 as INTEGER
:param table_name: str, the name of the table to create.
:param key1: str, the name of the first column in the table.
:param key2: str, the name of the second column in the table.
>>> db.create_table('user', 'name', 'age')
"""
def insert_into_database(self, table_name, data):
"""
Insert data into the specified table in the database.
:param table_name: str, the name of the table to insert data into.
:param data: list, a list of dictionaries where each dictionary represents a row of data.
>>> db.insert_into_database('user', [
{'name': 'John', 'age': 25},
{'name': 'Alice', 'age': 30}
])
"""
def search_database(self, table_name, name):
"""
Search the specified table in the database for rows with a matching name.
:param table_name: str, the name of the table to search.
:param name: str, the name to search for.
:return: list, a list of tuples representing the rows with matching name, if any;
otherwise, returns None.
>>> db.search_database('user', 'John')
[(1, 'John', 25)]
"""
def delete_from_database(self, table_name, name):
"""
Delete rows from the specified table in the database with a matching name.
:param table_name: str, the name of the table to delete rows from.
:param name: str, the name to match for deletion.
>>> db.delete_from_database('user', 'John')
""" | def delete_from_database(self, table_name, name):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
delete_query = f"DELETE FROM {table_name} WHERE name = ?"
cursor.execute(delete_query, (name,))
conn.commit()
conn.close() | Delete rows from the specified table in the database with a matching name. |
ClassEval_29_sum | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def median(self, data):
"""
Calculate the median of a group of data, accurate to two digits after the Decimal separator
:param data:list, data list
:return:float, the median value
>>> ds = DataStatistics()
>>> ds.median([2, 5, 1, 3, 4])
3.00
"""
sorted_data = sorted(data)
n = len(sorted_data)
if n % 2 == 0:
middle = n // 2
return round((sorted_data[middle - 1] + sorted_data[middle]) / 2, 2)
else:
middle = n // 2
return sorted_data[middle]
def mode(self, data):
"""
Calculate the mode of a set of data
:param data:list, data list
:return:float, the mode
>>> ds = DataStatistics()
>>> ds.mode([2, 2, 3, 3, 4])
[2, 3]
"""
counter = Counter(data)
mode_count = max(counter.values())
mode = [x for x, count in counter.items() if count == mode_count]
return mode | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def median(self, data):
"""
Calculate the median of a group of data, accurate to two digits after the Decimal separator
:param data:list, data list
:return:float, the median value
>>> ds = DataStatistics()
>>> ds.median([2, 5, 1, 3, 4])
3.00
"""
def mode(self, data):
"""
Calculate the mode of a set of data
:param data:list, data list
:return:float, the mode
>>> ds = DataStatistics()
>>> ds.mode([2, 2, 3, 3, 4])
[2, 3]
""" | def mean(self, data):
return round(sum(data) / len(data), 2) | Calculate the average value of a group of data, accurate to two digits after the Decimal separator |
ClassEval_29_sum | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def mean(self, data):
"""
Calculate the average value of a group of data, accurate to two digits after the Decimal separator
:param data:list, data list
:return:float, the mean value
>>> ds = DataStatistics()
>>> ds.mean([1, 2, 3, 4, 5])
3.00
"""
return round(sum(data) / len(data), 2)
def mode(self, data):
"""
Calculate the mode of a set of data
:param data:list, data list
:return:float, the mode
>>> ds = DataStatistics()
>>> ds.mode([2, 2, 3, 3, 4])
[2, 3]
"""
counter = Counter(data)
mode_count = max(counter.values())
mode = [x for x, count in counter.items() if count == mode_count]
return mode | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def mean(self, data):
"""
Calculate the average value of a group of data, accurate to two digits after the Decimal separator
:param data:list, data list
:return:float, the mean value
>>> ds = DataStatistics()
>>> ds.mean([1, 2, 3, 4, 5])
3.00
"""
def mode(self, data):
"""
Calculate the mode of a set of data
:param data:list, data list
:return:float, the mode
>>> ds = DataStatistics()
>>> ds.mode([2, 2, 3, 3, 4])
[2, 3]
""" | def median(self, data):
sorted_data = sorted(data)
n = len(sorted_data)
if n % 2 == 0:
middle = n // 2
return round((sorted_data[middle - 1] + sorted_data[middle]) / 2, 2)
else:
middle = n // 2
return sorted_data[middle] | Calculate the median of a group of data, accurate to two digits after the Decimal separator |
ClassEval_29_sum | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def mean(self, data):
"""
Calculate the average value of a group of data, accurate to two digits after the Decimal separator
:param data:list, data list
:return:float, the mean value
>>> ds = DataStatistics()
>>> ds.mean([1, 2, 3, 4, 5])
3.00
"""
return round(sum(data) / len(data), 2)
def median(self, data):
"""
Calculate the median of a group of data, accurate to two digits after the Decimal separator
:param data:list, data list
:return:float, the median value
>>> ds = DataStatistics()
>>> ds.median([2, 5, 1, 3, 4])
3.00
"""
sorted_data = sorted(data)
n = len(sorted_data)
if n % 2 == 0:
middle = n // 2
return round((sorted_data[middle - 1] + sorted_data[middle]) / 2, 2)
else:
middle = n // 2
return sorted_data[middle]
def mode(self, data):
counter = Counter(data)
mode_count = max(counter.values())
mode = [x for x, count in counter.items() if count == mode_count]
return mode | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def mean(self, data):
"""
Calculate the average value of a group of data, accurate to two digits after the Decimal separator
:param data:list, data list
:return:float, the mean value
>>> ds = DataStatistics()
>>> ds.mean([1, 2, 3, 4, 5])
3.00
"""
def median(self, data):
"""
Calculate the median of a group of data, accurate to two digits after the Decimal separator
:param data:list, data list
:return:float, the median value
>>> ds = DataStatistics()
>>> ds.median([2, 5, 1, 3, 4])
3.00
"""
def mode(self, data):
"""
Calculate the mode of a set of data
:param data:list, data list
:return:float, the mode
>>> ds = DataStatistics()
>>> ds.mode([2, 2, 3, 3, 4])
[2, 3]
""" | def mode(self, data):
counter = Counter(data)
mode_count = max(counter.values())
mode = [x for x, count in counter.items() if count == mode_count]
return mode | Calculate the mode of a set of data |
ClassEval_30_sum | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
self.data = np.array(data)
def get_min(self):
"""
Calculate the minimum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_min()
1
"""
return np.min(self.data)
def get_max(self):
"""
Calculate the maximum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_max()
4
"""
return np.max(self.data)
def get_variance(self):
"""
Calculate variance, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_variance()
1.25
"""
return round(np.var(self.data), 2)
def get_std_deviation(self):
"""
Calculate standard deviation, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_std_deviation()
1.12
"""
return round(np.std(self.data), 2)
def get_correlation(self):
"""
Calculate correlation
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_correlation()
1.0
"""
return np.corrcoef(self.data, rowvar=False) | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
"""
self.data = np.array(data)
def get_min(self):
"""
Calculate the minimum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_min()
1
"""
def get_max(self):
"""
Calculate the maximum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_max()
4
"""
def get_variance(self):
"""
Calculate variance, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_variance()
1.25
"""
def get_std_deviation(self):
"""
Calculate standard deviation, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_std_deviation()
1.12
"""
def get_correlation(self):
"""
Calculate correlation
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_correlation()
1.0
""" | def get_sum(self):
return np.sum(self.data) | Calculate the sum of data |
ClassEval_30_sum | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
self.data = np.array(data)
def get_sum(self):
"""
Calculate the sum of data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_sum()
10
"""
return np.sum(self.data)
def get_max(self):
"""
Calculate the maximum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_max()
4
"""
return np.max(self.data)
def get_variance(self):
"""
Calculate variance, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_variance()
1.25
"""
return round(np.var(self.data), 2)
def get_std_deviation(self):
"""
Calculate standard deviation, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_std_deviation()
1.12
"""
return round(np.std(self.data), 2)
def get_correlation(self):
"""
Calculate correlation
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_correlation()
1.0
"""
return np.corrcoef(self.data, rowvar=False) | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
"""
self.data = np.array(data)
def get_sum(self):
"""
Calculate the sum of data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_sum()
10
"""
def get_max(self):
"""
Calculate the maximum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_max()
4
"""
def get_variance(self):
"""
Calculate variance, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_variance()
1.25
"""
def get_std_deviation(self):
"""
Calculate standard deviation, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_std_deviation()
1.12
"""
def get_correlation(self):
"""
Calculate correlation
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_correlation()
1.0
""" | def get_min(self):
return np.min(self.data) | Calculate the minimum value in the data |
ClassEval_30_sum | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
self.data = np.array(data)
def get_sum(self):
"""
Calculate the sum of data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_sum()
10
"""
return np.sum(self.data)
def get_min(self):
"""
Calculate the minimum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_min()
1
"""
return np.min(self.data)
def get_variance(self):
"""
Calculate variance, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_variance()
1.25
"""
return round(np.var(self.data), 2)
def get_std_deviation(self):
"""
Calculate standard deviation, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_std_deviation()
1.12
"""
return round(np.std(self.data), 2)
def get_correlation(self):
"""
Calculate correlation
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_correlation()
1.0
"""
return np.corrcoef(self.data, rowvar=False) | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
"""
self.data = np.array(data)
def get_sum(self):
"""
Calculate the sum of data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_sum()
10
"""
def get_min(self):
"""
Calculate the minimum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_min()
1
"""
def get_variance(self):
"""
Calculate variance, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_variance()
1.25
"""
def get_std_deviation(self):
"""
Calculate standard deviation, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_std_deviation()
1.12
"""
def get_correlation(self):
"""
Calculate correlation
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_correlation()
1.0
""" | def get_max(self):
return np.max(self.data) | Calculate the maximum value in the data |
ClassEval_30_sum | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
self.data = np.array(data)
def get_sum(self):
"""
Calculate the sum of data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_sum()
10
"""
return np.sum(self.data)
def get_min(self):
"""
Calculate the minimum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_min()
1
"""
return np.min(self.data)
def get_max(self):
"""
Calculate the maximum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_max()
4
"""
return np.max(self.data)
def get_std_deviation(self):
"""
Calculate standard deviation, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_std_deviation()
1.12
"""
return round(np.std(self.data), 2)
def get_correlation(self):
"""
Calculate correlation
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_correlation()
1.0
"""
return np.corrcoef(self.data, rowvar=False) | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
"""
self.data = np.array(data)
def get_sum(self):
"""
Calculate the sum of data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_sum()
10
"""
def get_min(self):
"""
Calculate the minimum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_min()
1
"""
def get_max(self):
"""
Calculate the maximum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_max()
4
"""
def get_std_deviation(self):
"""
Calculate standard deviation, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_std_deviation()
1.12
"""
def get_correlation(self):
"""
Calculate correlation
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_correlation()
1.0
""" | def get_variance(self):
return round(np.var(self.data), 2) | Calculate variance, accurate to two digits after the Decimal separator |
ClassEval_30_sum | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
self.data = np.array(data)
def get_sum(self):
"""
Calculate the sum of data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_sum()
10
"""
return np.sum(self.data)
def get_min(self):
"""
Calculate the minimum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_min()
1
"""
return np.min(self.data)
def get_max(self):
"""
Calculate the maximum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_max()
4
"""
return np.max(self.data)
def get_variance(self):
"""
Calculate variance, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_variance()
1.25
"""
return round(np.var(self.data), 2)
def get_correlation(self):
"""
Calculate correlation
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_correlation()
1.0
"""
return np.corrcoef(self.data, rowvar=False) | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
"""
self.data = np.array(data)
def get_sum(self):
"""
Calculate the sum of data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_sum()
10
"""
def get_min(self):
"""
Calculate the minimum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_min()
1
"""
def get_max(self):
"""
Calculate the maximum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_max()
4
"""
def get_variance(self):
"""
Calculate variance, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_variance()
1.25
"""
def get_correlation(self):
"""
Calculate correlation
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_correlation()
1.0
""" | def get_std_deviation(self):
return round(np.std(self.data), 2) | Calculate standard deviation, accurate to two digits after the Decimal separator |
ClassEval_30_sum | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
self.data = np.array(data)
def get_sum(self):
"""
Calculate the sum of data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_sum()
10
"""
return np.sum(self.data)
def get_min(self):
"""
Calculate the minimum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_min()
1
"""
return np.min(self.data)
def get_max(self):
"""
Calculate the maximum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_max()
4
"""
return np.max(self.data)
def get_variance(self):
"""
Calculate variance, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_variance()
1.25
"""
return round(np.var(self.data), 2)
def get_std_deviation(self):
"""
Calculate standard deviation, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_std_deviation()
1.12
"""
return round(np.std(self.data), 2)
def get_correlation(self):
return np.corrcoef(self.data, rowvar=False) | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
"""
self.data = np.array(data)
def get_sum(self):
"""
Calculate the sum of data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_sum()
10
"""
def get_min(self):
"""
Calculate the minimum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_min()
1
"""
def get_max(self):
"""
Calculate the maximum value in the data
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_max()
4
"""
def get_variance(self):
"""
Calculate variance, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_variance()
1.25
"""
def get_std_deviation(self):
"""
Calculate standard deviation, accurate to two digits after the Decimal separator
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_std_deviation()
1.12
"""
def get_correlation(self):
"""
Calculate correlation
:return:float
>>> ds2 = DataStatistics2([1, 2, 3, 4])
>>> ds2.get_correlation()
1.0
""" | def get_correlation(self):
return np.corrcoef(self.data, rowvar=False) | Calculate correlation |
ClassEval_31_sum | import math
class DataStatistics4:
"""
This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.
"""
@staticmethod
def correlation_coefficient(data1, data2):
n = len(data1)
mean1 = sum(data1) / n
mean2 = sum(data2) / n
numerator = sum((data1[i] - mean1) * (data2[i] - mean2) for i in range(n))
denominator = math.sqrt(sum((data1[i] - mean1) ** 2 for i in range(n))) * math.sqrt(sum((data2[i] - mean2) ** 2 for i in range(n)))
return numerator / denominator if denominator != 0 else 0
@staticmethod
def skewness(data):
"""
Calculate the skewness of a set of data.
:param data: The input data list, list.
:return: The skewness, float.
>>> DataStatistics4.skewness([1, 2, 5])
2.3760224064818463
"""
n = len(data)
mean = sum(data) / n
variance = sum((x - mean) ** 2 for x in data) / n
std_deviation = math.sqrt(variance)
skewness = sum((x - mean) ** 3 for x in data) * n / ((n - 1) * (n - 2) * std_deviation ** 3) if std_deviation != 0 else 0
return skewness
@staticmethod
def kurtosis(data):
"""
Calculate the kurtosis of a set of data.
:param data: The input data list, list.
:return: The kurtosis, float.
>>> DataStatistics4.kurtosis([1, 20,100])
-1.5000000000000007
"""
n = len(data)
mean = sum(data) / n
std_dev = math.sqrt(sum((x - mean) ** 2 for x in data) / n)
if std_dev == 0:
return math.nan
centered_data = [(x - mean) for x in data]
fourth_moment = sum(x ** 4 for x in centered_data) / n
kurtosis_value = (fourth_moment / std_dev ** 4) - 3
return kurtosis_value
@staticmethod
def pdf(data, mu, sigma):
"""
Calculate the probability density function (PDF) of a set of data under a normal distribution.
:param data: The input data list, list.
:param mu: The mean of the normal distribution, float.
:param sigma: The standard deviation of the normal distribution, float.
:return: The probability density function (PDF), list.
>>> DataStatistics4.pdf([1, 2, 3], 1, 1)
[0.3989422804014327, 0.24197072451914337, 0.05399096651318806]
"""
pdf_values = [1 / (sigma * math.sqrt(2 * math.pi)) * math.exp(-0.5 * ((x - mu) / sigma) ** 2) for x in data]
return pdf_values | import math
class DataStatistics4:
"""
This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.
"""
@staticmethod
@staticmethod
def skewness(data):
"""
Calculate the skewness of a set of data.
:param data: The input data list, list.
:return: The skewness, float.
>>> DataStatistics4.skewness([1, 2, 5])
2.3760224064818463
"""
@staticmethod
def kurtosis(data):
"""
Calculate the kurtosis of a set of data.
:param data: The input data list, list.
:return: The kurtosis, float.
>>> DataStatistics4.kurtosis([1, 20,100])
-1.5000000000000007
"""
@staticmethod
def pdf(data, mu, sigma):
"""
Calculate the probability density function (PDF) of a set of data under a normal distribution.
:param data: The input data list, list.
:param mu: The mean of the normal distribution, float.
:param sigma: The standard deviation of the normal distribution, float.
:return: The probability density function (PDF), list.
>>> DataStatistics4.pdf([1, 2, 3], 1, 1)
[0.3989422804014327, 0.24197072451914337, 0.05399096651318806]
""" | def correlation_coefficient(data1, data2):
n = len(data1)
mean1 = sum(data1) / n
mean2 = sum(data2) / n
numerator = sum((data1[i] - mean1) * (data2[i] - mean2) for i in range(n))
denominator = math.sqrt(sum((data1[i] - mean1) ** 2 for i in range(n))) * math.sqrt(sum((data2[i] - mean2) ** 2 for i in range(n)))
return numerator / denominator if denominator != 0 else 0 | Calculate the correlation coefficient of two sets of data. |
ClassEval_31_sum | import math
class DataStatistics4:
"""
This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.
"""
@staticmethod
def correlation_coefficient(data1, data2):
"""
Calculate the correlation coefficient of two sets of data.
:param data1: The first set of data,list.
:param data2: The second set of data,list.
:return: The correlation coefficient, float.
>>> DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6])
0.9999999999999998
"""
n = len(data1)
mean1 = sum(data1) / n
mean2 = sum(data2) / n
numerator = sum((data1[i] - mean1) * (data2[i] - mean2) for i in range(n))
denominator = math.sqrt(sum((data1[i] - mean1) ** 2 for i in range(n))) * math.sqrt(sum((data2[i] - mean2) ** 2 for i in range(n)))
return numerator / denominator if denominator != 0 else 0
@staticmethod
def skewness(data):
n = len(data)
mean = sum(data) / n
variance = sum((x - mean) ** 2 for x in data) / n
std_deviation = math.sqrt(variance)
skewness = sum((x - mean) ** 3 for x in data) * n / ((n - 1) * (n - 2) * std_deviation ** 3) if std_deviation != 0 else 0
return skewness
@staticmethod
def kurtosis(data):
"""
Calculate the kurtosis of a set of data.
:param data: The input data list, list.
:return: The kurtosis, float.
>>> DataStatistics4.kurtosis([1, 20,100])
-1.5000000000000007
"""
n = len(data)
mean = sum(data) / n
std_dev = math.sqrt(sum((x - mean) ** 2 for x in data) / n)
if std_dev == 0:
return math.nan
centered_data = [(x - mean) for x in data]
fourth_moment = sum(x ** 4 for x in centered_data) / n
kurtosis_value = (fourth_moment / std_dev ** 4) - 3
return kurtosis_value
@staticmethod
def pdf(data, mu, sigma):
"""
Calculate the probability density function (PDF) of a set of data under a normal distribution.
:param data: The input data list, list.
:param mu: The mean of the normal distribution, float.
:param sigma: The standard deviation of the normal distribution, float.
:return: The probability density function (PDF), list.
>>> DataStatistics4.pdf([1, 2, 3], 1, 1)
[0.3989422804014327, 0.24197072451914337, 0.05399096651318806]
"""
pdf_values = [1 / (sigma * math.sqrt(2 * math.pi)) * math.exp(-0.5 * ((x - mu) / sigma) ** 2) for x in data]
return pdf_values | import math
class DataStatistics4:
"""
This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.
"""
@staticmethod
def correlation_coefficient(data1, data2):
"""
Calculate the correlation coefficient of two sets of data.
:param data1: The first set of data,list.
:param data2: The second set of data,list.
:return: The correlation coefficient, float.
>>> DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6])
0.9999999999999998
"""
@staticmethod
def kurtosis(data):
"""
Calculate the kurtosis of a set of data.
:param data: The input data list, list.
:return: The kurtosis, float.
>>> DataStatistics4.kurtosis([1, 20,100])
-1.5000000000000007
"""
@staticmethod
def pdf(data, mu, sigma):
"""
Calculate the probability density function (PDF) of a set of data under a normal distribution.
:param data: The input data list, list.
:param mu: The mean of the normal distribution, float.
:param sigma: The standard deviation of the normal distribution, float.
:return: The probability density function (PDF), list.
>>> DataStatistics4.pdf([1, 2, 3], 1, 1)
[0.3989422804014327, 0.24197072451914337, 0.05399096651318806]
""" | @staticmethod
def skewness(data):
n = len(data)
mean = sum(data) / n
variance = sum((x - mean) ** 2 for x in data) / n
std_deviation = math.sqrt(variance)
skewness = sum((x - mean) ** 3 for x in data) * n / ((n - 1) * (n - 2) * std_deviation ** 3) if std_deviation != 0 else 0
return skewness | Calculate the skewness of a set of data. |
ClassEval_31_sum | import math
class DataStatistics4:
"""
This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.
"""
@staticmethod
def correlation_coefficient(data1, data2):
"""
Calculate the correlation coefficient of two sets of data.
:param data1: The first set of data,list.
:param data2: The second set of data,list.
:return: The correlation coefficient, float.
>>> DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6])
0.9999999999999998
"""
n = len(data1)
mean1 = sum(data1) / n
mean2 = sum(data2) / n
numerator = sum((data1[i] - mean1) * (data2[i] - mean2) for i in range(n))
denominator = math.sqrt(sum((data1[i] - mean1) ** 2 for i in range(n))) * math.sqrt(sum((data2[i] - mean2) ** 2 for i in range(n)))
return numerator / denominator if denominator != 0 else 0
@staticmethod
def skewness(data):
"""
Calculate the skewness of a set of data.
:param data: The input data list, list.
:return: The skewness, float.
>>> DataStatistics4.skewness([1, 2, 5])
2.3760224064818463
"""
n = len(data)
mean = sum(data) / n
variance = sum((x - mean) ** 2 for x in data) / n
std_deviation = math.sqrt(variance)
skewness = sum((x - mean) ** 3 for x in data) * n / ((n - 1) * (n - 2) * std_deviation ** 3) if std_deviation != 0 else 0
return skewness
@staticmethod
def kurtosis(data):
n = len(data)
mean = sum(data) / n
std_dev = math.sqrt(sum((x - mean) ** 2 for x in data) / n)
if std_dev == 0:
return math.nan
centered_data = [(x - mean) for x in data]
fourth_moment = sum(x ** 4 for x in centered_data) / n
kurtosis_value = (fourth_moment / std_dev ** 4) - 3
return kurtosis_value
@staticmethod
def pdf(data, mu, sigma):
"""
Calculate the probability density function (PDF) of a set of data under a normal distribution.
:param data: The input data list, list.
:param mu: The mean of the normal distribution, float.
:param sigma: The standard deviation of the normal distribution, float.
:return: The probability density function (PDF), list.
>>> DataStatistics4.pdf([1, 2, 3], 1, 1)
[0.3989422804014327, 0.24197072451914337, 0.05399096651318806]
"""
pdf_values = [1 / (sigma * math.sqrt(2 * math.pi)) * math.exp(-0.5 * ((x - mu) / sigma) ** 2) for x in data]
return pdf_values | import math
class DataStatistics4:
"""
This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.
"""
@staticmethod
def correlation_coefficient(data1, data2):
"""
Calculate the correlation coefficient of two sets of data.
:param data1: The first set of data,list.
:param data2: The second set of data,list.
:return: The correlation coefficient, float.
>>> DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6])
0.9999999999999998
"""
@staticmethod
def skewness(data):
"""
Calculate the skewness of a set of data.
:param data: The input data list, list.
:return: The skewness, float.
>>> DataStatistics4.skewness([1, 2, 5])
2.3760224064818463
"""
@staticmethod
def pdf(data, mu, sigma):
"""
Calculate the probability density function (PDF) of a set of data under a normal distribution.
:param data: The input data list, list.
:param mu: The mean of the normal distribution, float.
:param sigma: The standard deviation of the normal distribution, float.
:return: The probability density function (PDF), list.
>>> DataStatistics4.pdf([1, 2, 3], 1, 1)
[0.3989422804014327, 0.24197072451914337, 0.05399096651318806]
""" | @staticmethod
def kurtosis(data):
n = len(data)
mean = sum(data) / n
std_dev = math.sqrt(sum((x - mean) ** 2 for x in data) / n)
if std_dev == 0:
return math.nan
centered_data = [(x - mean) for x in data]
fourth_moment = sum(x ** 4 for x in centered_data) / n
kurtosis_value = (fourth_moment / std_dev ** 4) - 3
return kurtosis_value | Calculate the kurtosis of a set of data. |
ClassEval_31_sum | import math
class DataStatistics4:
"""
This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.
"""
@staticmethod
def correlation_coefficient(data1, data2):
"""
Calculate the correlation coefficient of two sets of data.
:param data1: The first set of data,list.
:param data2: The second set of data,list.
:return: The correlation coefficient, float.
>>> DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6])
0.9999999999999998
"""
n = len(data1)
mean1 = sum(data1) / n
mean2 = sum(data2) / n
numerator = sum((data1[i] - mean1) * (data2[i] - mean2) for i in range(n))
denominator = math.sqrt(sum((data1[i] - mean1) ** 2 for i in range(n))) * math.sqrt(sum((data2[i] - mean2) ** 2 for i in range(n)))
return numerator / denominator if denominator != 0 else 0
@staticmethod
def skewness(data):
"""
Calculate the skewness of a set of data.
:param data: The input data list, list.
:return: The skewness, float.
>>> DataStatistics4.skewness([1, 2, 5])
2.3760224064818463
"""
n = len(data)
mean = sum(data) / n
variance = sum((x - mean) ** 2 for x in data) / n
std_deviation = math.sqrt(variance)
skewness = sum((x - mean) ** 3 for x in data) * n / ((n - 1) * (n - 2) * std_deviation ** 3) if std_deviation != 0 else 0
return skewness
@staticmethod
def kurtosis(data):
"""
Calculate the kurtosis of a set of data.
:param data: The input data list, list.
:return: The kurtosis, float.
>>> DataStatistics4.kurtosis([1, 20,100])
-1.5000000000000007
"""
n = len(data)
mean = sum(data) / n
std_dev = math.sqrt(sum((x - mean) ** 2 for x in data) / n)
if std_dev == 0:
return math.nan
centered_data = [(x - mean) for x in data]
fourth_moment = sum(x ** 4 for x in centered_data) / n
kurtosis_value = (fourth_moment / std_dev ** 4) - 3
return kurtosis_value
@staticmethod
def pdf(data, mu, sigma):
pdf_values = [1 / (sigma * math.sqrt(2 * math.pi)) * math.exp(-0.5 * ((x - mu) / sigma) ** 2) for x in data]
return pdf_values | import math
class DataStatistics4:
"""
This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.
"""
@staticmethod
def correlation_coefficient(data1, data2):
"""
Calculate the correlation coefficient of two sets of data.
:param data1: The first set of data,list.
:param data2: The second set of data,list.
:return: The correlation coefficient, float.
>>> DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6])
0.9999999999999998
"""
@staticmethod
def skewness(data):
"""
Calculate the skewness of a set of data.
:param data: The input data list, list.
:return: The skewness, float.
>>> DataStatistics4.skewness([1, 2, 5])
2.3760224064818463
"""
@staticmethod
def kurtosis(data):
"""
Calculate the kurtosis of a set of data.
:param data: The input data list, list.
:return: The kurtosis, float.
>>> DataStatistics4.kurtosis([1, 20,100])
-1.5000000000000007
"""
@staticmethod
def pdf(data, mu, sigma):
"""
Calculate the probability density function (PDF) of a set of data under a normal distribution.
:param data: The input data list, list.
:param mu: The mean of the normal distribution, float.
:param sigma: The standard deviation of the normal distribution, float.
:return: The probability density function (PDF), list.
>>> DataStatistics4.pdf([1, 2, 3], 1, 1)
[0.3989422804014327, 0.24197072451914337, 0.05399096651318806]
""" | @staticmethod
def pdf(data, mu, sigma):
pdf_values = [1 / (sigma * math.sqrt(2 * math.pi)) * math.exp(-0.5 * ((x - mu) / sigma) ** 2) for x in data]
return pdf_values | Calculate the probability density function (PDF) of a set of data under a normal distribution. |
ClassEval_32_sum | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
self.key = key
def caesar_decipher(self, ciphertext, shift):
plaintext = ""
for char in ciphertext:
if char.isalpha():
if char.isupper():
ascii_offset = 65
else:
ascii_offset = 97
shifted_char = chr((ord(char) - ascii_offset - shift) % 26 + ascii_offset)
plaintext += shifted_char
else:
plaintext += char
return plaintext
def vigenere_decipher(self, ciphertext):
"""
Deciphers the given ciphertext using the Vigenere cipher
:param ciphertext: The ciphertext to decipher,str.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.vigenere_decipher('ifmmp')
'ybocl'
"""
decrypted_text = ""
key_index = 0
for char in ciphertext:
if char.isalpha():
shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')
decrypted_char = chr((ord(char.lower()) - ord('a') - shift) % 26 + ord('a'))
decrypted_text += decrypted_char.upper() if char.isupper() else decrypted_char
key_index += 1
else:
decrypted_text += char
return decrypted_text
def rail_fence_decipher(self, encrypted_text, rails):
"""
Deciphers the given ciphertext using the Rail Fence cipher
:param encrypted_text: The ciphertext to decipher,str.
:param rails: The number of rails to use for decryption,int.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.rail_fence_decipher('Hoo!el,Wrdl l', 3)
'Hello, World!'
"""
fence = [['\n' for _ in range(len(encrypted_text))] for _ in range(rails)]
direction = -1
row, col = 0, 0
for _ in range(len(encrypted_text)):
if row == 0 or row == rails - 1:
direction = -direction
fence[row][col] = ''
col += 1
row += direction
index = 0
for i in range(rails):
for j in range(len(encrypted_text)):
if fence[i][j] == '':
fence[i][j] = encrypted_text[index]
index += 1
plain_text = ''
direction = -1
row, col = 0, 0
for _ in range(len(encrypted_text)):
if row == 0 or row == rails - 1:
direction = -direction
plain_text += fence[row][col]
col += 1
row += direction
return plain_text | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the decryption utility with a key.
:param key: The key to use for decryption,str.
"""
self.key = key
def vigenere_decipher(self, ciphertext):
"""
Deciphers the given ciphertext using the Vigenere cipher
:param ciphertext: The ciphertext to decipher,str.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.vigenere_decipher('ifmmp')
'ybocl'
"""
def rail_fence_decipher(self, encrypted_text, rails):
"""
Deciphers the given ciphertext using the Rail Fence cipher
:param encrypted_text: The ciphertext to decipher,str.
:param rails: The number of rails to use for decryption,int.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.rail_fence_decipher('Hoo!el,Wrdl l', 3)
'Hello, World!'
""" | def caesar_decipher(self, ciphertext, shift):
plaintext = ""
for char in ciphertext:
if char.isalpha():
if char.isupper():
ascii_offset = 65
else:
ascii_offset = 97
shifted_char = chr((ord(char) - ascii_offset - shift) % 26 + ascii_offset)
plaintext += shifted_char
else:
plaintext += char
return plaintext | Deciphers the given ciphertext using the Caesar cipher |
ClassEval_32_sum | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
self.key = key
def caesar_decipher(self, ciphertext, shift):
"""
Deciphers the given ciphertext using the Caesar cipher
:param ciphertext: The ciphertext to decipher,str.
:param shift: The shift to use for decryption,int.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.caesar_decipher('ifmmp', 1)
'hello'
"""
plaintext = ""
for char in ciphertext:
if char.isalpha():
if char.isupper():
ascii_offset = 65
else:
ascii_offset = 97
shifted_char = chr((ord(char) - ascii_offset - shift) % 26 + ascii_offset)
plaintext += shifted_char
else:
plaintext += char
return plaintext
def vigenere_decipher(self, ciphertext):
decrypted_text = ""
key_index = 0
for char in ciphertext:
if char.isalpha():
shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')
decrypted_char = chr((ord(char.lower()) - ord('a') - shift) % 26 + ord('a'))
decrypted_text += decrypted_char.upper() if char.isupper() else decrypted_char
key_index += 1
else:
decrypted_text += char
return decrypted_text
def rail_fence_decipher(self, encrypted_text, rails):
"""
Deciphers the given ciphertext using the Rail Fence cipher
:param encrypted_text: The ciphertext to decipher,str.
:param rails: The number of rails to use for decryption,int.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.rail_fence_decipher('Hoo!el,Wrdl l', 3)
'Hello, World!'
"""
fence = [['\n' for _ in range(len(encrypted_text))] for _ in range(rails)]
direction = -1
row, col = 0, 0
for _ in range(len(encrypted_text)):
if row == 0 or row == rails - 1:
direction = -direction
fence[row][col] = ''
col += 1
row += direction
index = 0
for i in range(rails):
for j in range(len(encrypted_text)):
if fence[i][j] == '':
fence[i][j] = encrypted_text[index]
index += 1
plain_text = ''
direction = -1
row, col = 0, 0
for _ in range(len(encrypted_text)):
if row == 0 or row == rails - 1:
direction = -direction
plain_text += fence[row][col]
col += 1
row += direction
return plain_text | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the decryption utility with a key.
:param key: The key to use for decryption,str.
"""
self.key = key
def caesar_decipher(self, ciphertext, shift):
"""
Deciphers the given ciphertext using the Caesar cipher
:param ciphertext: The ciphertext to decipher,str.
:param shift: The shift to use for decryption,int.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.caesar_decipher('ifmmp', 1)
'hello'
"""
def rail_fence_decipher(self, encrypted_text, rails):
"""
Deciphers the given ciphertext using the Rail Fence cipher
:param encrypted_text: The ciphertext to decipher,str.
:param rails: The number of rails to use for decryption,int.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.rail_fence_decipher('Hoo!el,Wrdl l', 3)
'Hello, World!'
""" | def vigenere_decipher(self, ciphertext):
decrypted_text = ""
key_index = 0
for char in ciphertext:
if char.isalpha():
shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')
decrypted_char = chr((ord(char.lower()) - ord('a') - shift) % 26 + ord('a'))
decrypted_text += decrypted_char.upper() if char.isupper() else decrypted_char
key_index += 1
else:
decrypted_text += char
return decrypted_text | Deciphers the given ciphertext using the Vigenere cipher |
ClassEval_32_sum | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
self.key = key
def caesar_decipher(self, ciphertext, shift):
"""
Deciphers the given ciphertext using the Caesar cipher
:param ciphertext: The ciphertext to decipher,str.
:param shift: The shift to use for decryption,int.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.caesar_decipher('ifmmp', 1)
'hello'
"""
plaintext = ""
for char in ciphertext:
if char.isalpha():
if char.isupper():
ascii_offset = 65
else:
ascii_offset = 97
shifted_char = chr((ord(char) - ascii_offset - shift) % 26 + ascii_offset)
plaintext += shifted_char
else:
plaintext += char
return plaintext
def vigenere_decipher(self, ciphertext):
"""
Deciphers the given ciphertext using the Vigenere cipher
:param ciphertext: The ciphertext to decipher,str.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.vigenere_decipher('ifmmp')
'ybocl'
"""
decrypted_text = ""
key_index = 0
for char in ciphertext:
if char.isalpha():
shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')
decrypted_char = chr((ord(char.lower()) - ord('a') - shift) % 26 + ord('a'))
decrypted_text += decrypted_char.upper() if char.isupper() else decrypted_char
key_index += 1
else:
decrypted_text += char
return decrypted_text
def rail_fence_decipher(self, encrypted_text, rails):
fence = [['\n' for _ in range(len(encrypted_text))] for _ in range(rails)]
direction = -1
row, col = 0, 0
for _ in range(len(encrypted_text)):
if row == 0 or row == rails - 1:
direction = -direction
fence[row][col] = ''
col += 1
row += direction
index = 0
for i in range(rails):
for j in range(len(encrypted_text)):
if fence[i][j] == '':
fence[i][j] = encrypted_text[index]
index += 1
plain_text = ''
direction = -1
row, col = 0, 0
for _ in range(len(encrypted_text)):
if row == 0 or row == rails - 1:
direction = -direction
plain_text += fence[row][col]
col += 1
row += direction
return plain_text | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the decryption utility with a key.
:param key: The key to use for decryption,str.
"""
self.key = key
def caesar_decipher(self, ciphertext, shift):
"""
Deciphers the given ciphertext using the Caesar cipher
:param ciphertext: The ciphertext to decipher,str.
:param shift: The shift to use for decryption,int.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.caesar_decipher('ifmmp', 1)
'hello'
"""
def vigenere_decipher(self, ciphertext):
"""
Deciphers the given ciphertext using the Vigenere cipher
:param ciphertext: The ciphertext to decipher,str.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.vigenere_decipher('ifmmp')
'ybocl'
"""
def rail_fence_decipher(self, encrypted_text, rails):
"""
Deciphers the given ciphertext using the Rail Fence cipher
:param encrypted_text: The ciphertext to decipher,str.
:param rails: The number of rails to use for decryption,int.
:return: The deciphered plaintext,str.
>>> d = DecryptionUtils('key')
>>> d.rail_fence_decipher('Hoo!el,Wrdl l', 3)
'Hello, World!'
""" | def rail_fence_decipher(self, encrypted_text, rails):
fence = [['\n' for _ in range(len(encrypted_text))] for _ in range(rails)]
direction = -1
row, col = 0, 0
for _ in range(len(encrypted_text)):
if row == 0 or row == rails - 1:
direction = -direction
fence[row][col] = ''
col += 1
row += direction
index = 0
for i in range(rails):
for j in range(len(encrypted_text)):
if fence[i][j] == '':
fence[i][j] = encrypted_text[index]
index += 1
plain_text = ''
direction = -1
row, col = 0, 0
for _ in range(len(encrypted_text)):
if row == 0 or row == rails - 1:
direction = -direction
plain_text += fence[row][col]
col += 1
row += direction
return plain_text | Deciphers the given ciphertext using the Rail Fence cipher |
ClassEval_33_sum | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = cart
self.promotion = promotion
self.__total = self.total()
def due(self):
"""
Calculate the final amount to be paid after applying the discount.
:return: float, final amount to be paid
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> ds.due()
312.55
"""
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.__total - discount
@staticmethod
def FidelityPromo(order):
"""
Calculate the discount based on the fidelity points of the customer.Customers with over 1000 points can enjoy a 5% discount on the entire order.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> DiscountStrategy.FidelityPromo(order)
16.45
"""
return order.total() * 0.05 if order.customer['fidelity'] >= 1000 else 0
@staticmethod
def BulkItemPromo(order):
"""
Calculate the discount based on bulk item quantity in the order.In the same order, if the quantity of a single item reaches 20 or more, each item will enjoy a 10% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 20, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
>>> DiscountStrategy.BulkItemPromo(order)
47.0
"""
discount = 0
for item in order.cart:
if item['quantity'] >= 20:
discount += item['quantity'] * item['price'] * 0.1
return discount
@staticmethod
def LargeOrderPromo(order):
"""
Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
>>> DiscountStrategy.LargeOrderPromo(order)
0.0
"""
return order.total() * 0.07 if len({item['product'] for item in order.cart}) >= 10 else 0 | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, and an optional promotion.
:param customer: dict, customer information
:param cart: list of dicts, a cart of items with details
:param promotion: function, optional promotion applied to the order
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
"""
self.customer = customer
self.cart = cart
self.promotion = promotion
self.total()
def due(self):
"""
Calculate the final amount to be paid after applying the discount.
:return: float, final amount to be paid
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> ds.due()
312.55
"""
@staticmethod
def FidelityPromo(order):
"""
Calculate the discount based on the fidelity points of the customer.Customers with over 1000 points can enjoy a 5% discount on the entire order.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> DiscountStrategy.FidelityPromo(order)
16.45
"""
@staticmethod
def BulkItemPromo(order):
"""
Calculate the discount based on bulk item quantity in the order.In the same order, if the quantity of a single item reaches 20 or more, each item will enjoy a 10% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 20, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
>>> DiscountStrategy.BulkItemPromo(order)
47.0
"""
@staticmethod
def LargeOrderPromo(order):
"""
Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
>>> DiscountStrategy.LargeOrderPromo(order)
0.0
""" | def total(self):
self.__total = sum(item['quantity'] * item['price'] for item in self.cart)
return self.__total | Calculate the total cost of items in the cart. |
ClassEval_33_sum | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = cart
self.promotion = promotion
self.__total = self.total()
def total(self):
"""
Calculate the total cost of items in the cart.
:return: float, total cost of items
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart)
>>> ds.total()
329.0
"""
self.__total = sum(item['quantity'] * item['price'] for item in self.cart)
return self.__total
@staticmethod
def FidelityPromo(order):
"""
Calculate the discount based on the fidelity points of the customer.Customers with over 1000 points can enjoy a 5% discount on the entire order.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> DiscountStrategy.FidelityPromo(order)
16.45
"""
return order.total() * 0.05 if order.customer['fidelity'] >= 1000 else 0
@staticmethod
def BulkItemPromo(order):
"""
Calculate the discount based on bulk item quantity in the order.In the same order, if the quantity of a single item reaches 20 or more, each item will enjoy a 10% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 20, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
>>> DiscountStrategy.BulkItemPromo(order)
47.0
"""
discount = 0
for item in order.cart:
if item['quantity'] >= 20:
discount += item['quantity'] * item['price'] * 0.1
return discount
@staticmethod
def LargeOrderPromo(order):
"""
Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
>>> DiscountStrategy.LargeOrderPromo(order)
0.0
"""
return order.total() * 0.07 if len({item['product'] for item in order.cart}) >= 10 else 0 | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, and an optional promotion.
:param customer: dict, customer information
:param cart: list of dicts, a cart of items with details
:param promotion: function, optional promotion applied to the order
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
"""
self.customer = customer
self.cart = cart
self.promotion = promotion
self.total()
def total(self):
"""
Calculate the total cost of items in the cart.
:return: float, total cost of items
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart)
>>> ds.total()
329.0
"""
@staticmethod
def FidelityPromo(order):
"""
Calculate the discount based on the fidelity points of the customer.Customers with over 1000 points can enjoy a 5% discount on the entire order.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> DiscountStrategy.FidelityPromo(order)
16.45
"""
@staticmethod
def BulkItemPromo(order):
"""
Calculate the discount based on bulk item quantity in the order.In the same order, if the quantity of a single item reaches 20 or more, each item will enjoy a 10% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 20, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
>>> DiscountStrategy.BulkItemPromo(order)
47.0
"""
@staticmethod
def LargeOrderPromo(order):
"""
Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
>>> DiscountStrategy.LargeOrderPromo(order)
0.0
""" | def due(self):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.__total - discount | Calculate the final amount to be paid after applying the discount. |
ClassEval_33_sum | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = cart
self.promotion = promotion
self.__total = self.total()
def total(self):
"""
Calculate the total cost of items in the cart.
:return: float, total cost of items
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart)
>>> ds.total()
329.0
"""
self.__total = sum(item['quantity'] * item['price'] for item in self.cart)
return self.__total
def due(self):
"""
Calculate the final amount to be paid after applying the discount.
:return: float, final amount to be paid
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> ds.due()
312.55
"""
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.__total - discount
@staticmethod
def BulkItemPromo(order):
"""
Calculate the discount based on bulk item quantity in the order.In the same order, if the quantity of a single item reaches 20 or more, each item will enjoy a 10% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 20, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
>>> DiscountStrategy.BulkItemPromo(order)
47.0
"""
discount = 0
for item in order.cart:
if item['quantity'] >= 20:
discount += item['quantity'] * item['price'] * 0.1
return discount
@staticmethod
def LargeOrderPromo(order):
"""
Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
>>> DiscountStrategy.LargeOrderPromo(order)
0.0
"""
return order.total() * 0.07 if len({item['product'] for item in order.cart}) >= 10 else 0 | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, and an optional promotion.
:param customer: dict, customer information
:param cart: list of dicts, a cart of items with details
:param promotion: function, optional promotion applied to the order
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
"""
self.customer = customer
self.cart = cart
self.promotion = promotion
self.total()
def total(self):
"""
Calculate the total cost of items in the cart.
:return: float, total cost of items
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart)
>>> ds.total()
329.0
"""
def due(self):
"""
Calculate the final amount to be paid after applying the discount.
:return: float, final amount to be paid
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> ds.due()
312.55
"""
@staticmethod
def BulkItemPromo(order):
"""
Calculate the discount based on bulk item quantity in the order.In the same order, if the quantity of a single item reaches 20 or more, each item will enjoy a 10% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 20, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
>>> DiscountStrategy.BulkItemPromo(order)
47.0
"""
@staticmethod
def LargeOrderPromo(order):
"""
Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
>>> DiscountStrategy.LargeOrderPromo(order)
0.0
""" | @staticmethod
def FidelityPromo(order):
return order.total() * 0.05 if order.customer['fidelity'] >= 1000 else 0 | Calculate the discount based on the fidelity points of the customer.Customers with over 1000 points can enjoy a 5% discount on the entire order. |
ClassEval_33_sum | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = cart
self.promotion = promotion
self.__total = self.total()
def total(self):
"""
Calculate the total cost of items in the cart.
:return: float, total cost of items
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart)
>>> ds.total()
329.0
"""
self.__total = sum(item['quantity'] * item['price'] for item in self.cart)
return self.__total
def due(self):
"""
Calculate the final amount to be paid after applying the discount.
:return: float, final amount to be paid
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> ds.due()
312.55
"""
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.__total - discount
@staticmethod
def FidelityPromo(order):
"""
Calculate the discount based on the fidelity points of the customer.Customers with over 1000 points can enjoy a 5% discount on the entire order.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> DiscountStrategy.FidelityPromo(order)
16.45
"""
return order.total() * 0.05 if order.customer['fidelity'] >= 1000 else 0
@staticmethod
def LargeOrderPromo(order):
"""
Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
>>> DiscountStrategy.LargeOrderPromo(order)
0.0
"""
return order.total() * 0.07 if len({item['product'] for item in order.cart}) >= 10 else 0 | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, and an optional promotion.
:param customer: dict, customer information
:param cart: list of dicts, a cart of items with details
:param promotion: function, optional promotion applied to the order
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
"""
self.customer = customer
self.cart = cart
self.promotion = promotion
self.total()
def total(self):
"""
Calculate the total cost of items in the cart.
:return: float, total cost of items
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart)
>>> ds.total()
329.0
"""
def due(self):
"""
Calculate the final amount to be paid after applying the discount.
:return: float, final amount to be paid
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> ds.due()
312.55
"""
@staticmethod
def FidelityPromo(order):
"""
Calculate the discount based on the fidelity points of the customer.Customers with over 1000 points can enjoy a 5% discount on the entire order.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> DiscountStrategy.FidelityPromo(order)
16.45
"""
@staticmethod
def LargeOrderPromo(order):
"""
Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
>>> DiscountStrategy.LargeOrderPromo(order)
0.0
""" | @staticmethod
def BulkItemPromo(order):
discount = 0
for item in order.cart:
if item['quantity'] >= 20:
discount += item['quantity'] * item['price'] * 0.1
return discount | Calculate the discount based on bulk item quantity in the order.In the same order, if the quantity of a single item reaches 20 or more, each item will enjoy a 10% discount. |
ClassEval_33_sum | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = cart
self.promotion = promotion
self.__total = self.total()
def total(self):
"""
Calculate the total cost of items in the cart.
:return: float, total cost of items
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart)
>>> ds.total()
329.0
"""
self.__total = sum(item['quantity'] * item['price'] for item in self.cart)
return self.__total
def due(self):
"""
Calculate the final amount to be paid after applying the discount.
:return: float, final amount to be paid
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> ds.due()
312.55
"""
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.__total - discount
@staticmethod
def FidelityPromo(order):
"""
Calculate the discount based on the fidelity points of the customer.Customers with over 1000 points can enjoy a 5% discount on the entire order.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> DiscountStrategy.FidelityPromo(order)
16.45
"""
return order.total() * 0.05 if order.customer['fidelity'] >= 1000 else 0
@staticmethod
def BulkItemPromo(order):
"""
Calculate the discount based on bulk item quantity in the order.In the same order, if the quantity of a single item reaches 20 or more, each item will enjoy a 10% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 20, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
>>> DiscountStrategy.BulkItemPromo(order)
47.0
"""
discount = 0
for item in order.cart:
if item['quantity'] >= 20:
discount += item['quantity'] * item['price'] * 0.1
return discount
@staticmethod
def LargeOrderPromo(order):
return order.total() * 0.07 if len({item['product'] for item in order.cart}) >= 10 else 0 | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, and an optional promotion.
:param customer: dict, customer information
:param cart: list of dicts, a cart of items with details
:param promotion: function, optional promotion applied to the order
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
"""
self.customer = customer
self.cart = cart
self.promotion = promotion
self.total()
def total(self):
"""
Calculate the total cost of items in the cart.
:return: float, total cost of items
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart)
>>> ds.total()
329.0
"""
def due(self):
"""
Calculate the final amount to be paid after applying the discount.
:return: float, final amount to be paid
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> ds = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> ds.due()
312.55
"""
@staticmethod
def FidelityPromo(order):
"""
Calculate the discount based on the fidelity points of the customer.Customers with over 1000 points can enjoy a 5% discount on the entire order.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)
>>> DiscountStrategy.FidelityPromo(order)
16.45
"""
@staticmethod
def BulkItemPromo(order):
"""
Calculate the discount based on bulk item quantity in the order.In the same order, if the quantity of a single item reaches 20 or more, each item will enjoy a 10% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 20, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)
>>> DiscountStrategy.BulkItemPromo(order)
47.0
"""
@staticmethod
def LargeOrderPromo(order):
"""
Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount.
:param order: object, the order to apply the discount to
:return: float, discount amount
>>> customer = {'name': 'John Doe', 'fidelity': 1200}
>>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]
>>> order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)
>>> DiscountStrategy.LargeOrderPromo(order)
0.0
""" | @staticmethod
def LargeOrderPromo(order):
return order.total() * 0.07 if len({item['product'] for item in order.cart}) >= 10 else 0 | Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount. |
ClassEval_34_sum | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path):
self.file_path = file_path
def write_text(self, content, font_size=12, alignment='left'):
"""
Writes the specified content to a Word document.
:param content: str, the text content to write.
:param font_size: int, optional, the font size of the text (default is 12).
:param alignment: str, optional, the alignment of the text ('left', 'center', or 'right'; default is 'left').
:return: bool, True if the write operation is successful, False otherwise.
"""
try:
doc = Document()
paragraph = doc.add_paragraph()
run = paragraph.add_run(content)
font = run.font
font.size = Pt(font_size)
alignment_value = self._get_alignment_value(alignment)
paragraph.alignment = alignment_value
doc.save(self.file_path)
return True
except:
return False
def add_heading(self, heading, level=1):
"""
Adds a heading to the Word document.
:param heading: str, the text of the heading.
:param level: int, optional, the level of the heading (1, 2, 3, etc.; default is 1).
:return: bool, True if the heading is successfully added, False otherwise.
"""
try:
doc = Document(self.file_path)
doc.add_heading(heading, level)
doc.save(self.file_path)
return True
except:
return False
def add_table(self, data):
"""
Adds a table to the Word document with the specified data.
:param data: list of lists, the data to populate the table.
:return: bool, True if the table is successfully added, False otherwise.
"""
try:
doc = Document(self.file_path)
table = doc.add_table(rows=len(data), cols=len(data[0]))
for i, row in enumerate(data):
for j, cell_value in enumerate(row):
table.cell(i, j).text = str(cell_value)
doc.save(self.file_path)
return True
except:
return False
def _get_alignment_value(self, alignment):
"""
Returns the alignment value corresponding to the given alignment string.
:param alignment: str, the alignment string ('left', 'center', or 'right').
:return: int, the alignment value.
"""
alignment_options = {
'left': WD_PARAGRAPH_ALIGNMENT.LEFT,
'center': WD_PARAGRAPH_ALIGNMENT.CENTER,
'right': WD_PARAGRAPH_ALIGNMENT.RIGHT
}
return alignment_options.get(alignment.lower(), WD_PARAGRAPH_ALIGNMENT.LEFT) | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path):
"""
Initializes the DocFileHandler object with the specified file path.
:param file_path: str, the path to the Word document file.
"""
self.file_path = file_path
def write_text(self, content, font_size=12, alignment='left'):
"""
Writes the specified content to a Word document.
:param content: str, the text content to write.
:param font_size: int, optional, the font size of the text (default is 12).
:param alignment: str, optional, the alignment of the text ('left', 'center', or 'right'; default is 'left').
:return: bool, True if the write operation is successful, False otherwise.
"""
def add_heading(self, heading, level=1):
"""
Adds a heading to the Word document.
:param heading: str, the text of the heading.
:param level: int, optional, the level of the heading (1, 2, 3, etc.; default is 1).
:return: bool, True if the heading is successfully added, False otherwise.
"""
def add_table(self, data):
"""
Adds a table to the Word document with the specified data.
:param data: list of lists, the data to populate the table.
:return: bool, True if the table is successfully added, False otherwise.
"""
def _get_alignment_value(self, alignment):
"""
Returns the alignment value corresponding to the given alignment string.
:param alignment: str, the alignment string ('left', 'center', or 'right').
:return: int, the alignment value.
""" | def read_text(self):
doc = Document(self.file_path)
text = []
for paragraph in doc.paragraphs:
text.append(paragraph.text)
return "\n".join(text) | Reads the content of a Word document and returns it as a string. |
ClassEval_34_sum | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path):
self.file_path = file_path
def read_text(self):
"""
Reads the content of a Word document and returns it as a string.
:return: str, the content of the Word document.
"""
doc = Document(self.file_path)
text = []
for paragraph in doc.paragraphs:
text.append(paragraph.text)
return "\n".join(text)
def add_heading(self, heading, level=1):
"""
Adds a heading to the Word document.
:param heading: str, the text of the heading.
:param level: int, optional, the level of the heading (1, 2, 3, etc.; default is 1).
:return: bool, True if the heading is successfully added, False otherwise.
"""
try:
doc = Document(self.file_path)
doc.add_heading(heading, level)
doc.save(self.file_path)
return True
except:
return False
def add_table(self, data):
"""
Adds a table to the Word document with the specified data.
:param data: list of lists, the data to populate the table.
:return: bool, True if the table is successfully added, False otherwise.
"""
try:
doc = Document(self.file_path)
table = doc.add_table(rows=len(data), cols=len(data[0]))
for i, row in enumerate(data):
for j, cell_value in enumerate(row):
table.cell(i, j).text = str(cell_value)
doc.save(self.file_path)
return True
except:
return False
def _get_alignment_value(self, alignment):
"""
Returns the alignment value corresponding to the given alignment string.
:param alignment: str, the alignment string ('left', 'center', or 'right').
:return: int, the alignment value.
"""
alignment_options = {
'left': WD_PARAGRAPH_ALIGNMENT.LEFT,
'center': WD_PARAGRAPH_ALIGNMENT.CENTER,
'right': WD_PARAGRAPH_ALIGNMENT.RIGHT
}
return alignment_options.get(alignment.lower(), WD_PARAGRAPH_ALIGNMENT.LEFT) | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path):
"""
Initializes the DocFileHandler object with the specified file path.
:param file_path: str, the path to the Word document file.
"""
self.file_path = file_path
def read_text(self):
"""
Reads the content of a Word document and returns it as a string.
:return: str, the content of the Word document.
"""
def add_heading(self, heading, level=1):
"""
Adds a heading to the Word document.
:param heading: str, the text of the heading.
:param level: int, optional, the level of the heading (1, 2, 3, etc.; default is 1).
:return: bool, True if the heading is successfully added, False otherwise.
"""
def add_table(self, data):
"""
Adds a table to the Word document with the specified data.
:param data: list of lists, the data to populate the table.
:return: bool, True if the table is successfully added, False otherwise.
"""
def _get_alignment_value(self, alignment):
"""
Returns the alignment value corresponding to the given alignment string.
:param alignment: str, the alignment string ('left', 'center', or 'right').
:return: int, the alignment value.
""" | def write_text(self, content, font_size=12, alignment='left'):
try:
doc = Document()
paragraph = doc.add_paragraph()
run = paragraph.add_run(content)
font = run.font
font.size = Pt(font_size)
alignment_value = self._get_alignment_value(alignment)
paragraph.alignment = alignment_value
doc.save(self.file_path)
return True
except:
return False | Writes the specified content to a Word document. |
ClassEval_34_sum | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path):
self.file_path = file_path
def read_text(self):
"""
Reads the content of a Word document and returns it as a string.
:return: str, the content of the Word document.
"""
doc = Document(self.file_path)
text = []
for paragraph in doc.paragraphs:
text.append(paragraph.text)
return "\n".join(text)
def write_text(self, content, font_size=12, alignment='left'):
"""
Writes the specified content to a Word document.
:param content: str, the text content to write.
:param font_size: int, optional, the font size of the text (default is 12).
:param alignment: str, optional, the alignment of the text ('left', 'center', or 'right'; default is 'left').
:return: bool, True if the write operation is successful, False otherwise.
"""
try:
doc = Document()
paragraph = doc.add_paragraph()
run = paragraph.add_run(content)
font = run.font
font.size = Pt(font_size)
alignment_value = self._get_alignment_value(alignment)
paragraph.alignment = alignment_value
doc.save(self.file_path)
return True
except:
return False
def add_table(self, data):
"""
Adds a table to the Word document with the specified data.
:param data: list of lists, the data to populate the table.
:return: bool, True if the table is successfully added, False otherwise.
"""
try:
doc = Document(self.file_path)
table = doc.add_table(rows=len(data), cols=len(data[0]))
for i, row in enumerate(data):
for j, cell_value in enumerate(row):
table.cell(i, j).text = str(cell_value)
doc.save(self.file_path)
return True
except:
return False
def _get_alignment_value(self, alignment):
"""
Returns the alignment value corresponding to the given alignment string.
:param alignment: str, the alignment string ('left', 'center', or 'right').
:return: int, the alignment value.
"""
alignment_options = {
'left': WD_PARAGRAPH_ALIGNMENT.LEFT,
'center': WD_PARAGRAPH_ALIGNMENT.CENTER,
'right': WD_PARAGRAPH_ALIGNMENT.RIGHT
}
return alignment_options.get(alignment.lower(), WD_PARAGRAPH_ALIGNMENT.LEFT) | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path):
"""
Initializes the DocFileHandler object with the specified file path.
:param file_path: str, the path to the Word document file.
"""
self.file_path = file_path
def read_text(self):
"""
Reads the content of a Word document and returns it as a string.
:return: str, the content of the Word document.
"""
def write_text(self, content, font_size=12, alignment='left'):
"""
Writes the specified content to a Word document.
:param content: str, the text content to write.
:param font_size: int, optional, the font size of the text (default is 12).
:param alignment: str, optional, the alignment of the text ('left', 'center', or 'right'; default is 'left').
:return: bool, True if the write operation is successful, False otherwise.
"""
def add_table(self, data):
"""
Adds a table to the Word document with the specified data.
:param data: list of lists, the data to populate the table.
:return: bool, True if the table is successfully added, False otherwise.
"""
def _get_alignment_value(self, alignment):
"""
Returns the alignment value corresponding to the given alignment string.
:param alignment: str, the alignment string ('left', 'center', or 'right').
:return: int, the alignment value.
""" | def add_heading(self, heading, level=1):
try:
doc = Document(self.file_path)
doc.add_heading(heading, level)
doc.save(self.file_path)
return True
except:
return False | Adds a heading to the Word document. |
ClassEval_34_sum | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path):
self.file_path = file_path
def read_text(self):
"""
Reads the content of a Word document and returns it as a string.
:return: str, the content of the Word document.
"""
doc = Document(self.file_path)
text = []
for paragraph in doc.paragraphs:
text.append(paragraph.text)
return "\n".join(text)
def write_text(self, content, font_size=12, alignment='left'):
"""
Writes the specified content to a Word document.
:param content: str, the text content to write.
:param font_size: int, optional, the font size of the text (default is 12).
:param alignment: str, optional, the alignment of the text ('left', 'center', or 'right'; default is 'left').
:return: bool, True if the write operation is successful, False otherwise.
"""
try:
doc = Document()
paragraph = doc.add_paragraph()
run = paragraph.add_run(content)
font = run.font
font.size = Pt(font_size)
alignment_value = self._get_alignment_value(alignment)
paragraph.alignment = alignment_value
doc.save(self.file_path)
return True
except:
return False
def add_heading(self, heading, level=1):
"""
Adds a heading to the Word document.
:param heading: str, the text of the heading.
:param level: int, optional, the level of the heading (1, 2, 3, etc.; default is 1).
:return: bool, True if the heading is successfully added, False otherwise.
"""
try:
doc = Document(self.file_path)
doc.add_heading(heading, level)
doc.save(self.file_path)
return True
except:
return False
def _get_alignment_value(self, alignment):
"""
Returns the alignment value corresponding to the given alignment string.
:param alignment: str, the alignment string ('left', 'center', or 'right').
:return: int, the alignment value.
"""
alignment_options = {
'left': WD_PARAGRAPH_ALIGNMENT.LEFT,
'center': WD_PARAGRAPH_ALIGNMENT.CENTER,
'right': WD_PARAGRAPH_ALIGNMENT.RIGHT
}
return alignment_options.get(alignment.lower(), WD_PARAGRAPH_ALIGNMENT.LEFT) | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path):
"""
Initializes the DocFileHandler object with the specified file path.
:param file_path: str, the path to the Word document file.
"""
self.file_path = file_path
def read_text(self):
"""
Reads the content of a Word document and returns it as a string.
:return: str, the content of the Word document.
"""
def write_text(self, content, font_size=12, alignment='left'):
"""
Writes the specified content to a Word document.
:param content: str, the text content to write.
:param font_size: int, optional, the font size of the text (default is 12).
:param alignment: str, optional, the alignment of the text ('left', 'center', or 'right'; default is 'left').
:return: bool, True if the write operation is successful, False otherwise.
"""
def add_heading(self, heading, level=1):
"""
Adds a heading to the Word document.
:param heading: str, the text of the heading.
:param level: int, optional, the level of the heading (1, 2, 3, etc.; default is 1).
:return: bool, True if the heading is successfully added, False otherwise.
"""
def _get_alignment_value(self, alignment):
"""
Returns the alignment value corresponding to the given alignment string.
:param alignment: str, the alignment string ('left', 'center', or 'right').
:return: int, the alignment value.
""" | def add_table(self, data):
try:
doc = Document(self.file_path)
table = doc.add_table(rows=len(data), cols=len(data[0]))
for i, row in enumerate(data):
for j, cell_value in enumerate(row):
table.cell(i, j).text = str(cell_value)
doc.save(self.file_path)
return True
except:
return False | Adds a table to the Word document with the specified data. |
ClassEval_34_sum | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path):
self.file_path = file_path
def read_text(self):
"""
Reads the content of a Word document and returns it as a string.
:return: str, the content of the Word document.
"""
doc = Document(self.file_path)
text = []
for paragraph in doc.paragraphs:
text.append(paragraph.text)
return "\n".join(text)
def write_text(self, content, font_size=12, alignment='left'):
"""
Writes the specified content to a Word document.
:param content: str, the text content to write.
:param font_size: int, optional, the font size of the text (default is 12).
:param alignment: str, optional, the alignment of the text ('left', 'center', or 'right'; default is 'left').
:return: bool, True if the write operation is successful, False otherwise.
"""
try:
doc = Document()
paragraph = doc.add_paragraph()
run = paragraph.add_run(content)
font = run.font
font.size = Pt(font_size)
alignment_value = self._get_alignment_value(alignment)
paragraph.alignment = alignment_value
doc.save(self.file_path)
return True
except:
return False
def add_heading(self, heading, level=1):
"""
Adds a heading to the Word document.
:param heading: str, the text of the heading.
:param level: int, optional, the level of the heading (1, 2, 3, etc.; default is 1).
:return: bool, True if the heading is successfully added, False otherwise.
"""
try:
doc = Document(self.file_path)
doc.add_heading(heading, level)
doc.save(self.file_path)
return True
except:
return False
def add_table(self, data):
"""
Adds a table to the Word document with the specified data.
:param data: list of lists, the data to populate the table.
:return: bool, True if the table is successfully added, False otherwise.
"""
try:
doc = Document(self.file_path)
table = doc.add_table(rows=len(data), cols=len(data[0]))
for i, row in enumerate(data):
for j, cell_value in enumerate(row):
table.cell(i, j).text = str(cell_value)
doc.save(self.file_path)
return True
except:
return False
def _get_alignment_value(self, alignment):
alignment_options = {
'left': WD_PARAGRAPH_ALIGNMENT.LEFT,
'center': WD_PARAGRAPH_ALIGNMENT.CENTER,
'right': WD_PARAGRAPH_ALIGNMENT.RIGHT
}
return alignment_options.get(alignment.lower(), WD_PARAGRAPH_ALIGNMENT.LEFT) | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path):
"""
Initializes the DocFileHandler object with the specified file path.
:param file_path: str, the path to the Word document file.
"""
self.file_path = file_path
def read_text(self):
"""
Reads the content of a Word document and returns it as a string.
:return: str, the content of the Word document.
"""
def write_text(self, content, font_size=12, alignment='left'):
"""
Writes the specified content to a Word document.
:param content: str, the text content to write.
:param font_size: int, optional, the font size of the text (default is 12).
:param alignment: str, optional, the alignment of the text ('left', 'center', or 'right'; default is 'left').
:return: bool, True if the write operation is successful, False otherwise.
"""
def add_heading(self, heading, level=1):
"""
Adds a heading to the Word document.
:param heading: str, the text of the heading.
:param level: int, optional, the level of the heading (1, 2, 3, etc.; default is 1).
:return: bool, True if the heading is successfully added, False otherwise.
"""
def add_table(self, data):
"""
Adds a table to the Word document with the specified data.
:param data: list of lists, the data to populate the table.
:return: bool, True if the table is successfully added, False otherwise.
"""
def _get_alignment_value(self, alignment):
"""
Returns the alignment value corresponding to the given alignment string.
:param alignment: str, the alignment string ('left', 'center', or 'right').
:return: int, the alignment value.
""" | def _get_alignment_value(self, alignment):
alignment_options = {
'left': WD_PARAGRAPH_ALIGNMENT.LEFT,
'center': WD_PARAGRAPH_ALIGNMENT.CENTER,
'right': WD_PARAGRAPH_ALIGNMENT.RIGHT
}
return alignment_options.get(alignment.lower(), WD_PARAGRAPH_ALIGNMENT.LEFT) | Returns the alignment value corresponding to the given alignment string. |
ClassEval_35_sum | class EightPuzzle:
"""
This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.
"""
def __init__(self, initial_state):
self.initial_state = initial_state
self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
def move(self, state, direction):
"""
Find the blank block, then makes the board moves forward the given direction.
:param state: a 3*3 size list of Integer, stores the state before moving.
:param direction: str, only has 4 direction 'up', 'down', 'left', 'right'
:return new_state: a 3*3 size list of Integer, stores the state after moving.
>>> eightPuzzle.move([[2, 3, 4], [5, 8, 1], [6, 0, 7]], 'left')
[[2, 3, 4], [5, 8, 1], [0, 6, 7]]
"""
i, j = self.find_blank(state)
new_state = [row[:] for row in state]
if direction == 'up':
new_state[i][j], new_state[i - 1][j] = new_state[i - 1][j], new_state[i][j]
elif direction == 'down':
new_state[i][j], new_state[i + 1][j] = new_state[i + 1][j], new_state[i][j]
elif direction == 'left':
new_state[i][j], new_state[i][j - 1] = new_state[i][j - 1], new_state[i][j]
elif direction == 'right':
new_state[i][j], new_state[i][j + 1] = new_state[i][j + 1], new_state[i][j]
return new_state
def get_possible_moves(self, state):
"""
According the current state, find all the possible moving directions. Only has 4 direction 'up', 'down', 'left', 'right'.
:param state: a 3*3 size list of Integer, stores the current state.
:return moves: a list of str, store all the possible moving directions according to the current state.
>>> eightPuzzle.get_possible_moves([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
['up', 'left', 'right']
"""
moves = []
i, j = self.find_blank(state)
if i > 0:
moves.append('up')
if i < 2:
moves.append('down')
if j > 0:
moves.append('left')
if j < 2:
moves.append('right')
return moves
def solve(self):
"""
Use BFS algorithm to find the path solution which makes the initial state to the goal method.
Maintain a list as a queue, named as open_list, append the initial state.
Always visit and pop the 0 index element, invoke get_possible_moves method find all the possible directions.
Traversal the possible_moves list and invoke move method to get several new states.Then append them.
redo the above steps until the open_list is empty or the state has changed to the goal state.
:return path: list of str, the solution to the goal state.
>>> eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])
>>> eightPuzzle.solve()
['right']
"""
open_list = [(self.initial_state, [])]
closed_list = []
while open_list:
current_state, path = open_list.pop(0)
closed_list.append(current_state)
if current_state == self.goal_state:
return path
for move in self.get_possible_moves(current_state):
new_state = self.move(current_state, move)
if new_state not in closed_list:
open_list.append((new_state, path + [move]))
return None | class EightPuzzle:
"""
This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.
"""
def __init__(self, initial_state):
"""
Initializing the initial state of Eight Puzzle Game, stores in attribute self.initial_state.
And set the goal state of this game, stores in self.goal_state. In this case, set the size as 3*3
:param initial_state: a 3*3 size list of Integer, stores the initial state
"""
self.initial_state = initial_state
self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
def move(self, state, direction):
"""
Find the blank block, then makes the board moves forward the given direction.
:param state: a 3*3 size list of Integer, stores the state before moving.
:param direction: str, only has 4 direction 'up', 'down', 'left', 'right'
:return new_state: a 3*3 size list of Integer, stores the state after moving.
>>> eightPuzzle.move([[2, 3, 4], [5, 8, 1], [6, 0, 7]], 'left')
[[2, 3, 4], [5, 8, 1], [0, 6, 7]]
"""
def get_possible_moves(self, state):
"""
According the current state, find all the possible moving directions. Only has 4 direction 'up', 'down', 'left', 'right'.
:param state: a 3*3 size list of Integer, stores the current state.
:return moves: a list of str, store all the possible moving directions according to the current state.
>>> eightPuzzle.get_possible_moves([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
['up', 'left', 'right']
"""
def solve(self):
"""
Use BFS algorithm to find the path solution which makes the initial state to the goal method.
Maintain a list as a queue, named as open_list, append the initial state.
Always visit and pop the 0 index element, invoke get_possible_moves method find all the possible directions.
Traversal the possible_moves list and invoke move method to get several new states.Then append them.
redo the above steps until the open_list is empty or the state has changed to the goal state.
:return path: list of str, the solution to the goal state.
>>> eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])
>>> eightPuzzle.solve()
['right']
""" | def find_blank(self, state):
for i in range(3):
for j in range(3):
if state[i][j] == 0:
return i, j | Find the blank position of current state, which is the 0 element. |
ClassEval_35_sum | class EightPuzzle:
"""
This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.
"""
def __init__(self, initial_state):
self.initial_state = initial_state
self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
def find_blank(self, state):
"""
Find the blank position of current state, which is the 0 element.
:param state: a 3*3 size list of Integer, stores the current state.
:return i, j: two Integers, represent the coordinate of the blank block.
>>> eightPuzzle = EightPuzzle([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
>>> eightPuzzle.find_blank([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
(2, 1)
"""
for i in range(3):
for j in range(3):
if state[i][j] == 0:
return i, j
def get_possible_moves(self, state):
"""
According the current state, find all the possible moving directions. Only has 4 direction 'up', 'down', 'left', 'right'.
:param state: a 3*3 size list of Integer, stores the current state.
:return moves: a list of str, store all the possible moving directions according to the current state.
>>> eightPuzzle.get_possible_moves([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
['up', 'left', 'right']
"""
moves = []
i, j = self.find_blank(state)
if i > 0:
moves.append('up')
if i < 2:
moves.append('down')
if j > 0:
moves.append('left')
if j < 2:
moves.append('right')
return moves
def solve(self):
"""
Use BFS algorithm to find the path solution which makes the initial state to the goal method.
Maintain a list as a queue, named as open_list, append the initial state.
Always visit and pop the 0 index element, invoke get_possible_moves method find all the possible directions.
Traversal the possible_moves list and invoke move method to get several new states.Then append them.
redo the above steps until the open_list is empty or the state has changed to the goal state.
:return path: list of str, the solution to the goal state.
>>> eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])
>>> eightPuzzle.solve()
['right']
"""
open_list = [(self.initial_state, [])]
closed_list = []
while open_list:
current_state, path = open_list.pop(0)
closed_list.append(current_state)
if current_state == self.goal_state:
return path
for move in self.get_possible_moves(current_state):
new_state = self.move(current_state, move)
if new_state not in closed_list:
open_list.append((new_state, path + [move]))
return None | class EightPuzzle:
"""
This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.
"""
def __init__(self, initial_state):
"""
Initializing the initial state of Eight Puzzle Game, stores in attribute self.initial_state.
And set the goal state of this game, stores in self.goal_state. In this case, set the size as 3*3
:param initial_state: a 3*3 size list of Integer, stores the initial state
"""
self.initial_state = initial_state
self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
def find_blank(self, state):
"""
Find the blank position of current state, which is the 0 element.
:param state: a 3*3 size list of Integer, stores the current state.
:return i, j: two Integers, represent the coordinate of the blank block.
>>> eightPuzzle = EightPuzzle([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
>>> eightPuzzle.find_blank([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
(2, 1)
"""
def get_possible_moves(self, state):
"""
According the current state, find all the possible moving directions. Only has 4 direction 'up', 'down', 'left', 'right'.
:param state: a 3*3 size list of Integer, stores the current state.
:return moves: a list of str, store all the possible moving directions according to the current state.
>>> eightPuzzle.get_possible_moves([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
['up', 'left', 'right']
"""
def solve(self):
"""
Use BFS algorithm to find the path solution which makes the initial state to the goal method.
Maintain a list as a queue, named as open_list, append the initial state.
Always visit and pop the 0 index element, invoke get_possible_moves method find all the possible directions.
Traversal the possible_moves list and invoke move method to get several new states.Then append them.
redo the above steps until the open_list is empty or the state has changed to the goal state.
:return path: list of str, the solution to the goal state.
>>> eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])
>>> eightPuzzle.solve()
['right']
""" | def move(self, state, direction):
i, j = self.find_blank(state)
new_state = [row[:] for row in state]
if direction == 'up':
new_state[i][j], new_state[i - 1][j] = new_state[i - 1][j], new_state[i][j]
elif direction == 'down':
new_state[i][j], new_state[i + 1][j] = new_state[i + 1][j], new_state[i][j]
elif direction == 'left':
new_state[i][j], new_state[i][j - 1] = new_state[i][j - 1], new_state[i][j]
elif direction == 'right':
new_state[i][j], new_state[i][j + 1] = new_state[i][j + 1], new_state[i][j]
return new_state | Find the blank block, then makes the board moves forward the given direction. |
ClassEval_35_sum | class EightPuzzle:
"""
This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.
"""
def __init__(self, initial_state):
self.initial_state = initial_state
self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
def find_blank(self, state):
"""
Find the blank position of current state, which is the 0 element.
:param state: a 3*3 size list of Integer, stores the current state.
:return i, j: two Integers, represent the coordinate of the blank block.
>>> eightPuzzle = EightPuzzle([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
>>> eightPuzzle.find_blank([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
(2, 1)
"""
for i in range(3):
for j in range(3):
if state[i][j] == 0:
return i, j
def move(self, state, direction):
"""
Find the blank block, then makes the board moves forward the given direction.
:param state: a 3*3 size list of Integer, stores the state before moving.
:param direction: str, only has 4 direction 'up', 'down', 'left', 'right'
:return new_state: a 3*3 size list of Integer, stores the state after moving.
>>> eightPuzzle.move([[2, 3, 4], [5, 8, 1], [6, 0, 7]], 'left')
[[2, 3, 4], [5, 8, 1], [0, 6, 7]]
"""
i, j = self.find_blank(state)
new_state = [row[:] for row in state]
if direction == 'up':
new_state[i][j], new_state[i - 1][j] = new_state[i - 1][j], new_state[i][j]
elif direction == 'down':
new_state[i][j], new_state[i + 1][j] = new_state[i + 1][j], new_state[i][j]
elif direction == 'left':
new_state[i][j], new_state[i][j - 1] = new_state[i][j - 1], new_state[i][j]
elif direction == 'right':
new_state[i][j], new_state[i][j + 1] = new_state[i][j + 1], new_state[i][j]
return new_state
def solve(self):
"""
Use BFS algorithm to find the path solution which makes the initial state to the goal method.
Maintain a list as a queue, named as open_list, append the initial state.
Always visit and pop the 0 index element, invoke get_possible_moves method find all the possible directions.
Traversal the possible_moves list and invoke move method to get several new states.Then append them.
redo the above steps until the open_list is empty or the state has changed to the goal state.
:return path: list of str, the solution to the goal state.
>>> eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])
>>> eightPuzzle.solve()
['right']
"""
open_list = [(self.initial_state, [])]
closed_list = []
while open_list:
current_state, path = open_list.pop(0)
closed_list.append(current_state)
if current_state == self.goal_state:
return path
for move in self.get_possible_moves(current_state):
new_state = self.move(current_state, move)
if new_state not in closed_list:
open_list.append((new_state, path + [move]))
return None | class EightPuzzle:
"""
This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.
"""
def __init__(self, initial_state):
"""
Initializing the initial state of Eight Puzzle Game, stores in attribute self.initial_state.
And set the goal state of this game, stores in self.goal_state. In this case, set the size as 3*3
:param initial_state: a 3*3 size list of Integer, stores the initial state
"""
self.initial_state = initial_state
self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
def find_blank(self, state):
"""
Find the blank position of current state, which is the 0 element.
:param state: a 3*3 size list of Integer, stores the current state.
:return i, j: two Integers, represent the coordinate of the blank block.
>>> eightPuzzle = EightPuzzle([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
>>> eightPuzzle.find_blank([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
(2, 1)
"""
def move(self, state, direction):
"""
Find the blank block, then makes the board moves forward the given direction.
:param state: a 3*3 size list of Integer, stores the state before moving.
:param direction: str, only has 4 direction 'up', 'down', 'left', 'right'
:return new_state: a 3*3 size list of Integer, stores the state after moving.
>>> eightPuzzle.move([[2, 3, 4], [5, 8, 1], [6, 0, 7]], 'left')
[[2, 3, 4], [5, 8, 1], [0, 6, 7]]
"""
def solve(self):
"""
Use BFS algorithm to find the path solution which makes the initial state to the goal method.
Maintain a list as a queue, named as open_list, append the initial state.
Always visit and pop the 0 index element, invoke get_possible_moves method find all the possible directions.
Traversal the possible_moves list and invoke move method to get several new states.Then append them.
redo the above steps until the open_list is empty or the state has changed to the goal state.
:return path: list of str, the solution to the goal state.
>>> eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])
>>> eightPuzzle.solve()
['right']
""" | def get_possible_moves(self, state):
moves = []
i, j = self.find_blank(state)
if i > 0:
moves.append('up')
if i < 2:
moves.append('down')
if j > 0:
moves.append('left')
if j < 2:
moves.append('right')
return moves | According the current state, find all the possible moving directions. Only has 4 direction 'up', 'down', 'left', 'right'. |
ClassEval_35_sum | class EightPuzzle:
"""
This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.
"""
def __init__(self, initial_state):
self.initial_state = initial_state
self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
def find_blank(self, state):
"""
Find the blank position of current state, which is the 0 element.
:param state: a 3*3 size list of Integer, stores the current state.
:return i, j: two Integers, represent the coordinate of the blank block.
>>> eightPuzzle = EightPuzzle([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
>>> eightPuzzle.find_blank([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
(2, 1)
"""
for i in range(3):
for j in range(3):
if state[i][j] == 0:
return i, j
def move(self, state, direction):
"""
Find the blank block, then makes the board moves forward the given direction.
:param state: a 3*3 size list of Integer, stores the state before moving.
:param direction: str, only has 4 direction 'up', 'down', 'left', 'right'
:return new_state: a 3*3 size list of Integer, stores the state after moving.
>>> eightPuzzle.move([[2, 3, 4], [5, 8, 1], [6, 0, 7]], 'left')
[[2, 3, 4], [5, 8, 1], [0, 6, 7]]
"""
i, j = self.find_blank(state)
new_state = [row[:] for row in state]
if direction == 'up':
new_state[i][j], new_state[i - 1][j] = new_state[i - 1][j], new_state[i][j]
elif direction == 'down':
new_state[i][j], new_state[i + 1][j] = new_state[i + 1][j], new_state[i][j]
elif direction == 'left':
new_state[i][j], new_state[i][j - 1] = new_state[i][j - 1], new_state[i][j]
elif direction == 'right':
new_state[i][j], new_state[i][j + 1] = new_state[i][j + 1], new_state[i][j]
return new_state
def get_possible_moves(self, state):
"""
According the current state, find all the possible moving directions. Only has 4 direction 'up', 'down', 'left', 'right'.
:param state: a 3*3 size list of Integer, stores the current state.
:return moves: a list of str, store all the possible moving directions according to the current state.
>>> eightPuzzle.get_possible_moves([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
['up', 'left', 'right']
"""
moves = []
i, j = self.find_blank(state)
if i > 0:
moves.append('up')
if i < 2:
moves.append('down')
if j > 0:
moves.append('left')
if j < 2:
moves.append('right')
return moves
def solve(self):
open_list = [(self.initial_state, [])]
closed_list = []
while open_list:
current_state, path = open_list.pop(0)
closed_list.append(current_state)
if current_state == self.goal_state:
return path
for move in self.get_possible_moves(current_state):
new_state = self.move(current_state, move)
if new_state not in closed_list:
open_list.append((new_state, path + [move]))
return None | class EightPuzzle:
"""
This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.
"""
def __init__(self, initial_state):
"""
Initializing the initial state of Eight Puzzle Game, stores in attribute self.initial_state.
And set the goal state of this game, stores in self.goal_state. In this case, set the size as 3*3
:param initial_state: a 3*3 size list of Integer, stores the initial state
"""
self.initial_state = initial_state
self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
def find_blank(self, state):
"""
Find the blank position of current state, which is the 0 element.
:param state: a 3*3 size list of Integer, stores the current state.
:return i, j: two Integers, represent the coordinate of the blank block.
>>> eightPuzzle = EightPuzzle([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
>>> eightPuzzle.find_blank([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
(2, 1)
"""
def move(self, state, direction):
"""
Find the blank block, then makes the board moves forward the given direction.
:param state: a 3*3 size list of Integer, stores the state before moving.
:param direction: str, only has 4 direction 'up', 'down', 'left', 'right'
:return new_state: a 3*3 size list of Integer, stores the state after moving.
>>> eightPuzzle.move([[2, 3, 4], [5, 8, 1], [6, 0, 7]], 'left')
[[2, 3, 4], [5, 8, 1], [0, 6, 7]]
"""
def get_possible_moves(self, state):
"""
According the current state, find all the possible moving directions. Only has 4 direction 'up', 'down', 'left', 'right'.
:param state: a 3*3 size list of Integer, stores the current state.
:return moves: a list of str, store all the possible moving directions according to the current state.
>>> eightPuzzle.get_possible_moves([[2, 3, 4], [5, 8, 1], [6, 0, 7]])
['up', 'left', 'right']
"""
def solve(self):
"""
Use BFS algorithm to find the path solution which makes the initial state to the goal method.
Maintain a list as a queue, named as open_list, append the initial state.
Always visit and pop the 0 index element, invoke get_possible_moves method find all the possible directions.
Traversal the possible_moves list and invoke move method to get several new states.Then append them.
redo the above steps until the open_list is empty or the state has changed to the goal state.
:return path: list of str, the solution to the goal state.
>>> eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])
>>> eightPuzzle.solve()
['right']
""" | def solve(self):
open_list = [(self.initial_state, [])]
closed_list = []
while open_list:
current_state, path = open_list.pop(0)
closed_list.append(current_state)
if current_state == self.goal_state:
return path
for move in self.get_possible_moves(current_state):
new_state = self.move(current_state, move)
if new_state not in closed_list:
open_list.append((new_state, path + [move]))
return None | Use BFS algorithm to find the path solution which makes the initial state to the goal method. Maintain a list as a queue, named as open_list, append the initial state. Always visit and pop the 0 index element, invoke get_possible_moves method find all the possible directions. Traversal the possible_moves list and invoke move method to get several new states.Then append them. redo the above steps until the open_list is empty or the state has changed to the goal state. |
ClassEval_36_sum | from datetime import datetime
class EmailClient:
"""
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
def __init__(self, addr, capacity) -> None:
self.addr = addr
self.capacity = capacity
self.inbox = []
def send_to(self, recv, content, size):
if not recv.is_full_with_one_more_email(size):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
email = {
"sender": self.addr,
"receiver": recv.addr,
"content": content,
"size": size,
"time": timestamp,
"state": "unread"
}
recv.inbox.append(email)
return True
else:
self.clear_inbox(size)
return False
def fetch(self):
"""
Retrieves the first unread email in the email box and marks it as read.
:return: The first unread email in the email box, dict.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}]
>>> receiver.fetch()
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'read'}
"""
if len(self.inbox) == 0:
return None
for i in range(len(self.inbox)):
if self.inbox[i]['state'] == "unread":
self.inbox[i]['state'] = "read"
return self.inbox[i]
return None
def is_full_with_one_more_email(self, size):
"""
Determines whether the email box is full after adding an email of the given size.
:param size: The size of the email, float.
:return: True if the email box is full, False otherwise.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.is_full_with_one_more_email(10)
False
"""
occupied_size = self.get_occupied_size()
return True if occupied_size + size > self.capacity else False
def get_occupied_size(self):
"""
Gets the total size of the emails in the email box.
:return: The total size of the emails in the email box, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]
>>> sender.get_occupied_size()
10
"""
occupied_size = 0
for email in self.inbox:
occupied_size += email["size"]
return occupied_size
def clear_inbox(self, size):
"""
Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size.
:param size: The size of the email, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]
>>> receiver.clear_inbox(30)
>>> receiver.inbox
[{'size': 15}]
"""
if len(self.addr) == 0:
return
freed_space = 0
while freed_space < size and self.inbox:
email = self.inbox[0]
freed_space += email['size']
del self.inbox[0] | from datetime import datetime
class EmailClient:
"""
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
def __init__(self, addr, capacity) -> None:
"""
Initializes the EmailClient class with the email address and the capacity of the email box.
:param addr: The email address, str.
:param capacity: The capacity of the email box, float.
"""
self.addr = addr
self.capacity = capacity
self.inbox = []
def fetch(self):
"""
Retrieves the first unread email in the email box and marks it as read.
:return: The first unread email in the email box, dict.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}]
>>> receiver.fetch()
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'read'}
"""
def is_full_with_one_more_email(self, size):
"""
Determines whether the email box is full after adding an email of the given size.
:param size: The size of the email, float.
:return: True if the email box is full, False otherwise.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.is_full_with_one_more_email(10)
False
"""
def get_occupied_size(self):
"""
Gets the total size of the emails in the email box.
:return: The total size of the emails in the email box, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]
>>> sender.get_occupied_size()
10
"""
def clear_inbox(self, size):
"""
Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size.
:param size: The size of the email, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]
>>> receiver.clear_inbox(30)
>>> receiver.inbox
[{'size': 15}]
""" | def send_to(self, recv, content, size):
if not recv.is_full_with_one_more_email(size):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
email = {
"sender": self.addr,
"receiver": recv.addr,
"content": content,
"size": size,
"time": timestamp,
"state": "unread"
}
recv.inbox.append(email)
return True
else:
self.clear_inbox(size)
return False | Sends an email to the given email address. |
ClassEval_36_sum | from datetime import datetime
class EmailClient:
"""
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
def __init__(self, addr, capacity) -> None:
self.addr = addr
self.capacity = capacity
self.inbox = []
def send_to(self, recv, content, size):
"""
Sends an email to the given email address.
:param recv: The email address of the receiver, str.
:param content: The content of the email, str.
:param size: The size of the email, float.
:return: True if the email is sent successfully, False if the receiver's email box is full.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.send_to(receiver, 'Hello', 10)
True
>>> receiver.inbox
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}
"""
if not recv.is_full_with_one_more_email(size):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
email = {
"sender": self.addr,
"receiver": recv.addr,
"content": content,
"size": size,
"time": timestamp,
"state": "unread"
}
recv.inbox.append(email)
return True
else:
self.clear_inbox(size)
return False
def is_full_with_one_more_email(self, size):
"""
Determines whether the email box is full after adding an email of the given size.
:param size: The size of the email, float.
:return: True if the email box is full, False otherwise.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.is_full_with_one_more_email(10)
False
"""
occupied_size = self.get_occupied_size()
return True if occupied_size + size > self.capacity else False
def get_occupied_size(self):
"""
Gets the total size of the emails in the email box.
:return: The total size of the emails in the email box, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]
>>> sender.get_occupied_size()
10
"""
occupied_size = 0
for email in self.inbox:
occupied_size += email["size"]
return occupied_size
def clear_inbox(self, size):
"""
Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size.
:param size: The size of the email, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]
>>> receiver.clear_inbox(30)
>>> receiver.inbox
[{'size': 15}]
"""
if len(self.addr) == 0:
return
freed_space = 0
while freed_space < size and self.inbox:
email = self.inbox[0]
freed_space += email['size']
del self.inbox[0] | from datetime import datetime
class EmailClient:
"""
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
def __init__(self, addr, capacity) -> None:
"""
Initializes the EmailClient class with the email address and the capacity of the email box.
:param addr: The email address, str.
:param capacity: The capacity of the email box, float.
"""
self.addr = addr
self.capacity = capacity
self.inbox = []
def send_to(self, recv, content, size):
"""
Sends an email to the given email address.
:param recv: The email address of the receiver, str.
:param content: The content of the email, str.
:param size: The size of the email, float.
:return: True if the email is sent successfully, False if the receiver's email box is full.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.send_to(receiver, 'Hello', 10)
True
>>> receiver.inbox
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}
"""
def is_full_with_one_more_email(self, size):
"""
Determines whether the email box is full after adding an email of the given size.
:param size: The size of the email, float.
:return: True if the email box is full, False otherwise.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.is_full_with_one_more_email(10)
False
"""
def get_occupied_size(self):
"""
Gets the total size of the emails in the email box.
:return: The total size of the emails in the email box, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]
>>> sender.get_occupied_size()
10
"""
def clear_inbox(self, size):
"""
Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size.
:param size: The size of the email, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]
>>> receiver.clear_inbox(30)
>>> receiver.inbox
[{'size': 15}]
""" | def fetch(self):
if len(self.inbox) == 0:
return None
for i in range(len(self.inbox)):
if self.inbox[i]['state'] == "unread":
self.inbox[i]['state'] = "read"
return self.inbox[i]
return None | Retrieves the first unread email in the email box and marks it as read. |
ClassEval_36_sum | from datetime import datetime
class EmailClient:
"""
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
def __init__(self, addr, capacity) -> None:
self.addr = addr
self.capacity = capacity
self.inbox = []
def send_to(self, recv, content, size):
"""
Sends an email to the given email address.
:param recv: The email address of the receiver, str.
:param content: The content of the email, str.
:param size: The size of the email, float.
:return: True if the email is sent successfully, False if the receiver's email box is full.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.send_to(receiver, 'Hello', 10)
True
>>> receiver.inbox
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}
"""
if not recv.is_full_with_one_more_email(size):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
email = {
"sender": self.addr,
"receiver": recv.addr,
"content": content,
"size": size,
"time": timestamp,
"state": "unread"
}
recv.inbox.append(email)
return True
else:
self.clear_inbox(size)
return False
def fetch(self):
"""
Retrieves the first unread email in the email box and marks it as read.
:return: The first unread email in the email box, dict.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}]
>>> receiver.fetch()
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'read'}
"""
if len(self.inbox) == 0:
return None
for i in range(len(self.inbox)):
if self.inbox[i]['state'] == "unread":
self.inbox[i]['state'] = "read"
return self.inbox[i]
return None
def is_full_with_one_more_email(self, size):
occupied_size = self.get_occupied_size()
return True if occupied_size + size > self.capacity else False
def get_occupied_size(self):
"""
Gets the total size of the emails in the email box.
:return: The total size of the emails in the email box, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]
>>> sender.get_occupied_size()
10
"""
occupied_size = 0
for email in self.inbox:
occupied_size += email["size"]
return occupied_size
def clear_inbox(self, size):
"""
Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size.
:param size: The size of the email, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]
>>> receiver.clear_inbox(30)
>>> receiver.inbox
[{'size': 15}]
"""
if len(self.addr) == 0:
return
freed_space = 0
while freed_space < size and self.inbox:
email = self.inbox[0]
freed_space += email['size']
del self.inbox[0] | from datetime import datetime
class EmailClient:
"""
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
def __init__(self, addr, capacity) -> None:
"""
Initializes the EmailClient class with the email address and the capacity of the email box.
:param addr: The email address, str.
:param capacity: The capacity of the email box, float.
"""
self.addr = addr
self.capacity = capacity
self.inbox = []
def send_to(self, recv, content, size):
"""
Sends an email to the given email address.
:param recv: The email address of the receiver, str.
:param content: The content of the email, str.
:param size: The size of the email, float.
:return: True if the email is sent successfully, False if the receiver's email box is full.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.send_to(receiver, 'Hello', 10)
True
>>> receiver.inbox
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}
"""
def fetch(self):
"""
Retrieves the first unread email in the email box and marks it as read.
:return: The first unread email in the email box, dict.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}]
>>> receiver.fetch()
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'read'}
"""
def get_occupied_size(self):
"""
Gets the total size of the emails in the email box.
:return: The total size of the emails in the email box, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]
>>> sender.get_occupied_size()
10
"""
def clear_inbox(self, size):
"""
Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size.
:param size: The size of the email, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]
>>> receiver.clear_inbox(30)
>>> receiver.inbox
[{'size': 15}]
""" | def is_full_with_one_more_email(self, size):
occupied_size = self.get_occupied_size()
return True if occupied_size + size > self.capacity else False | Determines whether the email box is full after adding an email of the given size. |
ClassEval_36_sum | from datetime import datetime
class EmailClient:
"""
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
def __init__(self, addr, capacity) -> None:
self.addr = addr
self.capacity = capacity
self.inbox = []
def send_to(self, recv, content, size):
"""
Sends an email to the given email address.
:param recv: The email address of the receiver, str.
:param content: The content of the email, str.
:param size: The size of the email, float.
:return: True if the email is sent successfully, False if the receiver's email box is full.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.send_to(receiver, 'Hello', 10)
True
>>> receiver.inbox
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}
"""
if not recv.is_full_with_one_more_email(size):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
email = {
"sender": self.addr,
"receiver": recv.addr,
"content": content,
"size": size,
"time": timestamp,
"state": "unread"
}
recv.inbox.append(email)
return True
else:
self.clear_inbox(size)
return False
def fetch(self):
"""
Retrieves the first unread email in the email box and marks it as read.
:return: The first unread email in the email box, dict.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}]
>>> receiver.fetch()
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'read'}
"""
if len(self.inbox) == 0:
return None
for i in range(len(self.inbox)):
if self.inbox[i]['state'] == "unread":
self.inbox[i]['state'] = "read"
return self.inbox[i]
return None
def is_full_with_one_more_email(self, size):
"""
Determines whether the email box is full after adding an email of the given size.
:param size: The size of the email, float.
:return: True if the email box is full, False otherwise.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.is_full_with_one_more_email(10)
False
"""
occupied_size = self.get_occupied_size()
return True if occupied_size + size > self.capacity else False
def clear_inbox(self, size):
"""
Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size.
:param size: The size of the email, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]
>>> receiver.clear_inbox(30)
>>> receiver.inbox
[{'size': 15}]
"""
if len(self.addr) == 0:
return
freed_space = 0
while freed_space < size and self.inbox:
email = self.inbox[0]
freed_space += email['size']
del self.inbox[0] | from datetime import datetime
class EmailClient:
"""
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
def __init__(self, addr, capacity) -> None:
"""
Initializes the EmailClient class with the email address and the capacity of the email box.
:param addr: The email address, str.
:param capacity: The capacity of the email box, float.
"""
self.addr = addr
self.capacity = capacity
self.inbox = []
def send_to(self, recv, content, size):
"""
Sends an email to the given email address.
:param recv: The email address of the receiver, str.
:param content: The content of the email, str.
:param size: The size of the email, float.
:return: True if the email is sent successfully, False if the receiver's email box is full.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.send_to(receiver, 'Hello', 10)
True
>>> receiver.inbox
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}
"""
def fetch(self):
"""
Retrieves the first unread email in the email box and marks it as read.
:return: The first unread email in the email box, dict.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}]
>>> receiver.fetch()
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'read'}
"""
def is_full_with_one_more_email(self, size):
"""
Determines whether the email box is full after adding an email of the given size.
:param size: The size of the email, float.
:return: True if the email box is full, False otherwise.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.is_full_with_one_more_email(10)
False
"""
def clear_inbox(self, size):
"""
Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size.
:param size: The size of the email, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]
>>> receiver.clear_inbox(30)
>>> receiver.inbox
[{'size': 15}]
""" | def get_occupied_size(self):
occupied_size = 0
for email in self.inbox:
occupied_size += email["size"]
return occupied_size | Gets the total size of the emails in the email box. |
ClassEval_36_sum | from datetime import datetime
class EmailClient:
"""
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
def __init__(self, addr, capacity) -> None:
self.addr = addr
self.capacity = capacity
self.inbox = []
def send_to(self, recv, content, size):
"""
Sends an email to the given email address.
:param recv: The email address of the receiver, str.
:param content: The content of the email, str.
:param size: The size of the email, float.
:return: True if the email is sent successfully, False if the receiver's email box is full.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.send_to(receiver, 'Hello', 10)
True
>>> receiver.inbox
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}
"""
if not recv.is_full_with_one_more_email(size):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
email = {
"sender": self.addr,
"receiver": recv.addr,
"content": content,
"size": size,
"time": timestamp,
"state": "unread"
}
recv.inbox.append(email)
return True
else:
self.clear_inbox(size)
return False
def fetch(self):
"""
Retrieves the first unread email in the email box and marks it as read.
:return: The first unread email in the email box, dict.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}]
>>> receiver.fetch()
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'read'}
"""
if len(self.inbox) == 0:
return None
for i in range(len(self.inbox)):
if self.inbox[i]['state'] == "unread":
self.inbox[i]['state'] = "read"
return self.inbox[i]
return None
def is_full_with_one_more_email(self, size):
"""
Determines whether the email box is full after adding an email of the given size.
:param size: The size of the email, float.
:return: True if the email box is full, False otherwise.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.is_full_with_one_more_email(10)
False
"""
occupied_size = self.get_occupied_size()
return True if occupied_size + size > self.capacity else False
def get_occupied_size(self):
"""
Gets the total size of the emails in the email box.
:return: The total size of the emails in the email box, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]
>>> sender.get_occupied_size()
10
"""
occupied_size = 0
for email in self.inbox:
occupied_size += email["size"]
return occupied_size
def clear_inbox(self, size):
if len(self.addr) == 0:
return
freed_space = 0
while freed_space < size and self.inbox:
email = self.inbox[0]
freed_space += email['size']
del self.inbox[0] | from datetime import datetime
class EmailClient:
"""
This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space
"""
def __init__(self, addr, capacity) -> None:
"""
Initializes the EmailClient class with the email address and the capacity of the email box.
:param addr: The email address, str.
:param capacity: The capacity of the email box, float.
"""
self.addr = addr
self.capacity = capacity
self.inbox = []
def send_to(self, recv, content, size):
"""
Sends an email to the given email address.
:param recv: The email address of the receiver, str.
:param content: The content of the email, str.
:param size: The size of the email, float.
:return: True if the email is sent successfully, False if the receiver's email box is full.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.send_to(receiver, 'Hello', 10)
True
>>> receiver.inbox
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}
"""
def fetch(self):
"""
Retrieves the first unread email in the email box and marks it as read.
:return: The first unread email in the email box, dict.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}]
>>> receiver.fetch()
{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'read'}
"""
def is_full_with_one_more_email(self, size):
"""
Determines whether the email box is full after adding an email of the given size.
:param size: The size of the email, float.
:return: True if the email box is full, False otherwise.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.is_full_with_one_more_email(10)
False
"""
def get_occupied_size(self):
"""
Gets the total size of the emails in the email box.
:return: The total size of the emails in the email box, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> sender.inbox = [{'sender': '[email protected]', 'receiver': '[email protected]', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]
>>> sender.get_occupied_size()
10
"""
def clear_inbox(self, size):
"""
Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size.
:param size: The size of the email, float.
>>> sender = EmailClient('[email protected]', 100)
>>> receiver = EmailClient('[email protected]', 50)
>>> receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]
>>> receiver.clear_inbox(30)
>>> receiver.inbox
[{'size': 15}]
""" | def clear_inbox(self, size):
if len(self.addr) == 0:
return
freed_space = 0
while freed_space < size and self.inbox:
email = self.inbox[0]
freed_space += email['size']
del self.inbox[0] | Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size. |
ClassEval_37_sum | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
self.key = key
def caesar_cipher(self, plaintext, shift):
ciphertext = ""
for char in plaintext:
if char.isalpha():
if char.isupper():
ascii_offset = 65
else:
ascii_offset = 97
shifted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
ciphertext += shifted_char
else:
ciphertext += char
return ciphertext
def vigenere_cipher(self, plain_text):
encrypted_text = ""
key_index = 0
for char in plain_text:
if char.isalpha():
shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')
encrypted_char = chr((ord(char.lower()) - ord('a') + shift) % 26 + ord('a'))
encrypted_text += encrypted_char.upper() if char.isupper() else encrypted_char
key_index += 1
else:
encrypted_text += char
return encrypted_text
def rail_fence_cipher(self, plain_text, rails):
fence = [['\n' for _ in range(len(plain_text))] for _ in range(rails)]
direction = -1
row, col = 0, 0
for char in plain_text:
if row == 0 or row == rails-1:
direction = -direction
fence[row][col] = char
col += 1
row += direction
encrypted_text = ''
for i in range(rails):
for j in range(len(plain_text)):
if fence[i][j] != '\n':
encrypted_text += fence[i][j]
return encrypted_text | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the class with a key.
:param key: The key to use for encryption, str.
"""
self.key = key
def vigenere_cipher(self, plaintext):
"""
Encrypts the plaintext using the Vigenere cipher.
:param plaintext: The plaintext to encrypt, str.
:return: The ciphertext, str.
>>> e = EncryptionUtils("key")
>>> e.vigenere_cipher("abc")
'kfa'
"""
def rail_fence_cipher(self,plain_text, rails):
"""
Encrypts the plaintext using the Rail Fence cipher.
:param plaintext: The plaintext to encrypt, str.
:return: The ciphertext, str.
>>> e = EncryptionUtils("key")
>>> e.rail_fence_cipher("abc", 2)
'acb'
""" | def caesar_cipher(self, plaintext, shift):
ciphertext = ""
for char in plaintext:
if char.isalpha():
if char.isupper():
ascii_offset = 65
else:
ascii_offset = 97
shifted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
ciphertext += shifted_char
else:
ciphertext += char
return ciphertext | Encrypts the plaintext using the Caesar cipher. |
ClassEval_37_sum | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
self.key = key
def caesar_cipher(self, plaintext, shift):
"""
Encrypts the plaintext using the Caesar cipher.
:param plaintext: The plaintext to encrypt, str.
:param shift: The number of characters to shift each character in the plaintext, int.
:return: The ciphertext, str.
>>> e = EncryptionUtils("key")
>>> e.caesar_cipher("abc", 1)
'bcd'
"""
ciphertext = ""
for char in plaintext:
if char.isalpha():
if char.isupper():
ascii_offset = 65
else:
ascii_offset = 97
shifted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
ciphertext += shifted_char
else:
ciphertext += char
return ciphertext
def rail_fence_cipher(self, plain_text, rails):
fence = [['\n' for _ in range(len(plain_text))] for _ in range(rails)]
direction = -1
row, col = 0, 0
for char in plain_text:
if row == 0 or row == rails-1:
direction = -direction
fence[row][col] = char
col += 1
row += direction
encrypted_text = ''
for i in range(rails):
for j in range(len(plain_text)):
if fence[i][j] != '\n':
encrypted_text += fence[i][j]
return encrypted_text | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the class with a key.
:param key: The key to use for encryption, str.
"""
self.key = key
def caesar_cipher(self, plaintext, shift):
"""
Encrypts the plaintext using the Caesar cipher.
:param plaintext: The plaintext to encrypt, str.
:param shift: The number of characters to shift each character in the plaintext, int.
:return: The ciphertext, str.
>>> e = EncryptionUtils("key")
>>> e.caesar_cipher("abc", 1)
'bcd'
"""
def rail_fence_cipher(self,plain_text, rails):
"""
Encrypts the plaintext using the Rail Fence cipher.
:param plaintext: The plaintext to encrypt, str.
:return: The ciphertext, str.
>>> e = EncryptionUtils("key")
>>> e.rail_fence_cipher("abc", 2)
'acb'
""" | def vigenere_cipher(self, plain_text):
encrypted_text = ""
key_index = 0
for char in plain_text:
if char.isalpha():
shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')
encrypted_char = chr((ord(char.lower()) - ord('a') + shift) % 26 + ord('a'))
encrypted_text += encrypted_char.upper() if char.isupper() else encrypted_char
key_index += 1
else:
encrypted_text += char
return encrypted_text | Encrypts the plaintext using the Vigenere cipher. |
ClassEval_37_sum | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
self.key = key
def caesar_cipher(self, plaintext, shift):
"""
Encrypts the plaintext using the Caesar cipher.
:param plaintext: The plaintext to encrypt, str.
:param shift: The number of characters to shift each character in the plaintext, int.
:return: The ciphertext, str.
>>> e = EncryptionUtils("key")
>>> e.caesar_cipher("abc", 1)
'bcd'
"""
ciphertext = ""
for char in plaintext:
if char.isalpha():
if char.isupper():
ascii_offset = 65
else:
ascii_offset = 97
shifted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
ciphertext += shifted_char
else:
ciphertext += char
return ciphertext
def vigenere_cipher(self, plain_text):
encrypted_text = ""
key_index = 0
for char in plain_text:
if char.isalpha():
shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')
encrypted_char = chr((ord(char.lower()) - ord('a') + shift) % 26 + ord('a'))
encrypted_text += encrypted_char.upper() if char.isupper() else encrypted_char
key_index += 1
else:
encrypted_text += char
return encrypted_text
def rail_fence_cipher(self, plain_text, rails):
fence = [['\n' for _ in range(len(plain_text))] for _ in range(rails)]
direction = -1
row, col = 0, 0
for char in plain_text:
if row == 0 or row == rails-1:
direction = -direction
fence[row][col] = char
col += 1
row += direction
encrypted_text = ''
for i in range(rails):
for j in range(len(plain_text)):
if fence[i][j] != '\n':
encrypted_text += fence[i][j]
return encrypted_text | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the class with a key.
:param key: The key to use for encryption, str.
"""
self.key = key
def caesar_cipher(self, plaintext, shift):
"""
Encrypts the plaintext using the Caesar cipher.
:param plaintext: The plaintext to encrypt, str.
:param shift: The number of characters to shift each character in the plaintext, int.
:return: The ciphertext, str.
>>> e = EncryptionUtils("key")
>>> e.caesar_cipher("abc", 1)
'bcd'
"""
def vigenere_cipher(self, plaintext):
"""
Encrypts the plaintext using the Vigenere cipher.
:param plaintext: The plaintext to encrypt, str.
:return: The ciphertext, str.
>>> e = EncryptionUtils("key")
>>> e.vigenere_cipher("abc")
'kfa'
"""
def rail_fence_cipher(self,plain_text, rails):
"""
Encrypts the plaintext using the Rail Fence cipher.
:param plaintext: The plaintext to encrypt, str.
:return: The ciphertext, str.
>>> e = EncryptionUtils("key")
>>> e.rail_fence_cipher("abc", 2)
'acb'
""" | def rail_fence_cipher(self, plain_text, rails):
fence = [['\n' for _ in range(len(plain_text))] for _ in range(rails)]
direction = -1
row, col = 0, 0
for char in plain_text:
if row == 0 or row == rails-1:
direction = -direction
fence[row][col] = char
col += 1
row += direction
encrypted_text = ''
for i in range(rails):
for j in range(len(plain_text)):
if fence[i][j] != '\n':
encrypted_text += fence[i][j]
return encrypted_text | Encrypts the plaintext using the Rail Fence cipher. |
ClassEval_38_sum | import openpyxl
class ExcelProcessor:
"""
This is a class for processing excel files, including readring and writing excel data, as well as processing specific operations and saving as a new excel file.
"""
def __init__(self):
pass
def write_excel(self, data, file_name):
"""
Write data to the specified Excel file
:param data: list, Data to be written
:param file_name: str, Excel file name to write to
:return: 0 or 1, 1 represents successful writing, 0 represents failed writing
>>> processor = ExcelProcessor()
>>> new_data = [
>>> ('Name', 'Age', 'Country'),
>>> ('John', 25, 'USA'),
>>> ('Alice', 30, 'Canada'),
>>> ('Bob', 35, 'Australia'),
>>> ('Julia', 28, 'Germany')
>>> ]
>>> data = processor.write_excel(new_data, 'test_data.xlsx')
"""
try:
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(file_name)
workbook.close()
return 1
except:
return 0
def process_excel_data(self, N, save_file_name):
"""
Change the specified column in the Excel file to uppercase
:param N: int, The serial number of the column that want to change
:param save_file_name: str, source file name
:return:(int, str), The former is the return value of write_excel, while the latter is the saved file name of the processed data
>>> processor = ExcelProcessor()
>>> success, output_file = processor.process_excel_data(1, 'test_data.xlsx')
"""
data = self.read_excel(save_file_name)
if data is None or N >= len(data[0]):
return 0
new_data = []
for row in data:
new_row = list(row[:])
if not str(row[N]).isdigit():
new_row.append(str(row[N]).upper())
else:
new_row.append(row[N])
new_data.append(new_row)
new_file_name = save_file_name.split('.')[0] + '_process.xlsx'
success = self.write_excel(new_data, new_file_name)
return success, new_file_name | import openpyxl
class ExcelProcessor:
"""
This is a class for processing excel files, including readring and writing excel data, as well as processing specific operations and saving as a new excel file.
"""
def __init__(self):
pass
def write_excel(self, data, file_name):
"""
Write data to the specified Excel file
:param data: list, Data to be written
:param file_name: str, Excel file name to write to
:return: 0 or 1, 1 represents successful writing, 0 represents failed writing
>>> processor = ExcelProcessor()
>>> new_data = [
>>> ('Name', 'Age', 'Country'),
>>> ('John', 25, 'USA'),
>>> ('Alice', 30, 'Canada'),
>>> ('Bob', 35, 'Australia'),
>>> ('Julia', 28, 'Germany')
>>> ]
>>> data = processor.write_excel(new_data, 'test_data.xlsx')
"""
def process_excel_data(self, N, save_file_name):
"""
Change the specified column in the Excel file to uppercase
:param N: int, The serial number of the column that want to change
:param save_file_name: str, source file name
:return:(int, str), The former is the return value of write_excel, while the latter is the saved file name of the processed data
>>> processor = ExcelProcessor()
>>> success, output_file = processor.process_excel_data(1, 'test_data.xlsx')
""" | def read_excel(self, file_name):
data = []
try:
workbook = openpyxl.load_workbook(file_name)
sheet = workbook.active
for row in sheet.iter_rows(values_only=True):
data.append(row)
workbook.close()
return data
except:
return None | Reading data from Excel files |
ClassEval_38_sum | import openpyxl
class ExcelProcessor:
"""
This is a class for processing excel files, including readring and writing excel data, as well as processing specific operations and saving as a new excel file.
"""
def __init__(self):
pass
def read_excel(self, file_name):
"""
Reading data from Excel files
:param file_name:str, Excel file name to read
:return:list of data, Data in Excel
"""
data = []
try:
workbook = openpyxl.load_workbook(file_name)
sheet = workbook.active
for row in sheet.iter_rows(values_only=True):
data.append(row)
workbook.close()
return data
except:
return None
def process_excel_data(self, N, save_file_name):
"""
Change the specified column in the Excel file to uppercase
:param N: int, The serial number of the column that want to change
:param save_file_name: str, source file name
:return:(int, str), The former is the return value of write_excel, while the latter is the saved file name of the processed data
>>> processor = ExcelProcessor()
>>> success, output_file = processor.process_excel_data(1, 'test_data.xlsx')
"""
data = self.read_excel(save_file_name)
if data is None or N >= len(data[0]):
return 0
new_data = []
for row in data:
new_row = list(row[:])
if not str(row[N]).isdigit():
new_row.append(str(row[N]).upper())
else:
new_row.append(row[N])
new_data.append(new_row)
new_file_name = save_file_name.split('.')[0] + '_process.xlsx'
success = self.write_excel(new_data, new_file_name)
return success, new_file_name | import openpyxl
class ExcelProcessor:
"""
This is a class for processing excel files, including readring and writing excel data, as well as processing specific operations and saving as a new excel file.
"""
def __init__(self):
pass
def read_excel(self, file_name):
"""
Reading data from Excel files
:param file_name:str, Excel file name to read
:return:list of data, Data in Excel
"""
def process_excel_data(self, N, save_file_name):
"""
Change the specified column in the Excel file to uppercase
:param N: int, The serial number of the column that want to change
:param save_file_name: str, source file name
:return:(int, str), The former is the return value of write_excel, while the latter is the saved file name of the processed data
>>> processor = ExcelProcessor()
>>> success, output_file = processor.process_excel_data(1, 'test_data.xlsx')
""" | def write_excel(self, data, file_name):
try:
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(file_name)
workbook.close()
return 1
except:
return 0 | Write data to the specified Excel file |
ClassEval_38_sum | import openpyxl
class ExcelProcessor:
"""
This is a class for processing excel files, including readring and writing excel data, as well as processing specific operations and saving as a new excel file.
"""
def __init__(self):
pass
def read_excel(self, file_name):
"""
Reading data from Excel files
:param file_name:str, Excel file name to read
:return:list of data, Data in Excel
"""
data = []
try:
workbook = openpyxl.load_workbook(file_name)
sheet = workbook.active
for row in sheet.iter_rows(values_only=True):
data.append(row)
workbook.close()
return data
except:
return None
def write_excel(self, data, file_name):
"""
Write data to the specified Excel file
:param data: list, Data to be written
:param file_name: str, Excel file name to write to
:return: 0 or 1, 1 represents successful writing, 0 represents failed writing
>>> processor = ExcelProcessor()
>>> new_data = [
>>> ('Name', 'Age', 'Country'),
>>> ('John', 25, 'USA'),
>>> ('Alice', 30, 'Canada'),
>>> ('Bob', 35, 'Australia'),
>>> ('Julia', 28, 'Germany')
>>> ]
>>> data = processor.write_excel(new_data, 'test_data.xlsx')
"""
try:
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(file_name)
workbook.close()
return 1
except:
return 0
def process_excel_data(self, N, save_file_name):
data = self.read_excel(save_file_name)
if data is None or N >= len(data[0]):
return 0
new_data = []
for row in data:
new_row = list(row[:])
if not str(row[N]).isdigit():
new_row.append(str(row[N]).upper())
else:
new_row.append(row[N])
new_data.append(new_row)
new_file_name = save_file_name.split('.')[0] + '_process.xlsx'
success = self.write_excel(new_data, new_file_name)
return success, new_file_name | import openpyxl
class ExcelProcessor:
"""
This is a class for processing excel files, including readring and writing excel data, as well as processing specific operations and saving as a new excel file.
"""
def __init__(self):
pass
def read_excel(self, file_name):
"""
Reading data from Excel files
:param file_name:str, Excel file name to read
:return:list of data, Data in Excel
"""
def write_excel(self, data, file_name):
"""
Write data to the specified Excel file
:param data: list, Data to be written
:param file_name: str, Excel file name to write to
:return: 0 or 1, 1 represents successful writing, 0 represents failed writing
>>> processor = ExcelProcessor()
>>> new_data = [
>>> ('Name', 'Age', 'Country'),
>>> ('John', 25, 'USA'),
>>> ('Alice', 30, 'Canada'),
>>> ('Bob', 35, 'Australia'),
>>> ('Julia', 28, 'Germany')
>>> ]
>>> data = processor.write_excel(new_data, 'test_data.xlsx')
"""
def process_excel_data(self, N, save_file_name):
"""
Change the specified column in the Excel file to uppercase
:param N: int, The serial number of the column that want to change
:param save_file_name: str, source file name
:return:(int, str), The former is the return value of write_excel, while the latter is the saved file name of the processed data
>>> processor = ExcelProcessor()
>>> success, output_file = processor.process_excel_data(1, 'test_data.xlsx')
""" | def process_excel_data(self, N, save_file_name):
data = self.read_excel(save_file_name)
if data is None or N >= len(data[0]):
return 0
new_data = []
for row in data:
new_row = list(row[:])
if not str(row[N]).isdigit():
new_row.append(str(row[N]).upper())
else:
new_row.append(row[N])
new_data.append(new_row)
new_file_name = save_file_name.split('.')[0] + '_process.xlsx'
success = self.write_excel(new_data, new_file_name)
return success, new_file_name | Change the specified column in the Excel file to uppercase |
ClassEval_39_sum | import re
from collections import deque
from decimal import Decimal
class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def prepare(self, expression):
"""
Prepare the infix expression for conversion to postfix notation
:param expression: string, the infix expression to be prepared
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.prepare("2+3*4")
expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']
"""
op_stack = deque([','])
arr = list(expression)
current_index = 0
count = 0
for i, current_op in enumerate(arr):
if self.is_operator(current_op):
if count > 0:
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
peek_op = op_stack[-1]
if current_op == ')':
while op_stack[-1] != '(':
self.postfix_stack.append(str(op_stack.pop()))
op_stack.pop()
else:
while current_op != '(' and peek_op != ',' and self.compare(current_op, peek_op):
self.postfix_stack.append(str(op_stack.pop()))
peek_op = op_stack[-1]
op_stack.append(current_op)
count = 0
current_index = i + 1
else:
count += 1
if count > 1 or (count == 1 and not self.is_operator(arr[current_index])):
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
while op_stack[-1] != ',':
self.postfix_stack.append(str(op_stack.pop()))
@staticmethod
def is_operator(c):
"""
Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}
:param c: string, the character to be checked
:return: bool, True if the character is an operator, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.is_operator("+")
True
"""
return c in {'+', '-', '*', '/', '(', ')', '%'}
def compare(self, cur, peek):
"""
Compare the precedence of two operators
:param cur: string, the current operator
:param peek: string, the operator at the top of the operator stack
:return: bool, True if the current operator has higher or equal precedence, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.compare("+", "-")
True
"""
if cur == '%':
cur = '/'
if peek == '%':
peek = '/'
return self.operat_priority[ord(peek) - 40] >= self.operat_priority[ord(cur) - 40]
@staticmethod
def _calculate(first_value, second_value, current_op):
"""
Perform the mathematical calculation based on the given operands and operator
:param first_value: string, the first operand
:param second_value: string, the second operand
:param current_op: string, the operator
:return: decimal.Decimal, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator._calculate("2", "3", "+")
5.0
"""
if current_op == '+':
return Decimal(first_value) + Decimal(second_value)
elif current_op == '-':
return Decimal(first_value) - Decimal(second_value)
elif current_op == '*':
return Decimal(first_value) * Decimal(second_value)
elif current_op == '/':
return Decimal(first_value) / Decimal(second_value)
elif current_op == '%':
return Decimal(first_value) % Decimal(second_value)
else:
raise ValueError("Unexpected operator: {}".format(current_op))
@staticmethod
def transform(expression):
"""
Transform the infix expression to a format suitable for conversion
:param expression: string, the infix expression to be transformed
:return: string, the transformed expression
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.transform("2 + 3 * 4")
"2+3*4"
"""
expression = re.sub(r"\s+", "", expression)
expression = re.sub(r"=$", "", expression)
arr = list(expression)
for i, c in enumerate(arr):
if c == '-':
if i == 0:
arr[i] = '~'
else:
prev_c = arr[i - 1]
if prev_c in {'+', '-', '*', '/', '(', 'E', 'e'}:
arr[i] = '~'
if arr[0] == '~' and (len(arr) > 1 and arr[1] == '('):
arr[0] = '-'
return "0" + "".join(arr)
else:
return "".join(arr) | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def prepare(self, expression):
"""
Prepare the infix expression for conversion to postfix notation
:param expression: string, the infix expression to be prepared
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.prepare("2+3*4")
expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']
"""
@staticmethod
def is_operator(c):
"""
Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}
:param c: string, the character to be checked
:return: bool, True if the character is an operator, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.is_operator("+")
True
"""
def compare(self, cur, peek):
"""
Compare the precedence of two operators
:param cur: string, the current operator
:param peek: string, the operator at the top of the operator stack
:return: bool, True if the current operator has higher or equal precedence, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.compare("+", "-")
True
"""
@staticmethod
def _calculate(first_value, second_value, current_op):
"""
Perform the mathematical calculation based on the given operands and operator
:param first_value: string, the first operand
:param second_value: string, the second operand
:param current_op: string, the operator
:return: decimal.Decimal, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator._calculate("2", "3", "+")
5.0
"""
@staticmethod
def transform(expression):
"""
Transform the infix expression to a format suitable for conversion
:param expression: string, the infix expression to be transformed
:return: string, the transformed expression
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.transform("2 + 3 * 4")
"2+3*4"
""" | def calculate(self, expression):
self.prepare(self.transform(expression))
result_stack = deque()
self.postfix_stack.reverse()
while self.postfix_stack:
current_op = self.postfix_stack.pop()
if not self.is_operator(current_op):
current_op = current_op.replace("~", "-")
result_stack.append(current_op)
else:
second_value = result_stack.pop()
first_value = result_stack.pop()
first_value = first_value.replace("~", "-")
second_value = second_value.replace("~", "-")
temp_result = self._calculate(first_value, second_value, current_op)
result_stack.append(str(temp_result))
return float(eval("*".join(result_stack))) | Calculate the result of the given postfix expression |
ClassEval_39_sum | import re
from collections import deque
from decimal import Decimal
class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def calculate(self, expression):
"""
Calculate the result of the given postfix expression
:param expression: string, the postfix expression to be calculated
:return: float, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.calculate("2 + 3 * 4")
14.0
"""
self.prepare(self.transform(expression))
result_stack = deque()
self.postfix_stack.reverse()
while self.postfix_stack:
current_op = self.postfix_stack.pop()
if not self.is_operator(current_op):
current_op = current_op.replace("~", "-")
result_stack.append(current_op)
else:
second_value = result_stack.pop()
first_value = result_stack.pop()
first_value = first_value.replace("~", "-")
second_value = second_value.replace("~", "-")
temp_result = self._calculate(first_value, second_value, current_op)
result_stack.append(str(temp_result))
return float(eval("*".join(result_stack)))
@staticmethod
def is_operator(c):
"""
Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}
:param c: string, the character to be checked
:return: bool, True if the character is an operator, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.is_operator("+")
True
"""
return c in {'+', '-', '*', '/', '(', ')', '%'}
def compare(self, cur, peek):
"""
Compare the precedence of two operators
:param cur: string, the current operator
:param peek: string, the operator at the top of the operator stack
:return: bool, True if the current operator has higher or equal precedence, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.compare("+", "-")
True
"""
if cur == '%':
cur = '/'
if peek == '%':
peek = '/'
return self.operat_priority[ord(peek) - 40] >= self.operat_priority[ord(cur) - 40]
@staticmethod
def _calculate(first_value, second_value, current_op):
"""
Perform the mathematical calculation based on the given operands and operator
:param first_value: string, the first operand
:param second_value: string, the second operand
:param current_op: string, the operator
:return: decimal.Decimal, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator._calculate("2", "3", "+")
5.0
"""
if current_op == '+':
return Decimal(first_value) + Decimal(second_value)
elif current_op == '-':
return Decimal(first_value) - Decimal(second_value)
elif current_op == '*':
return Decimal(first_value) * Decimal(second_value)
elif current_op == '/':
return Decimal(first_value) / Decimal(second_value)
elif current_op == '%':
return Decimal(first_value) % Decimal(second_value)
else:
raise ValueError("Unexpected operator: {}".format(current_op))
@staticmethod
def transform(expression):
"""
Transform the infix expression to a format suitable for conversion
:param expression: string, the infix expression to be transformed
:return: string, the transformed expression
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.transform("2 + 3 * 4")
"2+3*4"
"""
expression = re.sub(r"\s+", "", expression)
expression = re.sub(r"=$", "", expression)
arr = list(expression)
for i, c in enumerate(arr):
if c == '-':
if i == 0:
arr[i] = '~'
else:
prev_c = arr[i - 1]
if prev_c in {'+', '-', '*', '/', '(', 'E', 'e'}:
arr[i] = '~'
if arr[0] == '~' and (len(arr) > 1 and arr[1] == '('):
arr[0] = '-'
return "0" + "".join(arr)
else:
return "".join(arr) | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def calculate(self, expression):
"""
Calculate the result of the given postfix expression
:param expression: string, the postfix expression to be calculated
:return: float, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.calculate("2 + 3 * 4")
14.0
"""
@staticmethod
def is_operator(c):
"""
Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}
:param c: string, the character to be checked
:return: bool, True if the character is an operator, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.is_operator("+")
True
"""
def compare(self, cur, peek):
"""
Compare the precedence of two operators
:param cur: string, the current operator
:param peek: string, the operator at the top of the operator stack
:return: bool, True if the current operator has higher or equal precedence, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.compare("+", "-")
True
"""
@staticmethod
def _calculate(first_value, second_value, current_op):
"""
Perform the mathematical calculation based on the given operands and operator
:param first_value: string, the first operand
:param second_value: string, the second operand
:param current_op: string, the operator
:return: decimal.Decimal, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator._calculate("2", "3", "+")
5.0
"""
@staticmethod
def transform(expression):
"""
Transform the infix expression to a format suitable for conversion
:param expression: string, the infix expression to be transformed
:return: string, the transformed expression
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.transform("2 + 3 * 4")
"2+3*4"
""" | def prepare(self, expression):
op_stack = deque([','])
arr = list(expression)
current_index = 0
count = 0
for i, current_op in enumerate(arr):
if self.is_operator(current_op):
if count > 0:
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
peek_op = op_stack[-1]
if current_op == ')':
while op_stack[-1] != '(':
self.postfix_stack.append(str(op_stack.pop()))
op_stack.pop()
else:
while current_op != '(' and peek_op != ',' and self.compare(current_op, peek_op):
self.postfix_stack.append(str(op_stack.pop()))
peek_op = op_stack[-1]
op_stack.append(current_op)
count = 0
current_index = i + 1
else:
count += 1
if count > 1 or (count == 1 and not self.is_operator(arr[current_index])):
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
while op_stack[-1] != ',':
self.postfix_stack.append(str(op_stack.pop())) | Prepare the infix expression for conversion to postfix notation |
ClassEval_39_sum | import re
from collections import deque
from decimal import Decimal
class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def calculate(self, expression):
"""
Calculate the result of the given postfix expression
:param expression: string, the postfix expression to be calculated
:return: float, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.calculate("2 + 3 * 4")
14.0
"""
self.prepare(self.transform(expression))
result_stack = deque()
self.postfix_stack.reverse()
while self.postfix_stack:
current_op = self.postfix_stack.pop()
if not self.is_operator(current_op):
current_op = current_op.replace("~", "-")
result_stack.append(current_op)
else:
second_value = result_stack.pop()
first_value = result_stack.pop()
first_value = first_value.replace("~", "-")
second_value = second_value.replace("~", "-")
temp_result = self._calculate(first_value, second_value, current_op)
result_stack.append(str(temp_result))
return float(eval("*".join(result_stack)))
def prepare(self, expression):
"""
Prepare the infix expression for conversion to postfix notation
:param expression: string, the infix expression to be prepared
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.prepare("2+3*4")
expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']
"""
op_stack = deque([','])
arr = list(expression)
current_index = 0
count = 0
for i, current_op in enumerate(arr):
if self.is_operator(current_op):
if count > 0:
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
peek_op = op_stack[-1]
if current_op == ')':
while op_stack[-1] != '(':
self.postfix_stack.append(str(op_stack.pop()))
op_stack.pop()
else:
while current_op != '(' and peek_op != ',' and self.compare(current_op, peek_op):
self.postfix_stack.append(str(op_stack.pop()))
peek_op = op_stack[-1]
op_stack.append(current_op)
count = 0
current_index = i + 1
else:
count += 1
if count > 1 or (count == 1 and not self.is_operator(arr[current_index])):
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
while op_stack[-1] != ',':
self.postfix_stack.append(str(op_stack.pop()))
def compare(self, cur, peek):
"""
Compare the precedence of two operators
:param cur: string, the current operator
:param peek: string, the operator at the top of the operator stack
:return: bool, True if the current operator has higher or equal precedence, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.compare("+", "-")
True
"""
if cur == '%':
cur = '/'
if peek == '%':
peek = '/'
return self.operat_priority[ord(peek) - 40] >= self.operat_priority[ord(cur) - 40]
@staticmethod
def _calculate(first_value, second_value, current_op):
"""
Perform the mathematical calculation based on the given operands and operator
:param first_value: string, the first operand
:param second_value: string, the second operand
:param current_op: string, the operator
:return: decimal.Decimal, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator._calculate("2", "3", "+")
5.0
"""
if current_op == '+':
return Decimal(first_value) + Decimal(second_value)
elif current_op == '-':
return Decimal(first_value) - Decimal(second_value)
elif current_op == '*':
return Decimal(first_value) * Decimal(second_value)
elif current_op == '/':
return Decimal(first_value) / Decimal(second_value)
elif current_op == '%':
return Decimal(first_value) % Decimal(second_value)
else:
raise ValueError("Unexpected operator: {}".format(current_op))
@staticmethod
def transform(expression):
"""
Transform the infix expression to a format suitable for conversion
:param expression: string, the infix expression to be transformed
:return: string, the transformed expression
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.transform("2 + 3 * 4")
"2+3*4"
"""
expression = re.sub(r"\s+", "", expression)
expression = re.sub(r"=$", "", expression)
arr = list(expression)
for i, c in enumerate(arr):
if c == '-':
if i == 0:
arr[i] = '~'
else:
prev_c = arr[i - 1]
if prev_c in {'+', '-', '*', '/', '(', 'E', 'e'}:
arr[i] = '~'
if arr[0] == '~' and (len(arr) > 1 and arr[1] == '('):
arr[0] = '-'
return "0" + "".join(arr)
else:
return "".join(arr) | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def calculate(self, expression):
"""
Calculate the result of the given postfix expression
:param expression: string, the postfix expression to be calculated
:return: float, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.calculate("2 + 3 * 4")
14.0
"""
def prepare(self, expression):
"""
Prepare the infix expression for conversion to postfix notation
:param expression: string, the infix expression to be prepared
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.prepare("2+3*4")
expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']
"""
def compare(self, cur, peek):
"""
Compare the precedence of two operators
:param cur: string, the current operator
:param peek: string, the operator at the top of the operator stack
:return: bool, True if the current operator has higher or equal precedence, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.compare("+", "-")
True
"""
@staticmethod
def _calculate(first_value, second_value, current_op):
"""
Perform the mathematical calculation based on the given operands and operator
:param first_value: string, the first operand
:param second_value: string, the second operand
:param current_op: string, the operator
:return: decimal.Decimal, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator._calculate("2", "3", "+")
5.0
"""
@staticmethod
def transform(expression):
"""
Transform the infix expression to a format suitable for conversion
:param expression: string, the infix expression to be transformed
:return: string, the transformed expression
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.transform("2 + 3 * 4")
"2+3*4"
""" | @staticmethod
def is_operator(c):
return c in {'+', '-', '*', '/', '(', ')', '%'} | Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'} |
ClassEval_39_sum | import re
from collections import deque
from decimal import Decimal
class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def calculate(self, expression):
"""
Calculate the result of the given postfix expression
:param expression: string, the postfix expression to be calculated
:return: float, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.calculate("2 + 3 * 4")
14.0
"""
self.prepare(self.transform(expression))
result_stack = deque()
self.postfix_stack.reverse()
while self.postfix_stack:
current_op = self.postfix_stack.pop()
if not self.is_operator(current_op):
current_op = current_op.replace("~", "-")
result_stack.append(current_op)
else:
second_value = result_stack.pop()
first_value = result_stack.pop()
first_value = first_value.replace("~", "-")
second_value = second_value.replace("~", "-")
temp_result = self._calculate(first_value, second_value, current_op)
result_stack.append(str(temp_result))
return float(eval("*".join(result_stack)))
def prepare(self, expression):
"""
Prepare the infix expression for conversion to postfix notation
:param expression: string, the infix expression to be prepared
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.prepare("2+3*4")
expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']
"""
op_stack = deque([','])
arr = list(expression)
current_index = 0
count = 0
for i, current_op in enumerate(arr):
if self.is_operator(current_op):
if count > 0:
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
peek_op = op_stack[-1]
if current_op == ')':
while op_stack[-1] != '(':
self.postfix_stack.append(str(op_stack.pop()))
op_stack.pop()
else:
while current_op != '(' and peek_op != ',' and self.compare(current_op, peek_op):
self.postfix_stack.append(str(op_stack.pop()))
peek_op = op_stack[-1]
op_stack.append(current_op)
count = 0
current_index = i + 1
else:
count += 1
if count > 1 or (count == 1 and not self.is_operator(arr[current_index])):
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
while op_stack[-1] != ',':
self.postfix_stack.append(str(op_stack.pop()))
@staticmethod
def is_operator(c):
"""
Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}
:param c: string, the character to be checked
:return: bool, True if the character is an operator, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.is_operator("+")
True
"""
return c in {'+', '-', '*', '/', '(', ')', '%'}
@staticmethod
def _calculate(first_value, second_value, current_op):
"""
Perform the mathematical calculation based on the given operands and operator
:param first_value: string, the first operand
:param second_value: string, the second operand
:param current_op: string, the operator
:return: decimal.Decimal, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator._calculate("2", "3", "+")
5.0
"""
if current_op == '+':
return Decimal(first_value) + Decimal(second_value)
elif current_op == '-':
return Decimal(first_value) - Decimal(second_value)
elif current_op == '*':
return Decimal(first_value) * Decimal(second_value)
elif current_op == '/':
return Decimal(first_value) / Decimal(second_value)
elif current_op == '%':
return Decimal(first_value) % Decimal(second_value)
else:
raise ValueError("Unexpected operator: {}".format(current_op))
@staticmethod
def transform(expression):
"""
Transform the infix expression to a format suitable for conversion
:param expression: string, the infix expression to be transformed
:return: string, the transformed expression
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.transform("2 + 3 * 4")
"2+3*4"
"""
expression = re.sub(r"\s+", "", expression)
expression = re.sub(r"=$", "", expression)
arr = list(expression)
for i, c in enumerate(arr):
if c == '-':
if i == 0:
arr[i] = '~'
else:
prev_c = arr[i - 1]
if prev_c in {'+', '-', '*', '/', '(', 'E', 'e'}:
arr[i] = '~'
if arr[0] == '~' and (len(arr) > 1 and arr[1] == '('):
arr[0] = '-'
return "0" + "".join(arr)
else:
return "".join(arr) | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def calculate(self, expression):
"""
Calculate the result of the given postfix expression
:param expression: string, the postfix expression to be calculated
:return: float, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.calculate("2 + 3 * 4")
14.0
"""
def prepare(self, expression):
"""
Prepare the infix expression for conversion to postfix notation
:param expression: string, the infix expression to be prepared
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.prepare("2+3*4")
expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']
"""
@staticmethod
def is_operator(c):
"""
Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}
:param c: string, the character to be checked
:return: bool, True if the character is an operator, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.is_operator("+")
True
"""
@staticmethod
def _calculate(first_value, second_value, current_op):
"""
Perform the mathematical calculation based on the given operands and operator
:param first_value: string, the first operand
:param second_value: string, the second operand
:param current_op: string, the operator
:return: decimal.Decimal, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator._calculate("2", "3", "+")
5.0
"""
@staticmethod
def transform(expression):
"""
Transform the infix expression to a format suitable for conversion
:param expression: string, the infix expression to be transformed
:return: string, the transformed expression
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.transform("2 + 3 * 4")
"2+3*4"
""" | def compare(self, cur, peek):
if cur == '%':
cur = '/'
if peek == '%':
peek = '/'
return self.operat_priority[ord(peek) - 40] >= self.operat_priority[ord(cur) - 40] | Compare the precedence of two operators |
ClassEval_39_sum | import re
from collections import deque
from decimal import Decimal
class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def calculate(self, expression):
"""
Calculate the result of the given postfix expression
:param expression: string, the postfix expression to be calculated
:return: float, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.calculate("2 + 3 * 4")
14.0
"""
self.prepare(self.transform(expression))
result_stack = deque()
self.postfix_stack.reverse()
while self.postfix_stack:
current_op = self.postfix_stack.pop()
if not self.is_operator(current_op):
current_op = current_op.replace("~", "-")
result_stack.append(current_op)
else:
second_value = result_stack.pop()
first_value = result_stack.pop()
first_value = first_value.replace("~", "-")
second_value = second_value.replace("~", "-")
temp_result = self._calculate(first_value, second_value, current_op)
result_stack.append(str(temp_result))
return float(eval("*".join(result_stack)))
def prepare(self, expression):
"""
Prepare the infix expression for conversion to postfix notation
:param expression: string, the infix expression to be prepared
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.prepare("2+3*4")
expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']
"""
op_stack = deque([','])
arr = list(expression)
current_index = 0
count = 0
for i, current_op in enumerate(arr):
if self.is_operator(current_op):
if count > 0:
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
peek_op = op_stack[-1]
if current_op == ')':
while op_stack[-1] != '(':
self.postfix_stack.append(str(op_stack.pop()))
op_stack.pop()
else:
while current_op != '(' and peek_op != ',' and self.compare(current_op, peek_op):
self.postfix_stack.append(str(op_stack.pop()))
peek_op = op_stack[-1]
op_stack.append(current_op)
count = 0
current_index = i + 1
else:
count += 1
if count > 1 or (count == 1 and not self.is_operator(arr[current_index])):
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
while op_stack[-1] != ',':
self.postfix_stack.append(str(op_stack.pop()))
@staticmethod
def is_operator(c):
"""
Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}
:param c: string, the character to be checked
:return: bool, True if the character is an operator, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.is_operator("+")
True
"""
return c in {'+', '-', '*', '/', '(', ')', '%'}
def compare(self, cur, peek):
"""
Compare the precedence of two operators
:param cur: string, the current operator
:param peek: string, the operator at the top of the operator stack
:return: bool, True if the current operator has higher or equal precedence, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.compare("+", "-")
True
"""
if cur == '%':
cur = '/'
if peek == '%':
peek = '/'
return self.operat_priority[ord(peek) - 40] >= self.operat_priority[ord(cur) - 40]
@staticmethod
def transform(expression):
"""
Transform the infix expression to a format suitable for conversion
:param expression: string, the infix expression to be transformed
:return: string, the transformed expression
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.transform("2 + 3 * 4")
"2+3*4"
"""
expression = re.sub(r"\s+", "", expression)
expression = re.sub(r"=$", "", expression)
arr = list(expression)
for i, c in enumerate(arr):
if c == '-':
if i == 0:
arr[i] = '~'
else:
prev_c = arr[i - 1]
if prev_c in {'+', '-', '*', '/', '(', 'E', 'e'}:
arr[i] = '~'
if arr[0] == '~' and (len(arr) > 1 and arr[1] == '('):
arr[0] = '-'
return "0" + "".join(arr)
else:
return "".join(arr) | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def calculate(self, expression):
"""
Calculate the result of the given postfix expression
:param expression: string, the postfix expression to be calculated
:return: float, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.calculate("2 + 3 * 4")
14.0
"""
def prepare(self, expression):
"""
Prepare the infix expression for conversion to postfix notation
:param expression: string, the infix expression to be prepared
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.prepare("2+3*4")
expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']
"""
@staticmethod
def is_operator(c):
"""
Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}
:param c: string, the character to be checked
:return: bool, True if the character is an operator, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.is_operator("+")
True
"""
def compare(self, cur, peek):
"""
Compare the precedence of two operators
:param cur: string, the current operator
:param peek: string, the operator at the top of the operator stack
:return: bool, True if the current operator has higher or equal precedence, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.compare("+", "-")
True
"""
@staticmethod
def transform(expression):
"""
Transform the infix expression to a format suitable for conversion
:param expression: string, the infix expression to be transformed
:return: string, the transformed expression
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.transform("2 + 3 * 4")
"2+3*4"
""" | @staticmethod
def _calculate(first_value, second_value, current_op):
if current_op == '+':
return Decimal(first_value) + Decimal(second_value)
elif current_op == '-':
return Decimal(first_value) - Decimal(second_value)
elif current_op == '*':
return Decimal(first_value) * Decimal(second_value)
elif current_op == '/':
return Decimal(first_value) / Decimal(second_value)
elif current_op == '%':
return Decimal(first_value) % Decimal(second_value)
else:
raise ValueError("Unexpected operator: {}".format(current_op)) | Perform the mathematical calculation based on the given operands and operator |
ClassEval_39_sum | import re
from collections import deque
from decimal import Decimal
class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def calculate(self, expression):
"""
Calculate the result of the given postfix expression
:param expression: string, the postfix expression to be calculated
:return: float, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.calculate("2 + 3 * 4")
14.0
"""
self.prepare(self.transform(expression))
result_stack = deque()
self.postfix_stack.reverse()
while self.postfix_stack:
current_op = self.postfix_stack.pop()
if not self.is_operator(current_op):
current_op = current_op.replace("~", "-")
result_stack.append(current_op)
else:
second_value = result_stack.pop()
first_value = result_stack.pop()
first_value = first_value.replace("~", "-")
second_value = second_value.replace("~", "-")
temp_result = self._calculate(first_value, second_value, current_op)
result_stack.append(str(temp_result))
return float(eval("*".join(result_stack)))
def prepare(self, expression):
"""
Prepare the infix expression for conversion to postfix notation
:param expression: string, the infix expression to be prepared
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.prepare("2+3*4")
expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']
"""
op_stack = deque([','])
arr = list(expression)
current_index = 0
count = 0
for i, current_op in enumerate(arr):
if self.is_operator(current_op):
if count > 0:
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
peek_op = op_stack[-1]
if current_op == ')':
while op_stack[-1] != '(':
self.postfix_stack.append(str(op_stack.pop()))
op_stack.pop()
else:
while current_op != '(' and peek_op != ',' and self.compare(current_op, peek_op):
self.postfix_stack.append(str(op_stack.pop()))
peek_op = op_stack[-1]
op_stack.append(current_op)
count = 0
current_index = i + 1
else:
count += 1
if count > 1 or (count == 1 and not self.is_operator(arr[current_index])):
self.postfix_stack.append("".join(arr[current_index: current_index + count]))
while op_stack[-1] != ',':
self.postfix_stack.append(str(op_stack.pop()))
@staticmethod
def is_operator(c):
"""
Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}
:param c: string, the character to be checked
:return: bool, True if the character is an operator, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.is_operator("+")
True
"""
return c in {'+', '-', '*', '/', '(', ')', '%'}
def compare(self, cur, peek):
"""
Compare the precedence of two operators
:param cur: string, the current operator
:param peek: string, the operator at the top of the operator stack
:return: bool, True if the current operator has higher or equal precedence, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.compare("+", "-")
True
"""
if cur == '%':
cur = '/'
if peek == '%':
peek = '/'
return self.operat_priority[ord(peek) - 40] >= self.operat_priority[ord(cur) - 40]
@staticmethod
def _calculate(first_value, second_value, current_op):
"""
Perform the mathematical calculation based on the given operands and operator
:param first_value: string, the first operand
:param second_value: string, the second operand
:param current_op: string, the operator
:return: decimal.Decimal, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator._calculate("2", "3", "+")
5.0
"""
if current_op == '+':
return Decimal(first_value) + Decimal(second_value)
elif current_op == '-':
return Decimal(first_value) - Decimal(second_value)
elif current_op == '*':
return Decimal(first_value) * Decimal(second_value)
elif current_op == '/':
return Decimal(first_value) / Decimal(second_value)
elif current_op == '%':
return Decimal(first_value) % Decimal(second_value)
else:
raise ValueError("Unexpected operator: {}".format(current_op))
@staticmethod
def transform(expression):
expression = re.sub(r"\s+", "", expression)
expression = re.sub(r"=$", "", expression)
arr = list(expression)
for i, c in enumerate(arr):
if c == '-':
if i == 0:
arr[i] = '~'
else:
prev_c = arr[i - 1]
if prev_c in {'+', '-', '*', '/', '(', 'E', 'e'}:
arr[i] = '~'
if arr[0] == '~' and (len(arr) > 1 and arr[1] == '('):
arr[0] = '-'
return "0" + "".join(arr)
else:
return "".join(arr) | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.postfix_stack = deque()
self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]
def calculate(self, expression):
"""
Calculate the result of the given postfix expression
:param expression: string, the postfix expression to be calculated
:return: float, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.calculate("2 + 3 * 4")
14.0
"""
def prepare(self, expression):
"""
Prepare the infix expression for conversion to postfix notation
:param expression: string, the infix expression to be prepared
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.prepare("2+3*4")
expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']
"""
@staticmethod
def is_operator(c):
"""
Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}
:param c: string, the character to be checked
:return: bool, True if the character is an operator, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.is_operator("+")
True
"""
def compare(self, cur, peek):
"""
Compare the precedence of two operators
:param cur: string, the current operator
:param peek: string, the operator at the top of the operator stack
:return: bool, True if the current operator has higher or equal precedence, False otherwise
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.compare("+", "-")
True
"""
@staticmethod
def _calculate(first_value, second_value, current_op):
"""
Perform the mathematical calculation based on the given operands and operator
:param first_value: string, the first operand
:param second_value: string, the second operand
:param current_op: string, the operator
:return: decimal.Decimal, the calculated result
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator._calculate("2", "3", "+")
5.0
"""
@staticmethod
def transform(expression):
"""
Transform the infix expression to a format suitable for conversion
:param expression: string, the infix expression to be transformed
:return: string, the transformed expression
>>> expression_calculator = ExpressionCalculator()
>>> expression_calculator.transform("2 + 3 * 4")
"2+3*4"
""" | @staticmethod
def transform(expression):
expression = re.sub(r"\s+", "", expression)
expression = re.sub(r"=$", "", expression)
arr = list(expression)
for i, c in enumerate(arr):
if c == '-':
if i == 0:
arr[i] = '~'
else:
prev_c = arr[i - 1]
if prev_c in {'+', '-', '*', '/', '(', 'E', 'e'}:
arr[i] = '~'
if arr[0] == '~' and (len(arr) > 1 and arr[1] == '('):
arr[0] = '-'
return "0" + "".join(arr)
else:
return "".join(arr) | Transform the infix expression to a format suitable for conversion |
ClassEval_40_sum | class FitnessTracker:
"""
This is a class as fitness tracker that implements to calculate BMI (Body Mass Index) and calorie intake based on the user's height, weight, age, and sex.
"""
def __init__(self, height, weight, age, sex) -> None:
self.height = height
self.weight = weight
self.age = age
self.sex = sex
self.BMI_std = [
{"male": [20, 25]},
{"female": [19, 24]}
]
def condition_judge(self):
"""
Judge the condition of the user based on the BMI standard.
:return: 1 if the user is too fat, -1 if the user is too thin, 0 if the user is normal, int.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.condition_judge()
-1
"""
BMI = self.get_BMI()
if self.sex == "male":
BMI_range = self.BMI_std[0]["male"]
else:
BMI_range = self.BMI_std[1]["female"]
if BMI > BMI_range[1]:
# too fat
return 1
elif BMI < BMI_range[0]:
# too thin
return -1
else:
# normal
return 0
def calculate_calorie_intake(self):
"""
Calculate the calorie intake based on the user's condition and BMR (Basal Metabolic Rate),BMR is calculated based on the user's height, weight, age, and sex,male is10 * self.weight + 6.25 * self.height - 5 * self.age + 5,female is 10 * self.weight + 6.25 * self.height - 5 * self.age - 161, and the calorie intake is calculated based on the BMR and the user's condition,if the user is too fat, the calorie intake is BMR * 1.2, if the user is too thin, the calorie intake is BMR * 1.6, if the user is normal, the calorie intake is BMR * 1.4.
:return: calorie intake, float.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.calculate_calorie_intake()
986.0
"""
if self.sex == "male":
BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age + 5
else:
BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age - 161
if self.condition_judge() == 1:
calorie_intake = BMR * 1.2 # Sedentary lifestyle
elif self.condition_judge() == -1:
calorie_intake = BMR * 1.6 # Active lifestyle
else:
calorie_intake = BMR * 1.4 # Moderate lifestyle
return calorie_intake | class FitnessTracker:
"""
This is a class as fitness tracker that implements to calculate BMI (Body Mass Index) and calorie intake based on the user's height, weight, age, and sex.
"""
def __init__(self, height, weight, age, sex) -> None:
"""
Initialize the class with height, weight, age, and sex, and calculate the BMI standard based on sex, and male is 20-25, female is 19-24.
"""
self.height = height
self.weight = weight
self.age = age
self.sex = sex
self.BMI_std = [
{"male": [20, 25]},
{"female": [19, 24]}
]
def condition_judge(self):
"""
Judge the condition of the user based on the BMI standard.
:return: 1 if the user is too fat, -1 if the user is too thin, 0 if the user is normal, int.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.condition_judge()
-1
"""
def calculate_calorie_intake(self):
"""
Calculate the calorie intake based on the user's condition and BMR (Basal Metabolic Rate),BMR is calculated based on the user's height, weight, age, and sex,male is10 * self.weight + 6.25 * self.height - 5 * self.age + 5,female is 10 * self.weight + 6.25 * self.height - 5 * self.age - 161, and the calorie intake is calculated based on the BMR and the user's condition,if the user is too fat, the calorie intake is BMR * 1.2, if the user is too thin, the calorie intake is BMR * 1.6, if the user is normal, the calorie intake is BMR * 1.4.
:return: calorie intake, float.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.calculate_calorie_intake()
986.0
""" | def get_BMI(self):
return self.weight / self.height ** 2 | Calculate the BMI based on the height and weight. |
ClassEval_40_sum | class FitnessTracker:
"""
This is a class as fitness tracker that implements to calculate BMI (Body Mass Index) and calorie intake based on the user's height, weight, age, and sex.
"""
def __init__(self, height, weight, age, sex) -> None:
self.height = height
self.weight = weight
self.age = age
self.sex = sex
self.BMI_std = [
{"male": [20, 25]},
{"female": [19, 24]}
]
def get_BMI(self):
"""
Calculate the BMI based on the height and weight.
:return: BMI,which is the weight divide by the square of height, float.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.get_BMI()
21.604938271604937
"""
return self.weight / self.height ** 2
def calculate_calorie_intake(self):
"""
Calculate the calorie intake based on the user's condition and BMR (Basal Metabolic Rate),BMR is calculated based on the user's height, weight, age, and sex,male is10 * self.weight + 6.25 * self.height - 5 * self.age + 5,female is 10 * self.weight + 6.25 * self.height - 5 * self.age - 161, and the calorie intake is calculated based on the BMR and the user's condition,if the user is too fat, the calorie intake is BMR * 1.2, if the user is too thin, the calorie intake is BMR * 1.6, if the user is normal, the calorie intake is BMR * 1.4.
:return: calorie intake, float.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.calculate_calorie_intake()
986.0
"""
if self.sex == "male":
BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age + 5
else:
BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age - 161
if self.condition_judge() == 1:
calorie_intake = BMR * 1.2 # Sedentary lifestyle
elif self.condition_judge() == -1:
calorie_intake = BMR * 1.6 # Active lifestyle
else:
calorie_intake = BMR * 1.4 # Moderate lifestyle
return calorie_intake | class FitnessTracker:
"""
This is a class as fitness tracker that implements to calculate BMI (Body Mass Index) and calorie intake based on the user's height, weight, age, and sex.
"""
def __init__(self, height, weight, age, sex) -> None:
"""
Initialize the class with height, weight, age, and sex, and calculate the BMI standard based on sex, and male is 20-25, female is 19-24.
"""
self.height = height
self.weight = weight
self.age = age
self.sex = sex
self.BMI_std = [
{"male": [20, 25]},
{"female": [19, 24]}
]
def get_BMI(self):
"""
Calculate the BMI based on the height and weight.
:return: BMI,which is the weight divide by the square of height, float.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.get_BMI()
21.604938271604937
"""
def calculate_calorie_intake(self):
"""
Calculate the calorie intake based on the user's condition and BMR (Basal Metabolic Rate),BMR is calculated based on the user's height, weight, age, and sex,male is10 * self.weight + 6.25 * self.height - 5 * self.age + 5,female is 10 * self.weight + 6.25 * self.height - 5 * self.age - 161, and the calorie intake is calculated based on the BMR and the user's condition,if the user is too fat, the calorie intake is BMR * 1.2, if the user is too thin, the calorie intake is BMR * 1.6, if the user is normal, the calorie intake is BMR * 1.4.
:return: calorie intake, float.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.calculate_calorie_intake()
986.0
""" | def condition_judge(self):
BMI = self.get_BMI()
if self.sex == "male":
BMI_range = self.BMI_std[0]["male"]
else:
BMI_range = self.BMI_std[1]["female"]
if BMI > BMI_range[1]:
# too fat
return 1
elif BMI < BMI_range[0]:
# too thin
return -1
else:
# normal
return 0 | Judge the condition of the user based on the BMI standard. |
ClassEval_40_sum | class FitnessTracker:
"""
This is a class as fitness tracker that implements to calculate BMI (Body Mass Index) and calorie intake based on the user's height, weight, age, and sex.
"""
def __init__(self, height, weight, age, sex) -> None:
self.height = height
self.weight = weight
self.age = age
self.sex = sex
self.BMI_std = [
{"male": [20, 25]},
{"female": [19, 24]}
]
def get_BMI(self):
"""
Calculate the BMI based on the height and weight.
:return: BMI,which is the weight divide by the square of height, float.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.get_BMI()
21.604938271604937
"""
return self.weight / self.height ** 2
def condition_judge(self):
"""
Judge the condition of the user based on the BMI standard.
:return: 1 if the user is too fat, -1 if the user is too thin, 0 if the user is normal, int.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.condition_judge()
-1
"""
BMI = self.get_BMI()
if self.sex == "male":
BMI_range = self.BMI_std[0]["male"]
else:
BMI_range = self.BMI_std[1]["female"]
if BMI > BMI_range[1]:
# too fat
return 1
elif BMI < BMI_range[0]:
# too thin
return -1
else:
# normal
return 0
def calculate_calorie_intake(self):
if self.sex == "male":
BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age + 5
else:
BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age - 161
if self.condition_judge() == 1:
calorie_intake = BMR * 1.2 # Sedentary lifestyle
elif self.condition_judge() == -1:
calorie_intake = BMR * 1.6 # Active lifestyle
else:
calorie_intake = BMR * 1.4 # Moderate lifestyle
return calorie_intake | class FitnessTracker:
"""
This is a class as fitness tracker that implements to calculate BMI (Body Mass Index) and calorie intake based on the user's height, weight, age, and sex.
"""
def __init__(self, height, weight, age, sex) -> None:
"""
Initialize the class with height, weight, age, and sex, and calculate the BMI standard based on sex, and male is 20-25, female is 19-24.
"""
self.height = height
self.weight = weight
self.age = age
self.sex = sex
self.BMI_std = [
{"male": [20, 25]},
{"female": [19, 24]}
]
def get_BMI(self):
"""
Calculate the BMI based on the height and weight.
:return: BMI,which is the weight divide by the square of height, float.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.get_BMI()
21.604938271604937
"""
def condition_judge(self):
"""
Judge the condition of the user based on the BMI standard.
:return: 1 if the user is too fat, -1 if the user is too thin, 0 if the user is normal, int.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.condition_judge()
-1
"""
def calculate_calorie_intake(self):
"""
Calculate the calorie intake based on the user's condition and BMR (Basal Metabolic Rate),BMR is calculated based on the user's height, weight, age, and sex,male is10 * self.weight + 6.25 * self.height - 5 * self.age + 5,female is 10 * self.weight + 6.25 * self.height - 5 * self.age - 161, and the calorie intake is calculated based on the BMR and the user's condition,if the user is too fat, the calorie intake is BMR * 1.2, if the user is too thin, the calorie intake is BMR * 1.6, if the user is normal, the calorie intake is BMR * 1.4.
:return: calorie intake, float.
>>> fitnessTracker = FitnessTracker(1.8, 70, 20, "male")
>>> fitnessTracker.calculate_calorie_intake()
986.0
""" | def calculate_calorie_intake(self):
if self.sex == "male":
BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age + 5
else:
BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age - 161
if self.condition_judge() == 1:
calorie_intake = BMR * 1.2 # Sedentary lifestyle
elif self.condition_judge() == -1:
calorie_intake = BMR * 1.6 # Active lifestyle
else:
calorie_intake = BMR * 1.4 # Moderate lifestyle
return calorie_intake | Calculate the calorie intake based on the user's condition and BMR (Basal Metabolic Rate),BMR is calculated based on the user's height, weight, age, and sex,male is10 * self.weight + 6.25 * self.height - 5 * self.age + 5,female is 10 * self.weight + 6.25 * self.height - 5 * self.age - 161, and the calorie intake is calculated based on the BMR and the user's condition,if the user is too fat, the calorie intake is BMR * 1.2, if the user is too thin, the calorie intake is BMR * 1.6, if the user is normal, the calorie intake is BMR * 1.4. |
ClassEval_41_sum | class GomokuGame:
"""
This class is an implementation of a Gomoku game, supporting for making moves, checking for a winner, and checking if there are five consecutive symbols on the game board.
"""
def __init__(self, board_size):
self.board_size = board_size
self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)]
self.current_player = 'X'
def check_winner(self):
"""
Checks if there is a winner by looking for five in a row in all directions (horizontal, vertical, diagonal).
return: the symbol of the winning player (either 'X' or 'O') if there is a winner, or None otherwise.
>>> gomokuGame = GomokuGame(10)
>>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
>>> for move in moves:
... gomokuGame.make_move(move[0], move[1])
>>> gomokuGame.check_winner()
'X'
"""
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
for row in range(self.board_size):
for col in range(self.board_size):
if self.board[row][col] != ' ':
for direction in directions:
if self._check_five_in_a_row(row, col, direction):
return self.board[row][col]
return None
def _check_five_in_a_row(self, row, col, direction):
"""
checks if there are five consecutive symbols of the same player in a row starting from a given cell in a given direction (horizontal, vertical, diagonal).
Counts the number of consecutive symbols in that direction starting from the given cell,
:param row: int, row of the given cell
:param col: int, column of the given cell
:param direction: tuple, (int, int), named as (dx, dy). Row and col will plus several dx and dy repectively.
:return: True if there are five consecutive symbols of the same player, and False otherwise.
>>> gomokuGame = GomokuGame(10)
>>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
>>> for move in moves:
... gomokuGame.make_move(move[0], move[1])
>>> gomokuGame._check_five_in_a_row(5, 1, (0, 1))
True
>>> gomokuGame._check_five_in_a_row(5, 1, (1, 1))
False
"""
dx, dy = direction
count = 1
symbol = self.board[row][col]
for i in range(1, 5):
new_row = row + dx * i
new_col = col + dy * i
if not (0 <= new_row < self.board_size and 0 <= new_col < self.board_size):
return False
if self.board[new_row][new_col] != symbol:
return False
count += 1
return count == 5 | class GomokuGame:
"""
This class is an implementation of a Gomoku game, supporting for making moves, checking for a winner, and checking if there are five consecutive symbols on the game board.
"""
def __init__(self, board_size):
"""
Initializes the game with a given board size.
It initializes the board with empty spaces and sets the current player symble as 'X'.
"""
self.board_size = board_size
self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)]
self.current_player = 'X'
def check_winner(self):
"""
Checks if there is a winner by looking for five in a row in all directions (horizontal, vertical, diagonal).
return: the symbol of the winning player (either 'X' or 'O') if there is a winner, or None otherwise.
>>> gomokuGame = GomokuGame(10)
>>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
>>> for move in moves:
... gomokuGame.make_move(move[0], move[1])
>>> gomokuGame.check_winner()
'X'
"""
def _check_five_in_a_row(self, row, col, direction):
"""
checks if there are five consecutive symbols of the same player in a row starting from a given cell in a given direction (horizontal, vertical, diagonal).
Counts the number of consecutive symbols in that direction starting from the given cell,
:param row: int, row of the given cell
:param col: int, column of the given cell
:param direction: tuple, (int, int), named as (dx, dy). Row and col will plus several dx and dy repectively.
:return: True if there are five consecutive symbols of the same player, and False otherwise.
>>> gomokuGame = GomokuGame(10)
>>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
>>> for move in moves:
... gomokuGame.make_move(move[0], move[1])
>>> gomokuGame._check_five_in_a_row(5, 1, (0, 1))
True
>>> gomokuGame._check_five_in_a_row(5, 1, (1, 1))
False
""" | def make_move(self, row, col):
if self.board[row][col] == ' ':
self.board[row][col] = self.current_player
self.current_player = 'O' if self.current_player == 'X' else 'X'
return True
return False | Makes a move at the given row and column. If the move is valid, it places the current player's symbol on the board and changes the current player to the other player (if the current player is 'X', then it becomes 'O' and vice versa). |
ClassEval_41_sum | class GomokuGame:
"""
This class is an implementation of a Gomoku game, supporting for making moves, checking for a winner, and checking if there are five consecutive symbols on the game board.
"""
def __init__(self, board_size):
self.board_size = board_size
self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)]
self.current_player = 'X'
def make_move(self, row, col):
"""
Makes a move at the given row and column.
If the move is valid, it places the current player's symbol on the board
and changes the current player to the other player (if the current player is 'X', then it becomes 'O' and vice versa).
:param row: int, the row index of this move
:param col: int, the column index
return: True if the move is valid, or False otherwise.
>>> gomokuGame = GomokuGame(10)
>>> gomokuGame.make_move(5, 5)
True
>>> gomokuGame.make_move(5, 5)
False
"""
if self.board[row][col] == ' ':
self.board[row][col] = self.current_player
self.current_player = 'O' if self.current_player == 'X' else 'X'
return True
return False
def _check_five_in_a_row(self, row, col, direction):
"""
checks if there are five consecutive symbols of the same player in a row starting from a given cell in a given direction (horizontal, vertical, diagonal).
Counts the number of consecutive symbols in that direction starting from the given cell,
:param row: int, row of the given cell
:param col: int, column of the given cell
:param direction: tuple, (int, int), named as (dx, dy). Row and col will plus several dx and dy repectively.
:return: True if there are five consecutive symbols of the same player, and False otherwise.
>>> gomokuGame = GomokuGame(10)
>>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
>>> for move in moves:
... gomokuGame.make_move(move[0], move[1])
>>> gomokuGame._check_five_in_a_row(5, 1, (0, 1))
True
>>> gomokuGame._check_five_in_a_row(5, 1, (1, 1))
False
"""
dx, dy = direction
count = 1
symbol = self.board[row][col]
for i in range(1, 5):
new_row = row + dx * i
new_col = col + dy * i
if not (0 <= new_row < self.board_size and 0 <= new_col < self.board_size):
return False
if self.board[new_row][new_col] != symbol:
return False
count += 1
return count == 5 | class GomokuGame:
"""
This class is an implementation of a Gomoku game, supporting for making moves, checking for a winner, and checking if there are five consecutive symbols on the game board.
"""
def __init__(self, board_size):
"""
Initializes the game with a given board size.
It initializes the board with empty spaces and sets the current player symble as 'X'.
"""
self.board_size = board_size
self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)]
self.current_player = 'X'
def make_move(self, row, col):
"""
Makes a move at the given row and column.
If the move is valid, it places the current player's symbol on the board
and changes the current player to the other player (if the current player is 'X', then it becomes 'O' and vice versa).
:param row: int, the row index of this move
:param col: int, the column index
return: True if the move is valid, or False otherwise.
>>> gomokuGame = GomokuGame(10)
>>> gomokuGame.make_move(5, 5)
True
>>> gomokuGame.make_move(5, 5)
False
"""
def _check_five_in_a_row(self, row, col, direction):
"""
checks if there are five consecutive symbols of the same player in a row starting from a given cell in a given direction (horizontal, vertical, diagonal).
Counts the number of consecutive symbols in that direction starting from the given cell,
:param row: int, row of the given cell
:param col: int, column of the given cell
:param direction: tuple, (int, int), named as (dx, dy). Row and col will plus several dx and dy repectively.
:return: True if there are five consecutive symbols of the same player, and False otherwise.
>>> gomokuGame = GomokuGame(10)
>>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
>>> for move in moves:
... gomokuGame.make_move(move[0], move[1])
>>> gomokuGame._check_five_in_a_row(5, 1, (0, 1))
True
>>> gomokuGame._check_five_in_a_row(5, 1, (1, 1))
False
""" | def check_winner(self):
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
for row in range(self.board_size):
for col in range(self.board_size):
if self.board[row][col] != ' ':
for direction in directions:
if self._check_five_in_a_row(row, col, direction):
return self.board[row][col]
return None | Checks if there is a winner by looking for five in a row in all directions (horizontal, vertical, diagonal). return: the symbol of the winning player (either 'X' or 'O') if there is a winner, or None otherwise. |
ClassEval_41_sum | class GomokuGame:
"""
This class is an implementation of a Gomoku game, supporting for making moves, checking for a winner, and checking if there are five consecutive symbols on the game board.
"""
def __init__(self, board_size):
self.board_size = board_size
self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)]
self.current_player = 'X'
def make_move(self, row, col):
"""
Makes a move at the given row and column.
If the move is valid, it places the current player's symbol on the board
and changes the current player to the other player (if the current player is 'X', then it becomes 'O' and vice versa).
:param row: int, the row index of this move
:param col: int, the column index
return: True if the move is valid, or False otherwise.
>>> gomokuGame = GomokuGame(10)
>>> gomokuGame.make_move(5, 5)
True
>>> gomokuGame.make_move(5, 5)
False
"""
if self.board[row][col] == ' ':
self.board[row][col] = self.current_player
self.current_player = 'O' if self.current_player == 'X' else 'X'
return True
return False
def check_winner(self):
"""
Checks if there is a winner by looking for five in a row in all directions (horizontal, vertical, diagonal).
return: the symbol of the winning player (either 'X' or 'O') if there is a winner, or None otherwise.
>>> gomokuGame = GomokuGame(10)
>>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
>>> for move in moves:
... gomokuGame.make_move(move[0], move[1])
>>> gomokuGame.check_winner()
'X'
"""
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
for row in range(self.board_size):
for col in range(self.board_size):
if self.board[row][col] != ' ':
for direction in directions:
if self._check_five_in_a_row(row, col, direction):
return self.board[row][col]
return None
def _check_five_in_a_row(self, row, col, direction):
dx, dy = direction
count = 1
symbol = self.board[row][col]
for i in range(1, 5):
new_row = row + dx * i
new_col = col + dy * i
if not (0 <= new_row < self.board_size and 0 <= new_col < self.board_size):
return False
if self.board[new_row][new_col] != symbol:
return False
count += 1
return count == 5 | class GomokuGame:
"""
This class is an implementation of a Gomoku game, supporting for making moves, checking for a winner, and checking if there are five consecutive symbols on the game board.
"""
def __init__(self, board_size):
"""
Initializes the game with a given board size.
It initializes the board with empty spaces and sets the current player symble as 'X'.
"""
self.board_size = board_size
self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)]
self.current_player = 'X'
def make_move(self, row, col):
"""
Makes a move at the given row and column.
If the move is valid, it places the current player's symbol on the board
and changes the current player to the other player (if the current player is 'X', then it becomes 'O' and vice versa).
:param row: int, the row index of this move
:param col: int, the column index
return: True if the move is valid, or False otherwise.
>>> gomokuGame = GomokuGame(10)
>>> gomokuGame.make_move(5, 5)
True
>>> gomokuGame.make_move(5, 5)
False
"""
def check_winner(self):
"""
Checks if there is a winner by looking for five in a row in all directions (horizontal, vertical, diagonal).
return: the symbol of the winning player (either 'X' or 'O') if there is a winner, or None otherwise.
>>> gomokuGame = GomokuGame(10)
>>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
>>> for move in moves:
... gomokuGame.make_move(move[0], move[1])
>>> gomokuGame.check_winner()
'X'
"""
def _check_five_in_a_row(self, row, col, direction):
"""
checks if there are five consecutive symbols of the same player in a row starting from a given cell in a given direction (horizontal, vertical, diagonal).
Counts the number of consecutive symbols in that direction starting from the given cell,
:param row: int, row of the given cell
:param col: int, column of the given cell
:param direction: tuple, (int, int), named as (dx, dy). Row and col will plus several dx and dy repectively.
:return: True if there are five consecutive symbols of the same player, and False otherwise.
>>> gomokuGame = GomokuGame(10)
>>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]
>>> for move in moves:
... gomokuGame.make_move(move[0], move[1])
>>> gomokuGame._check_five_in_a_row(5, 1, (0, 1))
True
>>> gomokuGame._check_five_in_a_row(5, 1, (1, 1))
False
""" | def _check_five_in_a_row(self, row, col, direction):
dx, dy = direction
count = 1
symbol = self.board[row][col]
for i in range(1, 5):
new_row = row + dx * i
new_col = col + dy * i
if not (0 <= new_row < self.board_size and 0 <= new_col < self.board_size):
return False
if self.board[new_row][new_col] != symbol:
return False
count += 1
return count == 5 | checks if there are five consecutive symbols of the same player in a row starting from a given cell in a given direction (horizontal, vertical, diagonal). Counts the number of consecutive symbols in that direction starting from the given cell, |
ClassEval_42_sum | class Hotel:
"""
This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.
"""
def __init__(self, name, rooms):
self.name = name
self.available_rooms = rooms
# available_rooms = {room_type1: room_number1, room_type2: room_number2, ...}
# available_rooms = {'single': 5, 'double': 3}
self.booked_rooms = {}
# booked_rooms = {room_type1: {name1: room_number1, name2: room_number2, ...}, room_type2: {...}, ...}
# booked_rooms = {'single': {'name1': 2, 'name2':1}, 'double': {}}
def check_in(self, room_type, room_number, name):
"""
Check if the room of the specified type and number is booked by the person named name.
Remove this name when check in successfuly(room_number is equal to specific person's booked_rooms. When the actual check in quantity (room_number) is less than the booked quantity, number in booked_rooms will be booked quantity minus actual quantity
:param room_type: str, check in room type
:param room_number: int, check in room number
:param name: str, person name
:return False: only if the room_type is not in the booked_rooms or room_number is higher than quantity in booked rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.check_in('single', 2, 'guest 1')
False
>>> hotel.check_in('single', 1, 'guest 1')
>>> hotel.booked_rooms
{'single': {}}
"""
# Check if the room of the specified type and number is booked
if room_type not in self.booked_rooms.keys():
return False
if name in self.booked_rooms[room_type]:
if room_number > self.booked_rooms[room_type][name]:
return False
elif room_number == self.booked_rooms[room_type][name]:
# Check in the room by removing it from the booked_rooms dictionary
self.booked_rooms[room_type].pop(name)
else:
self.booked_rooms[room_type][name] -= room_number
def check_out(self, room_type, room_number):
"""
Check out rooms, add number for specific type in available_rooms.
If room_type is new, add new type in available_rooms.
:param room_type: str, check out room type
:param room_number: int, check out room number
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.check_out('single', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3}
>>> hotel.check_out('triple', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3, 'triple': 2}
"""
if room_type in self.available_rooms:
self.available_rooms[room_type] += room_number
else:
self.available_rooms[room_type] = room_number
def get_available_rooms(self, room_type):
"""
Get the number of specific type of available rooms.
:param room_type: str, the room type that want to know
:return: int, the remaining number of this type rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.get_available_rooms('single')
5
"""
return self.available_rooms[room_type] | class Hotel:
"""
This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.
"""
def __init__(self, name, rooms):
"""
Initialize the three fields in Hotel System.
name is the hotel name.
available_rooms stores the remaining rooms in the hotel
booked_rooms stores the rooms that have been booked and the person's name who booked rooms.
>>> hotel.name
'peace hotel'
>>> hotel.available_rooms
available_rooms = {'single': 5, 'double': 3}
>>> hotel.booked_rooms
{'single': {'guest 1': 2, 'guest 2':1}, 'double': {'guest1': 1}}
"""
self.name = name
self.available_rooms = rooms
self.booked_rooms = {}
def check_in(self, room_type, room_number, name):
"""
Check if the room of the specified type and number is booked by the person named name.
Remove this name when check in successfuly(room_number is equal to specific person's booked_rooms. When the actual check in quantity (room_number) is less than the booked quantity, number in booked_rooms will be booked quantity minus actual quantity
:param room_type: str, check in room type
:param room_number: int, check in room number
:param name: str, person name
:return False: only if the room_type is not in the booked_rooms or room_number is higher than quantity in booked rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.check_in('single', 2, 'guest 1')
False
>>> hotel.check_in('single', 1, 'guest 1')
>>> hotel.booked_rooms
{'single': {}}
"""
def check_out(self, room_type, room_number):
"""
Check out rooms, add number for specific type in available_rooms.
If room_type is new, add new type in available_rooms.
:param room_type: str, check out room type
:param room_number: int, check out room number
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.check_out('single', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3}
>>> hotel.check_out('triple', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3, 'triple': 2}
"""
def get_available_rooms(self, room_type):
"""
Get the number of specific type of available rooms.
:param room_type: str, the room type that want to know
:return: int, the remaining number of this type rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.get_available_rooms('single')
5
""" | def book_room(self, room_type, room_number, name):
# Check if there are any rooms of the specified type available
if room_type not in self.available_rooms.keys():
return False
if room_number <= self.available_rooms[room_type]:
# Book the room by adding it to the booked_rooms dictionary
if room_type not in self.booked_rooms.keys():
self.booked_rooms[room_type] = {}
self.booked_rooms[room_type][name] = room_number
self.available_rooms[room_type] -= room_number
return "Success!"
elif self.available_rooms[room_type] != 0:
return self.available_rooms[room_type]
else:
return False | Check if there are any rooms of the specified type available. if rooms are adequate, modify available_rooms and booked_rooms and finish booking, or fail to book otherwise. |
ClassEval_42_sum | class Hotel:
"""
This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.
"""
def __init__(self, name, rooms):
self.name = name
self.available_rooms = rooms
# available_rooms = {room_type1: room_number1, room_type2: room_number2, ...}
# available_rooms = {'single': 5, 'double': 3}
self.booked_rooms = {}
# booked_rooms = {room_type1: {name1: room_number1, name2: room_number2, ...}, room_type2: {...}, ...}
# booked_rooms = {'single': {'name1': 2, 'name2':1}, 'double': {}}
def book_room(self, room_type, room_number, name):
"""
Check if there are any rooms of the specified type available.
if rooms are adequate, modify available_rooms and booked_rooms and finish booking, or fail to book otherwise.
:param room_type: str
:param room_number: int, the expected number of specified type rooms to be booked
:param name: str, guest name
:return: if number of rooms about to be booked doesn't exceed the remaining rooms, return str 'Success!'
if exceeds but quantity of available rooms is not equal to zero, return int(the remaining quantity of this room type).
if exceeds and quantity is zero or the room_type isn't in available_room, return False.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.book_room('single', 5, 'guest 1')
4
>>> hotel.book_room('single', 4, 'guest 1')
'Success!'
>>> hotel.book_room('single', 1, 'guest 1')
False
>>> hotel.book_room('triple', 1, 'guest 1')
False
"""
# Check if there are any rooms of the specified type available
if room_type not in self.available_rooms.keys():
return False
if room_number <= self.available_rooms[room_type]:
# Book the room by adding it to the booked_rooms dictionary
if room_type not in self.booked_rooms.keys():
self.booked_rooms[room_type] = {}
self.booked_rooms[room_type][name] = room_number
self.available_rooms[room_type] -= room_number
return "Success!"
elif self.available_rooms[room_type] != 0:
return self.available_rooms[room_type]
else:
return False
def check_out(self, room_type, room_number):
"""
Check out rooms, add number for specific type in available_rooms.
If room_type is new, add new type in available_rooms.
:param room_type: str, check out room type
:param room_number: int, check out room number
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.check_out('single', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3}
>>> hotel.check_out('triple', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3, 'triple': 2}
"""
if room_type in self.available_rooms:
self.available_rooms[room_type] += room_number
else:
self.available_rooms[room_type] = room_number
def get_available_rooms(self, room_type):
"""
Get the number of specific type of available rooms.
:param room_type: str, the room type that want to know
:return: int, the remaining number of this type rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.get_available_rooms('single')
5
"""
return self.available_rooms[room_type] | class Hotel:
"""
This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.
"""
def __init__(self, name, rooms):
"""
Initialize the three fields in Hotel System.
name is the hotel name.
available_rooms stores the remaining rooms in the hotel
booked_rooms stores the rooms that have been booked and the person's name who booked rooms.
>>> hotel.name
'peace hotel'
>>> hotel.available_rooms
available_rooms = {'single': 5, 'double': 3}
>>> hotel.booked_rooms
{'single': {'guest 1': 2, 'guest 2':1}, 'double': {'guest1': 1}}
"""
self.name = name
self.available_rooms = rooms
self.booked_rooms = {}
def book_room(self, room_type, room_number, name):
"""
Check if there are any rooms of the specified type available.
if rooms are adequate, modify available_rooms and booked_rooms and finish booking, or fail to book otherwise.
:param room_type: str
:param room_number: int, the expected number of specified type rooms to be booked
:param name: str, guest name
:return: if number of rooms about to be booked doesn't exceed the remaining rooms, return str 'Success!'
if exceeds but quantity of available rooms is not equal to zero, return int(the remaining quantity of this room type).
if exceeds and quantity is zero or the room_type isn't in available_room, return False.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.book_room('single', 5, 'guest 1')
4
>>> hotel.book_room('single', 4, 'guest 1')
'Success!'
>>> hotel.book_room('single', 1, 'guest 1')
False
>>> hotel.book_room('triple', 1, 'guest 1')
False
"""
def check_out(self, room_type, room_number):
"""
Check out rooms, add number for specific type in available_rooms.
If room_type is new, add new type in available_rooms.
:param room_type: str, check out room type
:param room_number: int, check out room number
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.check_out('single', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3}
>>> hotel.check_out('triple', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3, 'triple': 2}
"""
def get_available_rooms(self, room_type):
"""
Get the number of specific type of available rooms.
:param room_type: str, the room type that want to know
:return: int, the remaining number of this type rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.get_available_rooms('single')
5
""" | def check_in(self, room_type, room_number, name):
# Check if the room of the specified type and number is booked
if room_type not in self.booked_rooms.keys():
return False
if name in self.booked_rooms[room_type]:
if room_number > self.booked_rooms[room_type][name]:
return False
elif room_number == self.booked_rooms[room_type][name]:
# Check in the room by removing it from the booked_rooms dictionary
self.booked_rooms[room_type].pop(name)
else:
self.booked_rooms[room_type][name] -= room_number | Check if the room of the specified type and number is booked by the person named name. Remove this name when check in successfuly(room_number is equal to specific person's booked_rooms. When the actual check in quantity (room_number) is less than the booked quantity, number in booked_rooms will be booked quantity minus actual quantity |
ClassEval_42_sum | class Hotel:
"""
This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.
"""
def __init__(self, name, rooms):
self.name = name
self.available_rooms = rooms
# available_rooms = {room_type1: room_number1, room_type2: room_number2, ...}
# available_rooms = {'single': 5, 'double': 3}
self.booked_rooms = {}
# booked_rooms = {room_type1: {name1: room_number1, name2: room_number2, ...}, room_type2: {...}, ...}
# booked_rooms = {'single': {'name1': 2, 'name2':1}, 'double': {}}
def book_room(self, room_type, room_number, name):
"""
Check if there are any rooms of the specified type available.
if rooms are adequate, modify available_rooms and booked_rooms and finish booking, or fail to book otherwise.
:param room_type: str
:param room_number: int, the expected number of specified type rooms to be booked
:param name: str, guest name
:return: if number of rooms about to be booked doesn't exceed the remaining rooms, return str 'Success!'
if exceeds but quantity of available rooms is not equal to zero, return int(the remaining quantity of this room type).
if exceeds and quantity is zero or the room_type isn't in available_room, return False.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.book_room('single', 5, 'guest 1')
4
>>> hotel.book_room('single', 4, 'guest 1')
'Success!'
>>> hotel.book_room('single', 1, 'guest 1')
False
>>> hotel.book_room('triple', 1, 'guest 1')
False
"""
# Check if there are any rooms of the specified type available
if room_type not in self.available_rooms.keys():
return False
if room_number <= self.available_rooms[room_type]:
# Book the room by adding it to the booked_rooms dictionary
if room_type not in self.booked_rooms.keys():
self.booked_rooms[room_type] = {}
self.booked_rooms[room_type][name] = room_number
self.available_rooms[room_type] -= room_number
return "Success!"
elif self.available_rooms[room_type] != 0:
return self.available_rooms[room_type]
else:
return False
def check_in(self, room_type, room_number, name):
"""
Check if the room of the specified type and number is booked by the person named name.
Remove this name when check in successfuly(room_number is equal to specific person's booked_rooms. When the actual check in quantity (room_number) is less than the booked quantity, number in booked_rooms will be booked quantity minus actual quantity
:param room_type: str, check in room type
:param room_number: int, check in room number
:param name: str, person name
:return False: only if the room_type is not in the booked_rooms or room_number is higher than quantity in booked rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.check_in('single', 2, 'guest 1')
False
>>> hotel.check_in('single', 1, 'guest 1')
>>> hotel.booked_rooms
{'single': {}}
"""
# Check if the room of the specified type and number is booked
if room_type not in self.booked_rooms.keys():
return False
if name in self.booked_rooms[room_type]:
if room_number > self.booked_rooms[room_type][name]:
return False
elif room_number == self.booked_rooms[room_type][name]:
# Check in the room by removing it from the booked_rooms dictionary
self.booked_rooms[room_type].pop(name)
else:
self.booked_rooms[room_type][name] -= room_number
def get_available_rooms(self, room_type):
"""
Get the number of specific type of available rooms.
:param room_type: str, the room type that want to know
:return: int, the remaining number of this type rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.get_available_rooms('single')
5
"""
return self.available_rooms[room_type] | class Hotel:
"""
This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.
"""
def __init__(self, name, rooms):
"""
Initialize the three fields in Hotel System.
name is the hotel name.
available_rooms stores the remaining rooms in the hotel
booked_rooms stores the rooms that have been booked and the person's name who booked rooms.
>>> hotel.name
'peace hotel'
>>> hotel.available_rooms
available_rooms = {'single': 5, 'double': 3}
>>> hotel.booked_rooms
{'single': {'guest 1': 2, 'guest 2':1}, 'double': {'guest1': 1}}
"""
self.name = name
self.available_rooms = rooms
self.booked_rooms = {}
def book_room(self, room_type, room_number, name):
"""
Check if there are any rooms of the specified type available.
if rooms are adequate, modify available_rooms and booked_rooms and finish booking, or fail to book otherwise.
:param room_type: str
:param room_number: int, the expected number of specified type rooms to be booked
:param name: str, guest name
:return: if number of rooms about to be booked doesn't exceed the remaining rooms, return str 'Success!'
if exceeds but quantity of available rooms is not equal to zero, return int(the remaining quantity of this room type).
if exceeds and quantity is zero or the room_type isn't in available_room, return False.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.book_room('single', 5, 'guest 1')
4
>>> hotel.book_room('single', 4, 'guest 1')
'Success!'
>>> hotel.book_room('single', 1, 'guest 1')
False
>>> hotel.book_room('triple', 1, 'guest 1')
False
"""
def check_in(self, room_type, room_number, name):
"""
Check if the room of the specified type and number is booked by the person named name.
Remove this name when check in successfuly(room_number is equal to specific person's booked_rooms. When the actual check in quantity (room_number) is less than the booked quantity, number in booked_rooms will be booked quantity minus actual quantity
:param room_type: str, check in room type
:param room_number: int, check in room number
:param name: str, person name
:return False: only if the room_type is not in the booked_rooms or room_number is higher than quantity in booked rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.check_in('single', 2, 'guest 1')
False
>>> hotel.check_in('single', 1, 'guest 1')
>>> hotel.booked_rooms
{'single': {}}
"""
def get_available_rooms(self, room_type):
"""
Get the number of specific type of available rooms.
:param room_type: str, the room type that want to know
:return: int, the remaining number of this type rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.get_available_rooms('single')
5
""" | def check_out(self, room_type, room_number):
if room_type in self.available_rooms:
self.available_rooms[room_type] += room_number
else:
self.available_rooms[room_type] = room_number | Check out rooms, add number for specific type in available_rooms. If room_type is new, add new type in available_rooms. |
ClassEval_42_sum | class Hotel:
"""
This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.
"""
def __init__(self, name, rooms):
self.name = name
self.available_rooms = rooms
# available_rooms = {room_type1: room_number1, room_type2: room_number2, ...}
# available_rooms = {'single': 5, 'double': 3}
self.booked_rooms = {}
# booked_rooms = {room_type1: {name1: room_number1, name2: room_number2, ...}, room_type2: {...}, ...}
# booked_rooms = {'single': {'name1': 2, 'name2':1}, 'double': {}}
def book_room(self, room_type, room_number, name):
"""
Check if there are any rooms of the specified type available.
if rooms are adequate, modify available_rooms and booked_rooms and finish booking, or fail to book otherwise.
:param room_type: str
:param room_number: int, the expected number of specified type rooms to be booked
:param name: str, guest name
:return: if number of rooms about to be booked doesn't exceed the remaining rooms, return str 'Success!'
if exceeds but quantity of available rooms is not equal to zero, return int(the remaining quantity of this room type).
if exceeds and quantity is zero or the room_type isn't in available_room, return False.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.book_room('single', 5, 'guest 1')
4
>>> hotel.book_room('single', 4, 'guest 1')
'Success!'
>>> hotel.book_room('single', 1, 'guest 1')
False
>>> hotel.book_room('triple', 1, 'guest 1')
False
"""
# Check if there are any rooms of the specified type available
if room_type not in self.available_rooms.keys():
return False
if room_number <= self.available_rooms[room_type]:
# Book the room by adding it to the booked_rooms dictionary
if room_type not in self.booked_rooms.keys():
self.booked_rooms[room_type] = {}
self.booked_rooms[room_type][name] = room_number
self.available_rooms[room_type] -= room_number
return "Success!"
elif self.available_rooms[room_type] != 0:
return self.available_rooms[room_type]
else:
return False
def check_in(self, room_type, room_number, name):
"""
Check if the room of the specified type and number is booked by the person named name.
Remove this name when check in successfuly(room_number is equal to specific person's booked_rooms. When the actual check in quantity (room_number) is less than the booked quantity, number in booked_rooms will be booked quantity minus actual quantity
:param room_type: str, check in room type
:param room_number: int, check in room number
:param name: str, person name
:return False: only if the room_type is not in the booked_rooms or room_number is higher than quantity in booked rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.check_in('single', 2, 'guest 1')
False
>>> hotel.check_in('single', 1, 'guest 1')
>>> hotel.booked_rooms
{'single': {}}
"""
# Check if the room of the specified type and number is booked
if room_type not in self.booked_rooms.keys():
return False
if name in self.booked_rooms[room_type]:
if room_number > self.booked_rooms[room_type][name]:
return False
elif room_number == self.booked_rooms[room_type][name]:
# Check in the room by removing it from the booked_rooms dictionary
self.booked_rooms[room_type].pop(name)
else:
self.booked_rooms[room_type][name] -= room_number
def check_out(self, room_type, room_number):
"""
Check out rooms, add number for specific type in available_rooms.
If room_type is new, add new type in available_rooms.
:param room_type: str, check out room type
:param room_number: int, check out room number
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.check_out('single', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3}
>>> hotel.check_out('triple', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3, 'triple': 2}
"""
if room_type in self.available_rooms:
self.available_rooms[room_type] += room_number
else:
self.available_rooms[room_type] = room_number
def get_available_rooms(self, room_type):
return self.available_rooms[room_type] | class Hotel:
"""
This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.
"""
def __init__(self, name, rooms):
"""
Initialize the three fields in Hotel System.
name is the hotel name.
available_rooms stores the remaining rooms in the hotel
booked_rooms stores the rooms that have been booked and the person's name who booked rooms.
>>> hotel.name
'peace hotel'
>>> hotel.available_rooms
available_rooms = {'single': 5, 'double': 3}
>>> hotel.booked_rooms
{'single': {'guest 1': 2, 'guest 2':1}, 'double': {'guest1': 1}}
"""
self.name = name
self.available_rooms = rooms
self.booked_rooms = {}
def book_room(self, room_type, room_number, name):
"""
Check if there are any rooms of the specified type available.
if rooms are adequate, modify available_rooms and booked_rooms and finish booking, or fail to book otherwise.
:param room_type: str
:param room_number: int, the expected number of specified type rooms to be booked
:param name: str, guest name
:return: if number of rooms about to be booked doesn't exceed the remaining rooms, return str 'Success!'
if exceeds but quantity of available rooms is not equal to zero, return int(the remaining quantity of this room type).
if exceeds and quantity is zero or the room_type isn't in available_room, return False.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.book_room('single', 5, 'guest 1')
4
>>> hotel.book_room('single', 4, 'guest 1')
'Success!'
>>> hotel.book_room('single', 1, 'guest 1')
False
>>> hotel.book_room('triple', 1, 'guest 1')
False
"""
def check_in(self, room_type, room_number, name):
"""
Check if the room of the specified type and number is booked by the person named name.
Remove this name when check in successfuly(room_number is equal to specific person's booked_rooms. When the actual check in quantity (room_number) is less than the booked quantity, number in booked_rooms will be booked quantity minus actual quantity
:param room_type: str, check in room type
:param room_number: int, check in room number
:param name: str, person name
:return False: only if the room_type is not in the booked_rooms or room_number is higher than quantity in booked rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.book_room('single', 1, 'guest 1')
'Success!'
>>> hotel.check_in('single', 2, 'guest 1')
False
>>> hotel.check_in('single', 1, 'guest 1')
>>> hotel.booked_rooms
{'single': {}}
"""
def check_out(self, room_type, room_number):
"""
Check out rooms, add number for specific type in available_rooms.
If room_type is new, add new type in available_rooms.
:param room_type: str, check out room type
:param room_number: int, check out room number
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.check_out('single', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3}
>>> hotel.check_out('triple', 2)
>>> hotel.available_rooms
{'single': 7, 'double': 3, 'triple': 2}
"""
def get_available_rooms(self, room_type):
"""
Get the number of specific type of available rooms.
:param room_type: str, the room type that want to know
:return: int, the remaining number of this type rooms.
>>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})
>>> hotel.get_available_rooms('single')
5
""" | def get_available_rooms(self, room_type):
return self.available_rooms[room_type] | Get the number of specific type of available rooms. |
ClassEval_43_sum | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
self.employees = {}
def remove_employee(self, employee_id):
"""
Remove an employee from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.remove_employee(1)
True
>>> hrManagementSystem.remove_employee(2)
False
"""
if employee_id in self.employees:
del self.employees[employee_id]
return True
else:
return False
def update_employee(self, employee_id: int, employee_info: dict):
"""
Update an employee's information in the HRManagementSystem.
:param employee_id: The employee's id, int.
:param employee_info: The employee's information, dict.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
True
>>> hrManagementSystem.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
False
"""
int, employee_info: dict):
employee = self.get_employee(employee_id)
if employee == False:
return False
else:
for key, value in employee_info.items():
if key not in employee:
return False
for key, value in employee_info.items():
employee[key] = value
return True
def get_employee(self, employee_id):
"""
Get an employee's information from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns the employee's information, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.get_employee(1)
{'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}
>>> hrManagementSystem.get_employee(2)
False
"""
if employee_id in self.employees:
return self.employees[employee_id]
else:
return False
def list_employees(self):
“”“
List all employees' information in the HRManagementSystem.
:return: A list of all employees' information,dict.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.list_employees()
{1: {'employee_ID': 1, 'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
"""
employee_data = {}
if self.employees:
for employee_id, employee_info in self.employees.items():
employee_details = {}
employee_details["employee_ID"] = employee_id
for key, value in employee_info.items():
employee_details[key] = value
employee_data[employee_id] = employee_details
return employee_data | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
"""
self.employees = {}
def remove_employee(self, employee_id):
"""
Remove an employee from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.remove_employee(1)
True
>>> hrManagementSystem.remove_employee(2)
False
"""
def update_employee(self, employee_id: int, employee_info: dict):
"""
Update an employee's information in the HRManagementSystem.
:param employee_id: The employee's id, int.
:param employee_info: The employee's information, dict.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
True
>>> hrManagementSystem.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
False
"""
def get_employee(self, employee_id):
"""
Get an employee's information from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns the employee's information, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.get_employee(1)
{'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}
>>> hrManagementSystem.get_employee(2)
False
"""
def list_employees(self):
“”“
List all employees' information in the HRManagementSystem.
:return: A list of all employees' information,dict.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.list_employees()
{1: {'employee_ID': 1, 'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
""" | def add_employee(self, employee_id, name, position, department, salary):
if employee_id in self.employees:
return False
else:
self.employees[employee_id] = {
'name': name,
'position': position,
'department': department,
'salary': salary
}
return True | Add a new employee to the HRManagementSystem. |
ClassEval_43_sum | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
"""
Add a new employee to the HRManagementSystem.
:param employee_id: The employee's id, int.
:param name: The employee's name, str.
:param position: The employee's position, str.
:param department: The employee's department, str.
:param salary: The employee's salary, int.
:return: If the employee is already in the HRManagementSystem, returns False, otherwise, returns True.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
True
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
False
"""
if employee_id in self.employees:
return False
else:
self.employees[employee_id] = {
'name': name,
'position': position,
'department': department,
'salary': salary
}
return True
def update_employee(self, employee_id: int, employee_info: dict):
"""
Update an employee's information in the HRManagementSystem.
:param employee_id: The employee's id, int.
:param employee_info: The employee's information, dict.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
True
>>> hrManagementSystem.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
False
"""
int, employee_info: dict):
employee = self.get_employee(employee_id)
if employee == False:
return False
else:
for key, value in employee_info.items():
if key not in employee:
return False
for key, value in employee_info.items():
employee[key] = value
return True
def get_employee(self, employee_id):
"""
Get an employee's information from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns the employee's information, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.get_employee(1)
{'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}
>>> hrManagementSystem.get_employee(2)
False
"""
if employee_id in self.employees:
return self.employees[employee_id]
else:
return False
def list_employees(self):
“”“
List all employees' information in the HRManagementSystem.
:return: A list of all employees' information,dict.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.list_employees()
{1: {'employee_ID': 1, 'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
"""
employee_data = {}
if self.employees:
for employee_id, employee_info in self.employees.items():
employee_details = {}
employee_details["employee_ID"] = employee_id
for key, value in employee_info.items():
employee_details[key] = value
employee_data[employee_id] = employee_details
return employee_data | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
"""
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
"""
Add a new employee to the HRManagementSystem.
:param employee_id: The employee's id, int.
:param name: The employee's name, str.
:param position: The employee's position, str.
:param department: The employee's department, str.
:param salary: The employee's salary, int.
:return: If the employee is already in the HRManagementSystem, returns False, otherwise, returns True.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
True
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
False
"""
def update_employee(self, employee_id: int, employee_info: dict):
"""
Update an employee's information in the HRManagementSystem.
:param employee_id: The employee's id, int.
:param employee_info: The employee's information, dict.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
True
>>> hrManagementSystem.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
False
"""
def get_employee(self, employee_id):
"""
Get an employee's information from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns the employee's information, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.get_employee(1)
{'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}
>>> hrManagementSystem.get_employee(2)
False
"""
def list_employees(self):
“”“
List all employees' information in the HRManagementSystem.
:return: A list of all employees' information,dict.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.list_employees()
{1: {'employee_ID': 1, 'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
""" | def remove_employee(self, employee_id):
if employee_id in self.employees:
del self.employees[employee_id]
return True
else:
return False | Remove an employee from the HRManagementSystem. |
ClassEval_43_sum | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
"""
Add a new employee to the HRManagementSystem.
:param employee_id: The employee's id, int.
:param name: The employee's name, str.
:param position: The employee's position, str.
:param department: The employee's department, str.
:param salary: The employee's salary, int.
:return: If the employee is already in the HRManagementSystem, returns False, otherwise, returns True.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
True
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
False
"""
if employee_id in self.employees:
return False
else:
self.employees[employee_id] = {
'name': name,
'position': position,
'department': department,
'salary': salary
}
return True
def remove_employee(self, employee_id):
"""
Remove an employee from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.remove_employee(1)
True
>>> hrManagementSystem.remove_employee(2)
False
"""
if employee_id in self.employees:
del self.employees[employee_id]
return True
else:
return False
def get_employee(self, employee_id):
"""
Get an employee's information from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns the employee's information, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.get_employee(1)
{'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}
>>> hrManagementSystem.get_employee(2)
False
"""
if employee_id in self.employees:
return self.employees[employee_id]
else:
return False
def list_employees(self):
“”“
List all employees' information in the HRManagementSystem.
:return: A list of all employees' information,dict.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.list_employees()
{1: {'employee_ID': 1, 'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
"""
employee_data = {}
if self.employees:
for employee_id, employee_info in self.employees.items():
employee_details = {}
employee_details["employee_ID"] = employee_id
for key, value in employee_info.items():
employee_details[key] = value
employee_data[employee_id] = employee_details
return employee_data | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
"""
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
"""
Add a new employee to the HRManagementSystem.
:param employee_id: The employee's id, int.
:param name: The employee's name, str.
:param position: The employee's position, str.
:param department: The employee's department, str.
:param salary: The employee's salary, int.
:return: If the employee is already in the HRManagementSystem, returns False, otherwise, returns True.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
True
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
False
"""
def remove_employee(self, employee_id):
"""
Remove an employee from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.remove_employee(1)
True
>>> hrManagementSystem.remove_employee(2)
False
"""
def get_employee(self, employee_id):
"""
Get an employee's information from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns the employee's information, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.get_employee(1)
{'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}
>>> hrManagementSystem.get_employee(2)
False
"""
def list_employees(self):
“”“
List all employees' information in the HRManagementSystem.
:return: A list of all employees' information,dict.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.list_employees()
{1: {'employee_ID': 1, 'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
""" | def update_employee(self, employee_id: int, employee_info: dict):
employee = self.get_employee(employee_id)
if employee == False:
return False
else:
for key, value in employee_info.items():
if key not in employee:
return False
for key, value in employee_info.items():
employee[key] = value
return True | Update an employee's information in the HRManagementSystem. |
ClassEval_43_sum | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
"""
Add a new employee to the HRManagementSystem.
:param employee_id: The employee's id, int.
:param name: The employee's name, str.
:param position: The employee's position, str.
:param department: The employee's department, str.
:param salary: The employee's salary, int.
:return: If the employee is already in the HRManagementSystem, returns False, otherwise, returns True.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
True
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
False
"""
if employee_id in self.employees:
return False
else:
self.employees[employee_id] = {
'name': name,
'position': position,
'department': department,
'salary': salary
}
return True
def remove_employee(self, employee_id):
"""
Remove an employee from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.remove_employee(1)
True
>>> hrManagementSystem.remove_employee(2)
False
"""
if employee_id in self.employees:
del self.employees[employee_id]
return True
else:
return False
def update_employee(self, employee_id: int, employee_info: dict):
"""
Update an employee's information in the HRManagementSystem.
:param employee_id: The employee's id, int.
:param employee_info: The employee's information, dict.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
True
>>> hrManagementSystem.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
False
"""
int, employee_info: dict):
employee = self.get_employee(employee_id)
if employee == False:
return False
else:
for key, value in employee_info.items():
if key not in employee:
return False
for key, value in employee_info.items():
employee[key] = value
return True
def list_employees(self):
“”“
List all employees' information in the HRManagementSystem.
:return: A list of all employees' information,dict.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.list_employees()
{1: {'employee_ID': 1, 'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
"""
employee_data = {}
if self.employees:
for employee_id, employee_info in self.employees.items():
employee_details = {}
employee_details["employee_ID"] = employee_id
for key, value in employee_info.items():
employee_details[key] = value
employee_data[employee_id] = employee_details
return employee_data | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
"""
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
"""
Add a new employee to the HRManagementSystem.
:param employee_id: The employee's id, int.
:param name: The employee's name, str.
:param position: The employee's position, str.
:param department: The employee's department, str.
:param salary: The employee's salary, int.
:return: If the employee is already in the HRManagementSystem, returns False, otherwise, returns True.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
True
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
False
"""
def remove_employee(self, employee_id):
"""
Remove an employee from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.remove_employee(1)
True
>>> hrManagementSystem.remove_employee(2)
False
"""
def update_employee(self, employee_id: int, employee_info: dict):
"""
Update an employee's information in the HRManagementSystem.
:param employee_id: The employee's id, int.
:param employee_info: The employee's information, dict.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
True
>>> hrManagementSystem.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
False
"""
def list_employees(self):
“”“
List all employees' information in the HRManagementSystem.
:return: A list of all employees' information,dict.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.list_employees()
{1: {'employee_ID': 1, 'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
""" | def get_employee(self, employee_id):
if employee_id in self.employees:
return self.employees[employee_id]
else:
return False | Get an employee's information from the HRManagementSystem. |
ClassEval_43_sum | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
"""
Add a new employee to the HRManagementSystem.
:param employee_id: The employee's id, int.
:param name: The employee's name, str.
:param position: The employee's position, str.
:param department: The employee's department, str.
:param salary: The employee's salary, int.
:return: If the employee is already in the HRManagementSystem, returns False, otherwise, returns True.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
True
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
False
"""
if employee_id in self.employees:
return False
else:
self.employees[employee_id] = {
'name': name,
'position': position,
'department': department,
'salary': salary
}
return True
def remove_employee(self, employee_id):
"""
Remove an employee from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.remove_employee(1)
True
>>> hrManagementSystem.remove_employee(2)
False
"""
if employee_id in self.employees:
del self.employees[employee_id]
return True
else:
return False
def update_employee(self, employee_id: int, employee_info: dict):
"""
Update an employee's information in the HRManagementSystem.
:param employee_id: The employee's id, int.
:param employee_info: The employee's information, dict.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
True
>>> hrManagementSystem.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
False
"""
int, employee_info: dict):
employee = self.get_employee(employee_id)
if employee == False:
return False
else:
for key, value in employee_info.items():
if key not in employee:
return False
for key, value in employee_info.items():
employee[key] = value
return True
def get_employee(self, employee_id):
"""
Get an employee's information from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns the employee's information, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.get_employee(1)
{'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}
>>> hrManagementSystem.get_employee(2)
False
"""
if employee_id in self.employees:
return self.employees[employee_id]
else:
return False
def list_employees(self):
employee_data = {}
if self.employees:
for employee_id, employee_info in self.employees.items():
employee_details = {}
employee_details["employee_ID"] = employee_id
for key, value in employee_info.items():
employee_details[key] = value
employee_data[employee_id] = employee_details
return employee_data | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
"""
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
"""
Add a new employee to the HRManagementSystem.
:param employee_id: The employee's id, int.
:param name: The employee's name, str.
:param position: The employee's position, str.
:param department: The employee's department, str.
:param salary: The employee's salary, int.
:return: If the employee is already in the HRManagementSystem, returns False, otherwise, returns True.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
True
>>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)
False
"""
def remove_employee(self, employee_id):
"""
Remove an employee from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.remove_employee(1)
True
>>> hrManagementSystem.remove_employee(2)
False
"""
def update_employee(self, employee_id: int, employee_info: dict):
"""
Update an employee's information in the HRManagementSystem.
:param employee_id: The employee's id, int.
:param employee_info: The employee's information, dict.
:return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
True
>>> hrManagementSystem.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})
False
"""
def get_employee(self, employee_id):
"""
Get an employee's information from the HRManagementSystem.
:param employee_id: The employee's id, int.
:return: If the employee is already in the HRManagementSystem, returns the employee's information, otherwise, returns False.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.get_employee(1)
{'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}
>>> hrManagementSystem.get_employee(2)
False
"""
def list_employees(self):
“”“
List all employees' information in the HRManagementSystem.
:return: A list of all employees' information,dict.
>>> hrManagementSystem = HRManagementSystem()
>>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
>>> hrManagementSystem.list_employees()
{1: {'employee_ID': 1, 'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}
""" | def list_employees(self):
employee_data = {}
if self.employees:
for employee_id, employee_info in self.employees.items():
employee_details = {}
employee_details["employee_ID"] = employee_id
for key, value in employee_info.items():
employee_details[key] = value
employee_data[employee_id] = employee_details
return employee_data | List all employees' information in the HRManagementSystem. |
ClassEval_44_sum | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
This is a class as util for html, supporting for formatting and extracting code from HTML text, including cleaning up the text and converting certain elements into specific marks.
"""
def __init__(self):
self.SPACE_MARK = '-SPACE-'
self.JSON_MARK = '-JSON-'
self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-'
self.URL_MARK = '-URL-'
self.NUMBER_MARK = '-NUMBER-'
self.TRACE_MARK = '-TRACE-'
self.COMMAND_MARK = '-COMMAND-'
self.COMMENT_MARK = '-COMMENT-'
self.CODE_MARK = '-CODE-'
@staticmethod
def format_line_html_text(self, html_text):
"""
get the html text without the code, and add the code tag -CODE- where the code is
:param html_text:string
:return:string
>>>htmlutil = HtmlUtil()
>>>htmlutil.format_line_html_text(<html>
>>> <body>
>>> <h1>Title</h1>
>>> <p>This is a paragraph.</p>
>>> <pre>print('Hello, world!')</pre>
>>> <p>Another paragraph.</p>
>>> <pre><code>for i in range(5):
>>> print(i)</code></pre>
>>> </body>
>>> </html>)
Title
This is a paragraph.
-CODE-
Another paragraph.
-CODE-
"""
if html_text is None or len(html_text) == 0:
return ''
soup = BeautifulSoup(html_text, 'lxml')
code_tag = soup.find_all(name=['pre', 'blockquote'])
for tag in code_tag:
tag.string = self.CODE_MARK
ul_ol_group = soup.find_all(name=['ul', 'ol'])
for ul_ol_item in ul_ol_group:
li_group = ul_ol_item.find_all('li')
for li_item in li_group:
li_item_text = li_item.get_text().strip()
if len(li_item_text) == 0:
continue
if li_item_text[-1] in string.punctuation:
li_item.string = '[{0}]{1}'.format('-', li_item_text)
continue
li_item.string = '[{0}]{1}.'.format('-', li_item_text)
p_group = soup.find_all(name=['p'])
for p_item in p_group:
p_item_text = p_item.get_text().strip()
if p_item_text:
if p_item_text[-1] in string.punctuation:
p_item.string = p_item_text
continue
next_sibling = p_item.find_next_sibling()
if next_sibling and self.CODE_MARK in next_sibling.get_text():
p_item.string = p_item_text + ':'
continue
p_item.string = p_item_text + '.'
clean_text = gensim.utils.decode_htmlentities(soup.get_text())
return self.__format_line_feed(clean_text)
def extract_code_from_html_text(self, html_text):
"""
extract codes from the html body
:param html_text: string, html text
:return: the list of code
>>>htmlutil = HtmlUtil()
>>>htmlutil.extract_code_from_html_text(<html>
>>> <body>
>>> <h1>Title</h1>
>>> <p>This is a paragraph.</p>
>>> <pre>print('Hello, world!')</pre>
>>> <p>Another paragraph.</p>
>>> <pre><code>for i in range(5):
>>> print(i)</code></pre>
>>> </body>
>>> </html>)
["print('Hello, world!')", 'for i in range(5):\n print(i)']
"""
text_with_code_tag = self.format_line_html_text(html_text)
if self.CODE_MARK not in text_with_code_tag:
return []
code_index_start = 0
soup = BeautifulSoup(html_text, 'lxml')
code_tag = soup.find_all(name=['pre', 'blockquote'])
code_count = text_with_code_tag.count(self.CODE_MARK)
code_list = []
for code_index in range(code_index_start, code_index_start + code_count):
code = code_tag[code_index].get_text()
if code:
code_list.append(code)
return code_list | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
This is a class as util for html, supporting for formatting and extracting code from HTML text, including cleaning up the text and converting certain elements into specific marks.
"""
def __init__(self):
"""
Initialize a series of labels
"""
self.SPACE_MARK = '-SPACE-'
self.JSON_MARK = '-JSON-'
self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-'
self.URL_MARK = '-URL-'
self.NUMBER_MARK = '-NUMBER-'
self.TRACE_MARK = '-TRACE-'
self.COMMAND_MARK = '-COMMAND-'
self.COMMENT_MARK = '-COMMENT-'
self.CODE_MARK = '-CODE-'
@staticmethod
def format_line_html_text(self, html_text):
"""
get the html text without the code, and add the code tag -CODE- where the code is
:param html_text:string
:return:string
>>>htmlutil = HtmlUtil()
>>>htmlutil.format_line_html_text(<html>
>>> <body>
>>> <h1>Title</h1>
>>> <p>This is a paragraph.</p>
>>> <pre>print('Hello, world!')</pre>
>>> <p>Another paragraph.</p>
>>> <pre><code>for i in range(5):
>>> print(i)</code></pre>
>>> </body>
>>> </html>)
Title
This is a paragraph.
-CODE-
Another paragraph.
-CODE-
"""
def extract_code_from_html_text(self, html_text):
"""
extract codes from the html body
:param html_text: string, html text
:return: the list of code
>>>htmlutil = HtmlUtil()
>>>htmlutil.extract_code_from_html_text(<html>
>>> <body>
>>> <h1>Title</h1>
>>> <p>This is a paragraph.</p>
>>> <pre>print('Hello, world!')</pre>
>>> <p>Another paragraph.</p>
>>> <pre><code>for i in range(5):
>>> print(i)</code></pre>
>>> </body>
>>> </html>)
["print('Hello, world!')", 'for i in range(5):\n print(i)']
""" | def __format_line_feed(text):
return re.sub(re.compile(r'\n+'), '\n', text) | Replace consecutive line breaks with a single line break |
ClassEval_44_sum | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
This is a class as util for html, supporting for formatting and extracting code from HTML text, including cleaning up the text and converting certain elements into specific marks.
"""
def __init__(self):
self.SPACE_MARK = '-SPACE-'
self.JSON_MARK = '-JSON-'
self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-'
self.URL_MARK = '-URL-'
self.NUMBER_MARK = '-NUMBER-'
self.TRACE_MARK = '-TRACE-'
self.COMMAND_MARK = '-COMMAND-'
self.COMMENT_MARK = '-COMMENT-'
self.CODE_MARK = '-CODE-'
@staticmethod
def __format_line_feed(text):
"""
Replace consecutive line breaks with a single line break
:param text: string with consecutive line breaks
:return:string, replaced text with single line break
"""
return re.sub(re.compile(r'\n+'), '\n', text)
def extract_code_from_html_text(self, html_text):
"""
extract codes from the html body
:param html_text: string, html text
:return: the list of code
>>>htmlutil = HtmlUtil()
>>>htmlutil.extract_code_from_html_text(<html>
>>> <body>
>>> <h1>Title</h1>
>>> <p>This is a paragraph.</p>
>>> <pre>print('Hello, world!')</pre>
>>> <p>Another paragraph.</p>
>>> <pre><code>for i in range(5):
>>> print(i)</code></pre>
>>> </body>
>>> </html>)
["print('Hello, world!')", 'for i in range(5):\n print(i)']
"""
text_with_code_tag = self.format_line_html_text(html_text)
if self.CODE_MARK not in text_with_code_tag:
return []
code_index_start = 0
soup = BeautifulSoup(html_text, 'lxml')
code_tag = soup.find_all(name=['pre', 'blockquote'])
code_count = text_with_code_tag.count(self.CODE_MARK)
code_list = []
for code_index in range(code_index_start, code_index_start + code_count):
code = code_tag[code_index].get_text()
if code:
code_list.append(code)
return code_list | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
This is a class as util for html, supporting for formatting and extracting code from HTML text, including cleaning up the text and converting certain elements into specific marks.
"""
def __init__(self):
"""
Initialize a series of labels
"""
self.SPACE_MARK = '-SPACE-'
self.JSON_MARK = '-JSON-'
self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-'
self.URL_MARK = '-URL-'
self.NUMBER_MARK = '-NUMBER-'
self.TRACE_MARK = '-TRACE-'
self.COMMAND_MARK = '-COMMAND-'
self.COMMENT_MARK = '-COMMENT-'
self.CODE_MARK = '-CODE-'
@staticmethod
def __format_line_feed(text):
"""
Replace consecutive line breaks with a single line break
:param text: string with consecutive line breaks
:return:string, replaced text with single line break
"""
def extract_code_from_html_text(self, html_text):
"""
extract codes from the html body
:param html_text: string, html text
:return: the list of code
>>>htmlutil = HtmlUtil()
>>>htmlutil.extract_code_from_html_text(<html>
>>> <body>
>>> <h1>Title</h1>
>>> <p>This is a paragraph.</p>
>>> <pre>print('Hello, world!')</pre>
>>> <p>Another paragraph.</p>
>>> <pre><code>for i in range(5):
>>> print(i)</code></pre>
>>> </body>
>>> </html>)
["print('Hello, world!')", 'for i in range(5):\n print(i)']
""" | def format_line_html_text(self, html_text):
if html_text is None or len(html_text) == 0:
return ''
soup = BeautifulSoup(html_text, 'lxml')
code_tag = soup.find_all(name=['pre', 'blockquote'])
for tag in code_tag:
tag.string = self.CODE_MARK
ul_ol_group = soup.find_all(name=['ul', 'ol'])
for ul_ol_item in ul_ol_group:
li_group = ul_ol_item.find_all('li')
for li_item in li_group:
li_item_text = li_item.get_text().strip()
if len(li_item_text) == 0:
continue
if li_item_text[-1] in string.punctuation:
li_item.string = '[{0}]{1}'.format('-', li_item_text)
continue
li_item.string = '[{0}]{1}.'.format('-', li_item_text)
p_group = soup.find_all(name=['p'])
for p_item in p_group:
p_item_text = p_item.get_text().strip()
if p_item_text:
if p_item_text[-1] in string.punctuation:
p_item.string = p_item_text
continue
next_sibling = p_item.find_next_sibling()
if next_sibling and self.CODE_MARK in next_sibling.get_text():
p_item.string = p_item_text + ':'
continue
p_item.string = p_item_text + '.'
clean_text = gensim.utils.decode_htmlentities(soup.get_text())
return self.__format_line_feed(clean_text) | get the html text without the code, and add the code tag -CODE- where the code is |
ClassEval_44_sum | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
This is a class as util for html, supporting for formatting and extracting code from HTML text, including cleaning up the text and converting certain elements into specific marks.
"""
def __init__(self):
self.SPACE_MARK = '-SPACE-'
self.JSON_MARK = '-JSON-'
self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-'
self.URL_MARK = '-URL-'
self.NUMBER_MARK = '-NUMBER-'
self.TRACE_MARK = '-TRACE-'
self.COMMAND_MARK = '-COMMAND-'
self.COMMENT_MARK = '-COMMENT-'
self.CODE_MARK = '-CODE-'
@staticmethod
def __format_line_feed(text):
"""
Replace consecutive line breaks with a single line break
:param text: string with consecutive line breaks
:return:string, replaced text with single line break
"""
return re.sub(re.compile(r'\n+'), '\n', text)
def format_line_html_text(self, html_text):
"""
get the html text without the code, and add the code tag -CODE- where the code is
:param html_text:string
:return:string
>>>htmlutil = HtmlUtil()
>>>htmlutil.format_line_html_text(<html>
>>> <body>
>>> <h1>Title</h1>
>>> <p>This is a paragraph.</p>
>>> <pre>print('Hello, world!')</pre>
>>> <p>Another paragraph.</p>
>>> <pre><code>for i in range(5):
>>> print(i)</code></pre>
>>> </body>
>>> </html>)
Title
This is a paragraph.
-CODE-
Another paragraph.
-CODE-
"""
if html_text is None or len(html_text) == 0:
return ''
soup = BeautifulSoup(html_text, 'lxml')
code_tag = soup.find_all(name=['pre', 'blockquote'])
for tag in code_tag:
tag.string = self.CODE_MARK
ul_ol_group = soup.find_all(name=['ul', 'ol'])
for ul_ol_item in ul_ol_group:
li_group = ul_ol_item.find_all('li')
for li_item in li_group:
li_item_text = li_item.get_text().strip()
if len(li_item_text) == 0:
continue
if li_item_text[-1] in string.punctuation:
li_item.string = '[{0}]{1}'.format('-', li_item_text)
continue
li_item.string = '[{0}]{1}.'.format('-', li_item_text)
p_group = soup.find_all(name=['p'])
for p_item in p_group:
p_item_text = p_item.get_text().strip()
if p_item_text:
if p_item_text[-1] in string.punctuation:
p_item.string = p_item_text
continue
next_sibling = p_item.find_next_sibling()
if next_sibling and self.CODE_MARK in next_sibling.get_text():
p_item.string = p_item_text + ':'
continue
p_item.string = p_item_text + '.'
clean_text = gensim.utils.decode_htmlentities(soup.get_text())
return self.__format_line_feed(clean_text)
def extract_code_from_html_text(self, html_text):
text_with_code_tag = self.format_line_html_text(html_text)
if self.CODE_MARK not in text_with_code_tag:
return []
code_index_start = 0
soup = BeautifulSoup(html_text, 'lxml')
code_tag = soup.find_all(name=['pre', 'blockquote'])
code_count = text_with_code_tag.count(self.CODE_MARK)
code_list = []
for code_index in range(code_index_start, code_index_start + code_count):
code = code_tag[code_index].get_text()
if code:
code_list.append(code)
return code_list | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
This is a class as util for html, supporting for formatting and extracting code from HTML text, including cleaning up the text and converting certain elements into specific marks.
"""
def __init__(self):
"""
Initialize a series of labels
"""
self.SPACE_MARK = '-SPACE-'
self.JSON_MARK = '-JSON-'
self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-'
self.URL_MARK = '-URL-'
self.NUMBER_MARK = '-NUMBER-'
self.TRACE_MARK = '-TRACE-'
self.COMMAND_MARK = '-COMMAND-'
self.COMMENT_MARK = '-COMMENT-'
self.CODE_MARK = '-CODE-'
@staticmethod
def __format_line_feed(text):
"""
Replace consecutive line breaks with a single line break
:param text: string with consecutive line breaks
:return:string, replaced text with single line break
"""
def format_line_html_text(self, html_text):
"""
get the html text without the code, and add the code tag -CODE- where the code is
:param html_text:string
:return:string
>>>htmlutil = HtmlUtil()
>>>htmlutil.format_line_html_text(<html>
>>> <body>
>>> <h1>Title</h1>
>>> <p>This is a paragraph.</p>
>>> <pre>print('Hello, world!')</pre>
>>> <p>Another paragraph.</p>
>>> <pre><code>for i in range(5):
>>> print(i)</code></pre>
>>> </body>
>>> </html>)
Title
This is a paragraph.
-CODE-
Another paragraph.
-CODE-
"""
def extract_code_from_html_text(self, html_text):
"""
extract codes from the html body
:param html_text: string, html text
:return: the list of code
>>>htmlutil = HtmlUtil()
>>>htmlutil.extract_code_from_html_text(<html>
>>> <body>
>>> <h1>Title</h1>
>>> <p>This is a paragraph.</p>
>>> <pre>print('Hello, world!')</pre>
>>> <p>Another paragraph.</p>
>>> <pre><code>for i in range(5):
>>> print(i)</code></pre>
>>> </body>
>>> </html>)
["print('Hello, world!')", 'for i in range(5):\n print(i)']
""" | def extract_code_from_html_text(self, html_text):
text_with_code_tag = self.format_line_html_text(html_text)
if self.CODE_MARK not in text_with_code_tag:
return []
code_index_start = 0
soup = BeautifulSoup(html_text, 'lxml')
code_tag = soup.find_all(name=['pre', 'blockquote'])
code_count = text_with_code_tag.count(self.CODE_MARK)
code_list = []
for code_index in range(code_index_start, code_index_start + code_count):
code = code_tag[code_index].get_text()
if code:
code_list.append(code)
return code_list | extract codes from the html body |
ClassEval_45_sum | from PIL import Image, ImageEnhance, ImageChops
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
self.image = None
def save_image(self, save_path):
"""
Save image to a path if image has opened
:param save_path: str, the path that the image will be saved
>>> processor.load_image('test.jpg')
>>> processor.save_image('test2.jpg')
"""
if self.image:
self.image.save(save_path)
def resize_image(self, width, height):
"""
Risize the image if image has opened.
:param width: int, the target width of image
:param height: int, the target height of image
>>> processor.load_image('test.jpg')
>>> processor.resize_image(300, 300)
>>> processor.image.width
300
>>> processor.image.height
300
"""
if self.image:
self.image = self.image.resize((width, height))
def rotate_image(self, degrees):
"""
rotate image if image has opened
:param degrees: float, the degrees that the image will be rotated
>>> processor.load_image('test.jpg')
>>> processor.resize_image(90)
"""
if self.image:
self.image = self.image.rotate(degrees)
def adjust_brightness(self, factor):
"""
Adjust the brightness of image if image has opened.
:param factor: float, brightness of an image. A factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
>>> processor.load_image('test.jpg')
>>> processor.adjust_brightness(0.5)
"""
if self.image:
enhancer = ImageEnhance.Brightness(self.image)
self.image = enhancer.enhance(factor) | from PIL import Image, ImageEnhance
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
"""
Initialize self.image
"""
self.image = None
def save_image(self, save_path):
"""
Save image to a path if image has opened
:param save_path: str, the path that the image will be saved
>>> processor.load_image('test.jpg')
>>> processor.save_image('test2.jpg')
"""
def resize_image(self, width, height):
"""
Risize the image if image has opened.
:param width: int, the target width of image
:param height: int, the target height of image
>>> processor.load_image('test.jpg')
>>> processor.resize_image(300, 300)
>>> processor.image.width
300
>>> processor.image.height
300
"""
def rotate_image(self, degrees):
"""
rotate image if image has opened
:param degrees: float, the degrees that the image will be rotated
>>> processor.load_image('test.jpg')
>>> processor.resize_image(90)
"""
def adjust_brightness(self, factor):
"""
Adjust the brightness of image if image has opened.
:param factor: float, brightness of an image. A factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
>>> processor.load_image('test.jpg')
>>> processor.adjust_brightness(0.5)
""" | def load_image(self, image_path):
self.image = Image.open(image_path) | Use Image util in PIL to open a image |
ClassEval_45_sum | from PIL import Image, ImageEnhance, ImageChops
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
self.image = None
def load_image(self, image_path):
"""
Use Image util in PIL to open a image
:param image_path: str, path of image that is to be
>>> processor.load_image('test.jpg')
>>> processor.image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=3072x4096 at 0x194F2412A48>
"""
self.image = Image.open(image_path)
def resize_image(self, width, height):
"""
Risize the image if image has opened.
:param width: int, the target width of image
:param height: int, the target height of image
>>> processor.load_image('test.jpg')
>>> processor.resize_image(300, 300)
>>> processor.image.width
300
>>> processor.image.height
300
"""
if self.image:
self.image = self.image.resize((width, height))
def rotate_image(self, degrees):
"""
rotate image if image has opened
:param degrees: float, the degrees that the image will be rotated
>>> processor.load_image('test.jpg')
>>> processor.resize_image(90)
"""
if self.image:
self.image = self.image.rotate(degrees)
def adjust_brightness(self, factor):
"""
Adjust the brightness of image if image has opened.
:param factor: float, brightness of an image. A factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
>>> processor.load_image('test.jpg')
>>> processor.adjust_brightness(0.5)
"""
if self.image:
enhancer = ImageEnhance.Brightness(self.image)
self.image = enhancer.enhance(factor) | from PIL import Image, ImageEnhance
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
"""
Initialize self.image
"""
self.image = None
def load_image(self, image_path):
"""
Use Image util in PIL to open a image
:param image_path: str, path of image that is to be
>>> processor.load_image('test.jpg')
>>> processor.image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=3072x4096 at 0x194F2412A48>
"""
def resize_image(self, width, height):
"""
Risize the image if image has opened.
:param width: int, the target width of image
:param height: int, the target height of image
>>> processor.load_image('test.jpg')
>>> processor.resize_image(300, 300)
>>> processor.image.width
300
>>> processor.image.height
300
"""
def rotate_image(self, degrees):
"""
rotate image if image has opened
:param degrees: float, the degrees that the image will be rotated
>>> processor.load_image('test.jpg')
>>> processor.resize_image(90)
"""
def adjust_brightness(self, factor):
"""
Adjust the brightness of image if image has opened.
:param factor: float, brightness of an image. A factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
>>> processor.load_image('test.jpg')
>>> processor.adjust_brightness(0.5)
""" | def save_image(self, save_path):
if self.image:
self.image.save(save_path) | Save image to a path if image has opened |
ClassEval_45_sum | from PIL import Image, ImageEnhance, ImageChops
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
self.image = None
def load_image(self, image_path):
"""
Use Image util in PIL to open a image
:param image_path: str, path of image that is to be
>>> processor.load_image('test.jpg')
>>> processor.image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=3072x4096 at 0x194F2412A48>
"""
self.image = Image.open(image_path)
def save_image(self, save_path):
"""
Save image to a path if image has opened
:param save_path: str, the path that the image will be saved
>>> processor.load_image('test.jpg')
>>> processor.save_image('test2.jpg')
"""
if self.image:
self.image.save(save_path)
def rotate_image(self, degrees):
"""
rotate image if image has opened
:param degrees: float, the degrees that the image will be rotated
>>> processor.load_image('test.jpg')
>>> processor.resize_image(90)
"""
if self.image:
self.image = self.image.rotate(degrees)
def adjust_brightness(self, factor):
"""
Adjust the brightness of image if image has opened.
:param factor: float, brightness of an image. A factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
>>> processor.load_image('test.jpg')
>>> processor.adjust_brightness(0.5)
"""
if self.image:
enhancer = ImageEnhance.Brightness(self.image)
self.image = enhancer.enhance(factor) | from PIL import Image, ImageEnhance
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
"""
Initialize self.image
"""
self.image = None
def load_image(self, image_path):
"""
Use Image util in PIL to open a image
:param image_path: str, path of image that is to be
>>> processor.load_image('test.jpg')
>>> processor.image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=3072x4096 at 0x194F2412A48>
"""
def save_image(self, save_path):
"""
Save image to a path if image has opened
:param save_path: str, the path that the image will be saved
>>> processor.load_image('test.jpg')
>>> processor.save_image('test2.jpg')
"""
def rotate_image(self, degrees):
"""
rotate image if image has opened
:param degrees: float, the degrees that the image will be rotated
>>> processor.load_image('test.jpg')
>>> processor.resize_image(90)
"""
def adjust_brightness(self, factor):
"""
Adjust the brightness of image if image has opened.
:param factor: float, brightness of an image. A factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
>>> processor.load_image('test.jpg')
>>> processor.adjust_brightness(0.5)
""" | def resize_image(self, width, height):
if self.image:
self.image = self.image.resize((width, height)) | Risize the image if image has opened. |
ClassEval_45_sum | from PIL import Image, ImageEnhance, ImageChops
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
self.image = None
def load_image(self, image_path):
"""
Use Image util in PIL to open a image
:param image_path: str, path of image that is to be
>>> processor.load_image('test.jpg')
>>> processor.image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=3072x4096 at 0x194F2412A48>
"""
self.image = Image.open(image_path)
def save_image(self, save_path):
"""
Save image to a path if image has opened
:param save_path: str, the path that the image will be saved
>>> processor.load_image('test.jpg')
>>> processor.save_image('test2.jpg')
"""
if self.image:
self.image.save(save_path)
def resize_image(self, width, height):
"""
Risize the image if image has opened.
:param width: int, the target width of image
:param height: int, the target height of image
>>> processor.load_image('test.jpg')
>>> processor.resize_image(300, 300)
>>> processor.image.width
300
>>> processor.image.height
300
"""
if self.image:
self.image = self.image.resize((width, height))
def adjust_brightness(self, factor):
"""
Adjust the brightness of image if image has opened.
:param factor: float, brightness of an image. A factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
>>> processor.load_image('test.jpg')
>>> processor.adjust_brightness(0.5)
"""
if self.image:
enhancer = ImageEnhance.Brightness(self.image)
self.image = enhancer.enhance(factor) | from PIL import Image, ImageEnhance
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
"""
Initialize self.image
"""
self.image = None
def load_image(self, image_path):
"""
Use Image util in PIL to open a image
:param image_path: str, path of image that is to be
>>> processor.load_image('test.jpg')
>>> processor.image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=3072x4096 at 0x194F2412A48>
"""
def save_image(self, save_path):
"""
Save image to a path if image has opened
:param save_path: str, the path that the image will be saved
>>> processor.load_image('test.jpg')
>>> processor.save_image('test2.jpg')
"""
def resize_image(self, width, height):
"""
Risize the image if image has opened.
:param width: int, the target width of image
:param height: int, the target height of image
>>> processor.load_image('test.jpg')
>>> processor.resize_image(300, 300)
>>> processor.image.width
300
>>> processor.image.height
300
"""
def adjust_brightness(self, factor):
"""
Adjust the brightness of image if image has opened.
:param factor: float, brightness of an image. A factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
>>> processor.load_image('test.jpg')
>>> processor.adjust_brightness(0.5)
""" | def rotate_image(self, degrees):
if self.image:
self.image = self.image.rotate(degrees) | rotate image if image has opened |
ClassEval_45_sum | from PIL import Image, ImageEnhance, ImageChops
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
self.image = None
def load_image(self, image_path):
"""
Use Image util in PIL to open a image
:param image_path: str, path of image that is to be
>>> processor.load_image('test.jpg')
>>> processor.image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=3072x4096 at 0x194F2412A48>
"""
self.image = Image.open(image_path)
def save_image(self, save_path):
"""
Save image to a path if image has opened
:param save_path: str, the path that the image will be saved
>>> processor.load_image('test.jpg')
>>> processor.save_image('test2.jpg')
"""
if self.image:
self.image.save(save_path)
def resize_image(self, width, height):
"""
Risize the image if image has opened.
:param width: int, the target width of image
:param height: int, the target height of image
>>> processor.load_image('test.jpg')
>>> processor.resize_image(300, 300)
>>> processor.image.width
300
>>> processor.image.height
300
"""
if self.image:
self.image = self.image.resize((width, height))
def rotate_image(self, degrees):
"""
rotate image if image has opened
:param degrees: float, the degrees that the image will be rotated
>>> processor.load_image('test.jpg')
>>> processor.resize_image(90)
"""
if self.image:
self.image = self.image.rotate(degrees)
def adjust_brightness(self, factor):
if self.image:
enhancer = ImageEnhance.Brightness(self.image)
self.image = enhancer.enhance(factor) | from PIL import Image, ImageEnhance
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
"""
Initialize self.image
"""
self.image = None
def load_image(self, image_path):
"""
Use Image util in PIL to open a image
:param image_path: str, path of image that is to be
>>> processor.load_image('test.jpg')
>>> processor.image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=3072x4096 at 0x194F2412A48>
"""
def save_image(self, save_path):
"""
Save image to a path if image has opened
:param save_path: str, the path that the image will be saved
>>> processor.load_image('test.jpg')
>>> processor.save_image('test2.jpg')
"""
def resize_image(self, width, height):
"""
Risize the image if image has opened.
:param width: int, the target width of image
:param height: int, the target height of image
>>> processor.load_image('test.jpg')
>>> processor.resize_image(300, 300)
>>> processor.image.width
300
>>> processor.image.height
300
"""
def rotate_image(self, degrees):
"""
rotate image if image has opened
:param degrees: float, the degrees that the image will be rotated
>>> processor.load_image('test.jpg')
>>> processor.resize_image(90)
"""
def adjust_brightness(self, factor):
"""
Adjust the brightness of image if image has opened.
:param factor: float, brightness of an image. A factor of 0.0 gives a black image. A factor of 1.0 gives the original image.
>>> processor.load_image('test.jpg')
>>> processor.adjust_brightness(0.5)
""" | def adjust_brightness(self, factor):
if self.image:
enhancer = ImageEnhance.Brightness(self.image)
self.image = enhancer.enhance(factor) | Adjust the brightness of image if image has opened. |
ClassEval_46_sum | class Interpolation:
"""
This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data
"""
def __init__(self):
pass
@staticmethod
def interpolate_1d(x, y, x_interp):
y_interp = []
for xi in x_interp:
for i in range(len(x) - 1):
if x[i] <= xi <= x[i+1]:
yi = y[i] + (y[i+1] - y[i]) * (xi - x[i]) / (x[i+1] - x[i])
y_interp.append(yi)
break
return y_interp
@staticmethod
def interpolate_2d(x, y, z, x_interp, y_interp):
”“”
Linear interpolation of two-dimensional data
:param x: The x-coordinate of the data point, list.
:param y: The y-coordinate of the data point, list.
:param z: The z-coordinate of the data point, list.
:param x_interp: The x-coordinate of the interpolation point, list.
:param y_interp: The y-coordinate of the interpolation point, list.
:return: The z-coordinate of the interpolation point, list.
>>> interpolation = Interpolation()
>>> interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5], [1.5, 2.5])
[3.0, 7.0]
”“”
z_interp = []
for xi, yi in zip(x_interp, y_interp):
for i in range(len(x) - 1):
if x[i] <= xi <= x[i+1]:
for j in range(len(y) - 1):
if y[j] <= yi <= y[j+1]:
z00 = z[i][j]
z01 = z[i][j+1]
z10 = z[i+1][j]
z11 = z[i+1][j+1]
zi = (z00 * (x[i+1] - xi) * (y[j+1] - yi) +
z10 * (xi - x[i]) * (y[j+1] - yi) +
z01 * (x[i+1] - xi) * (yi - y[j]) +
z11 * (xi - x[i]) * (yi - y[j])) / ((x[i+1] - x[i]) * (y[j+1] - y[j]))
z_interp.append(zi)
break
break
return z_interp | class Interpolation:
"""
This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data
"""
def __init__(self):
pass
@staticmethod
@staticmethod
def interpolate_2d(x, y, z, x_interp, y_interp):
”“”
Linear interpolation of two-dimensional data
:param x: The x-coordinate of the data point, list.
:param y: The y-coordinate of the data point, list.
:param z: The z-coordinate of the data point, list.
:param x_interp: The x-coordinate of the interpolation point, list.
:param y_interp: The y-coordinate of the interpolation point, list.
:return: The z-coordinate of the interpolation point, list.
>>> interpolation = Interpolation()
>>> interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5], [1.5, 2.5])
[3.0, 7.0]
”“” | def interpolate_1d(x, y, x_interp):
y_interp = []
for xi in x_interp:
for i in range(len(x) - 1):
if x[i] <= xi <= x[i+1]:
yi = y[i] + (y[i+1] - y[i]) * (xi - x[i]) / (x[i+1] - x[i])
y_interp.append(yi)
break
return y_interp | Linear interpolation of one-dimensional data |
ClassEval_46_sum | class Interpolation:
"""
This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data
"""
def __init__(self):
pass
@staticmethod
def interpolate_1d(x, y, x_interp):
"""
Linear interpolation of one-dimensional data
:param x: The x-coordinate of the data point, list.
:param y: The y-coordinate of the data point, list.
:param x_interp: The x-coordinate of the interpolation point, list.
:return: The y-coordinate of the interpolation point, list.
>>> interpolation = Interpolation()
>>> interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5])
[1.5, 2.5]
"""
y_interp = []
for xi in x_interp:
for i in range(len(x) - 1):
if x[i] <= xi <= x[i+1]:
yi = y[i] + (y[i+1] - y[i]) * (xi - x[i]) / (x[i+1] - x[i])
y_interp.append(yi)
break
return y_interp
@staticmethod
def interpolate_2d(x, y, z, x_interp, y_interp):
z_interp = []
for xi, yi in zip(x_interp, y_interp):
for i in range(len(x) - 1):
if x[i] <= xi <= x[i+1]:
for j in range(len(y) - 1):
if y[j] <= yi <= y[j+1]:
z00 = z[i][j]
z01 = z[i][j+1]
z10 = z[i+1][j]
z11 = z[i+1][j+1]
zi = (z00 * (x[i+1] - xi) * (y[j+1] - yi) +
z10 * (xi - x[i]) * (y[j+1] - yi) +
z01 * (x[i+1] - xi) * (yi - y[j]) +
z11 * (xi - x[i]) * (yi - y[j])) / ((x[i+1] - x[i]) * (y[j+1] - y[j]))
z_interp.append(zi)
break
break
return z_interp | class Interpolation:
"""
This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data
"""
def __init__(self):
pass
@staticmethod
def interpolate_1d(x, y, x_interp):
"""
Linear interpolation of one-dimensional data
:param x: The x-coordinate of the data point, list.
:param y: The y-coordinate of the data point, list.
:param x_interp: The x-coordinate of the interpolation point, list.
:return: The y-coordinate of the interpolation point, list.
>>> interpolation = Interpolation()
>>> interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5])
[1.5, 2.5]
"""
@staticmethod
def interpolate_2d(x, y, z, x_interp, y_interp):
”“”
Linear interpolation of two-dimensional data
:param x: The x-coordinate of the data point, list.
:param y: The y-coordinate of the data point, list.
:param z: The z-coordinate of the data point, list.
:param x_interp: The x-coordinate of the interpolation point, list.
:param y_interp: The y-coordinate of the interpolation point, list.
:return: The z-coordinate of the interpolation point, list.
>>> interpolation = Interpolation()
>>> interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5], [1.5, 2.5])
[3.0, 7.0]
”“” | @staticmethod
def interpolate_2d(x, y, z, x_interp, y_interp):
z_interp = []
for xi, yi in zip(x_interp, y_interp):
for i in range(len(x) - 1):
if x[i] <= xi <= x[i+1]:
for j in range(len(y) - 1):
if y[j] <= yi <= y[j+1]:
z00 = z[i][j]
z01 = z[i][j+1]
z10 = z[i+1][j]
z11 = z[i+1][j+1]
zi = (z00 * (x[i+1] - xi) * (y[j+1] - yi) +
z10 * (xi - x[i]) * (y[j+1] - yi) +
z01 * (x[i+1] - xi) * (yi - y[j]) +
z11 * (xi - x[i]) * (yi - y[j])) / ((x[i+1] - x[i]) * (y[j+1] - y[j]))
z_interp.append(zi)
break
break
return z_interp | Linear interpolation of two-dimensional data |
ClassEval_47_sum | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
self.ip_address = ip_address
def get_octets(self):
"""
If the IP address is valid, the list of four decimal numbers separated by "." constituting the IP address is returned; otherwise, an empty list is returned
:return: list
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.get_octets()
["10", "10", "10", "10"]
"""
if self.is_valid():
return self.ip_address.split('.')
else:
return []
def get_binary(self):
"""
If the IP address is valid, return the binary form of the IP address; otherwise, return ''
:return: string
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.get_binary()
"00001010.00001010.00001010.00001010"
"""
if self.is_valid():
binary_octets = []
for octet in self.get_octets():
binary_octets.append(format(int(octet), '08b'))
return '.'.join(binary_octets)
else:
return '' | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
"""
Initialize the IP address to the specified address
:param ip_address:string
"""
self.ip_address = ip_address
def get_octets(self):
"""
If the IP address is valid, the list of four decimal numbers separated by "." constituting the IP address is returned; otherwise, an empty list is returned
:return: list
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.get_octets()
["10", "10", "10", "10"]
"""
def get_binary(self):
"""
If the IP address is valid, return the binary form of the IP address; otherwise, return ''
:return: string
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.get_binary()
"00001010.00001010.00001010.00001010"
""" | def is_valid(self):
octets = self.ip_address.split('.')
if len(octets) != 4:
return False
for octet in octets:
if not octet.isdigit() or int(octet) < 0 or int(octet) > 255:
return False
return True | Judge whether the IP address is valid, that is, whether the IP address is composed of four Decimal digits separated by '.'. Each digit is greater than or equal to 0 and less than or equal to 255 |
ClassEval_47_sum | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
self.ip_address = ip_address
def is_valid(self):
"""
Judge whether the IP address is valid, that is, whether the IP address is composed of four Decimal digits separated by '.'. Each digit is greater than or equal to 0 and less than or equal to 255
:return: bool
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.is_valid()
True
"""
octets = self.ip_address.split('.')
if len(octets) != 4:
return False
for octet in octets:
if not octet.isdigit() or int(octet) < 0 or int(octet) > 255:
return False
return True
def get_binary(self):
"""
If the IP address is valid, return the binary form of the IP address; otherwise, return ''
:return: string
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.get_binary()
"00001010.00001010.00001010.00001010"
"""
if self.is_valid():
binary_octets = []
for octet in self.get_octets():
binary_octets.append(format(int(octet), '08b'))
return '.'.join(binary_octets)
else:
return '' | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
"""
Initialize the IP address to the specified address
:param ip_address:string
"""
self.ip_address = ip_address
def is_valid(self):
"""
Judge whether the IP address is valid, that is, whether the IP address is composed of four Decimal digits separated by '.'. Each digit is greater than or equal to 0 and less than or equal to 255
:return: bool
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.is_valid()
True
"""
def get_binary(self):
"""
If the IP address is valid, return the binary form of the IP address; otherwise, return ''
:return: string
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.get_binary()
"00001010.00001010.00001010.00001010"
""" | def get_octets(self):
if self.is_valid():
return self.ip_address.split('.')
else:
return [] | If the IP address is valid, the list of four decimal numbers separated by "." constituting the IP address is returned; otherwise, an empty list is returned |
ClassEval_47_sum | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
self.ip_address = ip_address
def is_valid(self):
"""
Judge whether the IP address is valid, that is, whether the IP address is composed of four Decimal digits separated by '.'. Each digit is greater than or equal to 0 and less than or equal to 255
:return: bool
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.is_valid()
True
"""
octets = self.ip_address.split('.')
if len(octets) != 4:
return False
for octet in octets:
if not octet.isdigit() or int(octet) < 0 or int(octet) > 255:
return False
return True
def get_octets(self):
"""
If the IP address is valid, the list of four decimal numbers separated by "." constituting the IP address is returned; otherwise, an empty list is returned
:return: list
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.get_octets()
["10", "10", "10", "10"]
"""
if self.is_valid():
return self.ip_address.split('.')
else:
return []
def get_binary(self):
if self.is_valid():
binary_octets = []
for octet in self.get_octets():
binary_octets.append(format(int(octet), '08b'))
return '.'.join(binary_octets)
else:
return '' | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
"""
Initialize the IP address to the specified address
:param ip_address:string
"""
self.ip_address = ip_address
def is_valid(self):
"""
Judge whether the IP address is valid, that is, whether the IP address is composed of four Decimal digits separated by '.'. Each digit is greater than or equal to 0 and less than or equal to 255
:return: bool
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.is_valid()
True
"""
def get_octets(self):
"""
If the IP address is valid, the list of four decimal numbers separated by "." constituting the IP address is returned; otherwise, an empty list is returned
:return: list
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.get_octets()
["10", "10", "10", "10"]
"""
def get_binary(self):
"""
If the IP address is valid, return the binary form of the IP address; otherwise, return ''
:return: string
>>> ipaddress = IPAddress("10.10.10.10")
>>> ipaddress.get_binary()
"00001010.00001010.00001010.00001010"
""" | def get_binary(self):
if self.is_valid():
binary_octets = []
for octet in self.get_octets():
binary_octets.append(format(int(octet), '08b'))
return '.'.join(binary_octets)
else:
return '' | If the IP address is valid, return the binary form of the IP address; otherwise, return '' |
ClassEval_48_sum | import socket
class IpUtil:
"""
This is a class as tool for ip that can be used to obtain the local IP address, validate its validity, and also provides the functionality to retrieve the corresponding hostname.
"""
@staticmethod
@staticmethod
def is_valid_ipv6(ip_address):
"""
Check if the given IP address is a valid IPv6 address.
:param ip_address:string, the IP address to check
:return:bool, True if the IP address is valid, False otherwise
>>> IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')
True
>>> IpUtil.is_valid_ipv6('2001:0db8:85a3:::8a2e:0370:7334')
False
"""
try:
socket.inet_pton(socket.AF_INET6, ip_address)
return True
except socket.error:
return False
@staticmethod
def get_hostname(ip_address):
"""
Get the hostname associated with the given IP address.
:param ip_address:string, the IP address to get the hostname for
:return: string, the hostname associated with the IP address
>>> IpUtil.get_hostname('110.242.68.3')
'www.baidu.com'
>>> IpUtil.get_hostname('10.0.0.1')
"""
try:
hostname = socket.gethostbyaddr(ip_address)[0]
return hostname
except socket.herror:
return None | import socket
import netifaces
class IpUtil:
"""
This is a class as tool for ip that can be used to obtain the local IP address, validate its validity, and also provides the functionality to retrieve the corresponding hostname.
"""
@staticmethod
@staticmethod
def is_valid_ipv6(ip_address):
"""
Check if the given IP address is a valid IPv6 address.
:param ip_address:string, the IP address to check
:return:bool, True if the IP address is valid, False otherwise
>>> IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')
True
>>> IpUtil.is_valid_ipv6('2001:0db8:85a3:::8a2e:0370:7334')
False
"""
@staticmethod
def get_hostname(ip_address):
"""
Get the hostname associated with the given IP address.
:param ip_address:string, the IP address to get the hostname for
:return: string, the hostname associated with the IP address
>>> IpUtil.get_hostname('110.242.68.3')
'www.baidu.com'
>>> IpUtil.get_hostname('10.0.0.1')
""" | def is_valid_ipv4(ip_address):
try:
socket.inet_pton(socket.AF_INET, ip_address)
return True
except socket.error:
return False | Check if the given IP address is a valid IPv4 address. |
ClassEval_48_sum | import socket
class IpUtil:
"""
This is a class as tool for ip that can be used to obtain the local IP address, validate its validity, and also provides the functionality to retrieve the corresponding hostname.
"""
@staticmethod
def is_valid_ipv4(ip_address):
"""
Check if the given IP address is a valid IPv4 address.
:param ip_address: string, the IP address to check
:return: bool, True if the IP address is valid, False otherwise
>>> IpUtil.is_valid_ipv4('192.168.0.123')
True
>>> IpUtil.is_valid_ipv4('256.0.0.0')
False
"""
try:
socket.inet_pton(socket.AF_INET, ip_address)
return True
except socket.error:
return False
@staticmethod
def get_hostname(ip_address):
"""
Get the hostname associated with the given IP address.
:param ip_address:string, the IP address to get the hostname for
:return: string, the hostname associated with the IP address
>>> IpUtil.get_hostname('110.242.68.3')
'www.baidu.com'
>>> IpUtil.get_hostname('10.0.0.1')
"""
try:
hostname = socket.gethostbyaddr(ip_address)[0]
return hostname
except socket.herror:
return None | import socket
import netifaces
class IpUtil:
"""
This is a class as tool for ip that can be used to obtain the local IP address, validate its validity, and also provides the functionality to retrieve the corresponding hostname.
"""
@staticmethod
def is_valid_ipv4(ip_address):
"""
Check if the given IP address is a valid IPv4 address.
:param ip_address: string, the IP address to check
:return: bool, True if the IP address is valid, False otherwise
>>> IpUtil.is_valid_ipv4('192.168.0.123')
True
>>> IpUtil.is_valid_ipv4('256.0.0.0')
False
"""
@staticmethod
def get_hostname(ip_address):
"""
Get the hostname associated with the given IP address.
:param ip_address:string, the IP address to get the hostname for
:return: string, the hostname associated with the IP address
>>> IpUtil.get_hostname('110.242.68.3')
'www.baidu.com'
>>> IpUtil.get_hostname('10.0.0.1')
""" | @staticmethod
def is_valid_ipv6(ip_address):
try:
socket.inet_pton(socket.AF_INET6, ip_address)
return True
except socket.error:
return False | Check if the given IP address is a valid IPv6 address. |
ClassEval_48_sum | import socket
class IpUtil:
"""
This is a class as tool for ip that can be used to obtain the local IP address, validate its validity, and also provides the functionality to retrieve the corresponding hostname.
"""
@staticmethod
def is_valid_ipv4(ip_address):
"""
Check if the given IP address is a valid IPv4 address.
:param ip_address: string, the IP address to check
:return: bool, True if the IP address is valid, False otherwise
>>> IpUtil.is_valid_ipv4('192.168.0.123')
True
>>> IpUtil.is_valid_ipv4('256.0.0.0')
False
"""
try:
socket.inet_pton(socket.AF_INET, ip_address)
return True
except socket.error:
return False
@staticmethod
def is_valid_ipv6(ip_address):
"""
Check if the given IP address is a valid IPv6 address.
:param ip_address:string, the IP address to check
:return:bool, True if the IP address is valid, False otherwise
>>> IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')
True
>>> IpUtil.is_valid_ipv6('2001:0db8:85a3:::8a2e:0370:7334')
False
"""
try:
socket.inet_pton(socket.AF_INET6, ip_address)
return True
except socket.error:
return False
@staticmethod
def get_hostname(ip_address):
try:
hostname = socket.gethostbyaddr(ip_address)[0]
return hostname
except socket.herror:
return None | import socket
import netifaces
class IpUtil:
"""
This is a class as tool for ip that can be used to obtain the local IP address, validate its validity, and also provides the functionality to retrieve the corresponding hostname.
"""
@staticmethod
def is_valid_ipv4(ip_address):
"""
Check if the given IP address is a valid IPv4 address.
:param ip_address: string, the IP address to check
:return: bool, True if the IP address is valid, False otherwise
>>> IpUtil.is_valid_ipv4('192.168.0.123')
True
>>> IpUtil.is_valid_ipv4('256.0.0.0')
False
"""
@staticmethod
def is_valid_ipv6(ip_address):
"""
Check if the given IP address is a valid IPv6 address.
:param ip_address:string, the IP address to check
:return:bool, True if the IP address is valid, False otherwise
>>> IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')
True
>>> IpUtil.is_valid_ipv6('2001:0db8:85a3:::8a2e:0370:7334')
False
"""
@staticmethod
def get_hostname(ip_address):
"""
Get the hostname associated with the given IP address.
:param ip_address:string, the IP address to get the hostname for
:return: string, the hostname associated with the IP address
>>> IpUtil.get_hostname('110.242.68.3')
'www.baidu.com'
>>> IpUtil.get_hostname('10.0.0.1')
""" | @staticmethod
def get_hostname(ip_address):
try:
hostname = socket.gethostbyaddr(ip_address)[0]
return hostname
except socket.herror:
return None | Get the hostname associated with the given IP address. |
ClassEval_49_sum | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def remove_job(self, job):
"""
This function is used to remove positions,and remove the position information from the job_listings list.
:param job: The position information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}]
>>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])
>>> jobMarketplace.job_listings
[]
"""
self.job_listings.remove(job)
def submit_resume(self, name, skills, experience):
"""
This function is used to submit resumes,and add the resume information to the resumes list.
:param name: The name of the resume,str.
:param skills: The skills of the resume,list.
:param experience: The experience of the resume,str.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
>>> jobMarketplace.resumes
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
resume = {"name": name, "skills": skills, "experience": experience}
self.resumes.append(resume)
def withdraw_resume(self, resume):
"""
This function is used to withdraw resumes,and remove the resume information from the resumes list.
:param resume: The resume information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
>>> jobMarketplace.resumes
[]
"""
self.resumes.remove(resume)
def search_jobs(self, criteria):
"""
This function is used to search for positions,and return the position information that meets the requirements.
:param criteria: The requirements of the position,str.
:return: The position information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.search_jobs("skill1")
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]
"""
matching_jobs = []
for job_listing in self.job_listings:
if criteria.lower() in job_listing["job_title"].lower() or criteria.lower() in [r.lower() for r in job_listing["requirements"]]:
matching_jobs.append(job_listing)
return matching_jobs
def get_job_applicants(self, job):
"""
This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.
:param job: The position information,dict.
:return: The candidate information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
applicants = []
for resume in self.resumes:
if self.matches_requirements(resume, job["requirements"]):
applicants.append(resume)
return applicants
@staticmethod
def matches_requirements(resume, requirements):
for skill in resume["skills"]:
if skill not in requirements:
return False
return True | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def remove_job(self, job):
"""
This function is used to remove positions,and remove the position information from the job_listings list.
:param job: The position information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}]
>>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])
>>> jobMarketplace.job_listings
[]
"""
def submit_resume(self, name, skills, experience):
"""
This function is used to submit resumes,and add the resume information to the resumes list.
:param name: The name of the resume,str.
:param skills: The skills of the resume,list.
:param experience: The experience of the resume,str.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
>>> jobMarketplace.resumes
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
def withdraw_resume(self, resume):
"""
This function is used to withdraw resumes,and remove the resume information from the resumes list.
:param resume: The resume information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
>>> jobMarketplace.resumes
[]
"""
def search_jobs(self, criteria):
"""
This function is used to search for positions,and return the position information that meets the requirements.
:param criteria: The requirements of the position,str.
:return: The position information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.search_jobs("skill1")
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]
"""
def get_job_applicants(self, job):
"""
This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.
:param job: The position information,dict.
:return: The candidate information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
""" | def post_job(self, job_title, company, requirements):
# requirements = ['requirement1', 'requirement2']
job = {"job_title": job_title, "company": company, "requirements": requirements}
self.job_listings.append(job) | This function is used to publish positions,and add the position information to the job_listings list. |
ClassEval_49_sum | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(self, job_title, company, requirements):
"""
This function is used to publish positions,and add the position information to the job_listings list.
:param job_title: The title of the position,str.
:param company: The company of the position,str.
:param requirements: The requirements of the position,list.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
>>> jobMarketplace.job_listings
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]
"""
# requirements = ['requirement1', 'requirement2']
job = {"job_title": job_title, "company": company, "requirements": requirements}
self.job_listings.append(job)
def submit_resume(self, name, skills, experience):
"""
This function is used to submit resumes,and add the resume information to the resumes list.
:param name: The name of the resume,str.
:param skills: The skills of the resume,list.
:param experience: The experience of the resume,str.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
>>> jobMarketplace.resumes
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
resume = {"name": name, "skills": skills, "experience": experience}
self.resumes.append(resume)
def withdraw_resume(self, resume):
"""
This function is used to withdraw resumes,and remove the resume information from the resumes list.
:param resume: The resume information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
>>> jobMarketplace.resumes
[]
"""
self.resumes.remove(resume)
def search_jobs(self, criteria):
"""
This function is used to search for positions,and return the position information that meets the requirements.
:param criteria: The requirements of the position,str.
:return: The position information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.search_jobs("skill1")
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]
"""
matching_jobs = []
for job_listing in self.job_listings:
if criteria.lower() in job_listing["job_title"].lower() or criteria.lower() in [r.lower() for r in job_listing["requirements"]]:
matching_jobs.append(job_listing)
return matching_jobs
def get_job_applicants(self, job):
"""
This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.
:param job: The position information,dict.
:return: The candidate information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
applicants = []
for resume in self.resumes:
if self.matches_requirements(resume, job["requirements"]):
applicants.append(resume)
return applicants
@staticmethod
def matches_requirements(resume, requirements):
for skill in resume["skills"]:
if skill not in requirements:
return False
return True | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(self, job_title, company, requirements):
"""
This function is used to publish positions,and add the position information to the job_listings list.
:param job_title: The title of the position,str.
:param company: The company of the position,str.
:param requirements: The requirements of the position,list.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
>>> jobMarketplace.job_listings
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]
"""
def submit_resume(self, name, skills, experience):
"""
This function is used to submit resumes,and add the resume information to the resumes list.
:param name: The name of the resume,str.
:param skills: The skills of the resume,list.
:param experience: The experience of the resume,str.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
>>> jobMarketplace.resumes
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
def withdraw_resume(self, resume):
"""
This function is used to withdraw resumes,and remove the resume information from the resumes list.
:param resume: The resume information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
>>> jobMarketplace.resumes
[]
"""
def search_jobs(self, criteria):
"""
This function is used to search for positions,and return the position information that meets the requirements.
:param criteria: The requirements of the position,str.
:return: The position information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.search_jobs("skill1")
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]
"""
def get_job_applicants(self, job):
"""
This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.
:param job: The position information,dict.
:return: The candidate information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
""" | def remove_job(self, job):
self.job_listings.remove(job) | This function is used to remove positions,and remove the position information from the job_listings list. |
ClassEval_49_sum | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(self, job_title, company, requirements):
"""
This function is used to publish positions,and add the position information to the job_listings list.
:param job_title: The title of the position,str.
:param company: The company of the position,str.
:param requirements: The requirements of the position,list.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
>>> jobMarketplace.job_listings
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]
"""
# requirements = ['requirement1', 'requirement2']
job = {"job_title": job_title, "company": company, "requirements": requirements}
self.job_listings.append(job)
def remove_job(self, job):
"""
This function is used to remove positions,and remove the position information from the job_listings list.
:param job: The position information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}]
>>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])
>>> jobMarketplace.job_listings
[]
"""
self.job_listings.remove(job)
def withdraw_resume(self, resume):
"""
This function is used to withdraw resumes,and remove the resume information from the resumes list.
:param resume: The resume information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
>>> jobMarketplace.resumes
[]
"""
self.resumes.remove(resume)
def search_jobs(self, criteria):
"""
This function is used to search for positions,and return the position information that meets the requirements.
:param criteria: The requirements of the position,str.
:return: The position information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.search_jobs("skill1")
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]
"""
matching_jobs = []
for job_listing in self.job_listings:
if criteria.lower() in job_listing["job_title"].lower() or criteria.lower() in [r.lower() for r in job_listing["requirements"]]:
matching_jobs.append(job_listing)
return matching_jobs
def get_job_applicants(self, job):
"""
This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.
:param job: The position information,dict.
:return: The candidate information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
applicants = []
for resume in self.resumes:
if self.matches_requirements(resume, job["requirements"]):
applicants.append(resume)
return applicants
@staticmethod
def matches_requirements(resume, requirements):
for skill in resume["skills"]:
if skill not in requirements:
return False
return True | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(self, job_title, company, requirements):
"""
This function is used to publish positions,and add the position information to the job_listings list.
:param job_title: The title of the position,str.
:param company: The company of the position,str.
:param requirements: The requirements of the position,list.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
>>> jobMarketplace.job_listings
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]
"""
def remove_job(self, job):
"""
This function is used to remove positions,and remove the position information from the job_listings list.
:param job: The position information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}]
>>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])
>>> jobMarketplace.job_listings
[]
"""
def withdraw_resume(self, resume):
"""
This function is used to withdraw resumes,and remove the resume information from the resumes list.
:param resume: The resume information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
>>> jobMarketplace.resumes
[]
"""
def search_jobs(self, criteria):
"""
This function is used to search for positions,and return the position information that meets the requirements.
:param criteria: The requirements of the position,str.
:return: The position information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.search_jobs("skill1")
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]
"""
def get_job_applicants(self, job):
"""
This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.
:param job: The position information,dict.
:return: The candidate information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
""" | def submit_resume(self, name, skills, experience):
resume = {"name": name, "skills": skills, "experience": experience}
self.resumes.append(resume) | This function is used to submit resumes,and add the resume information to the resumes list. |
ClassEval_49_sum | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(self, job_title, company, requirements):
"""
This function is used to publish positions,and add the position information to the job_listings list.
:param job_title: The title of the position,str.
:param company: The company of the position,str.
:param requirements: The requirements of the position,list.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
>>> jobMarketplace.job_listings
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]
"""
# requirements = ['requirement1', 'requirement2']
job = {"job_title": job_title, "company": company, "requirements": requirements}
self.job_listings.append(job)
def remove_job(self, job):
"""
This function is used to remove positions,and remove the position information from the job_listings list.
:param job: The position information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}]
>>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])
>>> jobMarketplace.job_listings
[]
"""
self.job_listings.remove(job)
def submit_resume(self, name, skills, experience):
"""
This function is used to submit resumes,and add the resume information to the resumes list.
:param name: The name of the resume,str.
:param skills: The skills of the resume,list.
:param experience: The experience of the resume,str.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
>>> jobMarketplace.resumes
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
resume = {"name": name, "skills": skills, "experience": experience}
self.resumes.append(resume)
def search_jobs(self, criteria):
"""
This function is used to search for positions,and return the position information that meets the requirements.
:param criteria: The requirements of the position,str.
:return: The position information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.search_jobs("skill1")
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]
"""
matching_jobs = []
for job_listing in self.job_listings:
if criteria.lower() in job_listing["job_title"].lower() or criteria.lower() in [r.lower() for r in job_listing["requirements"]]:
matching_jobs.append(job_listing)
return matching_jobs
def get_job_applicants(self, job):
"""
This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.
:param job: The position information,dict.
:return: The candidate information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
applicants = []
for resume in self.resumes:
if self.matches_requirements(resume, job["requirements"]):
applicants.append(resume)
return applicants
@staticmethod
def matches_requirements(resume, requirements):
for skill in resume["skills"]:
if skill not in requirements:
return False
return True | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(self, job_title, company, requirements):
"""
This function is used to publish positions,and add the position information to the job_listings list.
:param job_title: The title of the position,str.
:param company: The company of the position,str.
:param requirements: The requirements of the position,list.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
>>> jobMarketplace.job_listings
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]
"""
def remove_job(self, job):
"""
This function is used to remove positions,and remove the position information from the job_listings list.
:param job: The position information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}]
>>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])
>>> jobMarketplace.job_listings
[]
"""
def submit_resume(self, name, skills, experience):
"""
This function is used to submit resumes,and add the resume information to the resumes list.
:param name: The name of the resume,str.
:param skills: The skills of the resume,list.
:param experience: The experience of the resume,str.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
>>> jobMarketplace.resumes
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
def search_jobs(self, criteria):
"""
This function is used to search for positions,and return the position information that meets the requirements.
:param criteria: The requirements of the position,str.
:return: The position information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.search_jobs("skill1")
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]
"""
def get_job_applicants(self, job):
"""
This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.
:param job: The position information,dict.
:return: The candidate information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
""" | def withdraw_resume(self, resume):
self.resumes.remove(resume) | This function is used to withdraw resumes,and remove the resume information from the resumes list. |
ClassEval_49_sum | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(self, job_title, company, requirements):
"""
This function is used to publish positions,and add the position information to the job_listings list.
:param job_title: The title of the position,str.
:param company: The company of the position,str.
:param requirements: The requirements of the position,list.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
>>> jobMarketplace.job_listings
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]
"""
# requirements = ['requirement1', 'requirement2']
job = {"job_title": job_title, "company": company, "requirements": requirements}
self.job_listings.append(job)
def remove_job(self, job):
"""
This function is used to remove positions,and remove the position information from the job_listings list.
:param job: The position information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}]
>>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])
>>> jobMarketplace.job_listings
[]
"""
self.job_listings.remove(job)
def submit_resume(self, name, skills, experience):
"""
This function is used to submit resumes,and add the resume information to the resumes list.
:param name: The name of the resume,str.
:param skills: The skills of the resume,list.
:param experience: The experience of the resume,str.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
>>> jobMarketplace.resumes
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
resume = {"name": name, "skills": skills, "experience": experience}
self.resumes.append(resume)
def withdraw_resume(self, resume):
"""
This function is used to withdraw resumes,and remove the resume information from the resumes list.
:param resume: The resume information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
>>> jobMarketplace.resumes
[]
"""
self.resumes.remove(resume)
def get_job_applicants(self, job):
"""
This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.
:param job: The position information,dict.
:return: The candidate information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
applicants = []
for resume in self.resumes:
if self.matches_requirements(resume, job["requirements"]):
applicants.append(resume)
return applicants
@staticmethod
def matches_requirements(resume, requirements):
for skill in resume["skills"]:
if skill not in requirements:
return False
return True | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(self, job_title, company, requirements):
"""
This function is used to publish positions,and add the position information to the job_listings list.
:param job_title: The title of the position,str.
:param company: The company of the position,str.
:param requirements: The requirements of the position,list.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
>>> jobMarketplace.job_listings
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]
"""
def remove_job(self, job):
"""
This function is used to remove positions,and remove the position information from the job_listings list.
:param job: The position information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}]
>>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])
>>> jobMarketplace.job_listings
[]
"""
def submit_resume(self, name, skills, experience):
"""
This function is used to submit resumes,and add the resume information to the resumes list.
:param name: The name of the resume,str.
:param skills: The skills of the resume,list.
:param experience: The experience of the resume,str.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
>>> jobMarketplace.resumes
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
def withdraw_resume(self, resume):
"""
This function is used to withdraw resumes,and remove the resume information from the resumes list.
:param resume: The resume information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
>>> jobMarketplace.resumes
[]
"""
def get_job_applicants(self, job):
"""
This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.
:param job: The position information,dict.
:return: The candidate information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
""" | def search_jobs(self, criteria):
matching_jobs = []
for job_listing in self.job_listings:
if criteria.lower() in job_listing["job_title"].lower() or criteria.lower() in [r.lower() for r in job_listing["requirements"]]:
matching_jobs.append(job_listing)
return matching_jobs | This function is used to search for positions,and return the position information that meets the requirements. |
ClassEval_49_sum | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(self, job_title, company, requirements):
"""
This function is used to publish positions,and add the position information to the job_listings list.
:param job_title: The title of the position,str.
:param company: The company of the position,str.
:param requirements: The requirements of the position,list.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
>>> jobMarketplace.job_listings
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]
"""
# requirements = ['requirement1', 'requirement2']
job = {"job_title": job_title, "company": company, "requirements": requirements}
self.job_listings.append(job)
def remove_job(self, job):
"""
This function is used to remove positions,and remove the position information from the job_listings list.
:param job: The position information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}]
>>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])
>>> jobMarketplace.job_listings
[]
"""
self.job_listings.remove(job)
def submit_resume(self, name, skills, experience):
"""
This function is used to submit resumes,and add the resume information to the resumes list.
:param name: The name of the resume,str.
:param skills: The skills of the resume,list.
:param experience: The experience of the resume,str.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
>>> jobMarketplace.resumes
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
resume = {"name": name, "skills": skills, "experience": experience}
self.resumes.append(resume)
def withdraw_resume(self, resume):
"""
This function is used to withdraw resumes,and remove the resume information from the resumes list.
:param resume: The resume information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
>>> jobMarketplace.resumes
[]
"""
self.resumes.remove(resume)
def search_jobs(self, criteria):
"""
This function is used to search for positions,and return the position information that meets the requirements.
:param criteria: The requirements of the position,str.
:return: The position information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.search_jobs("skill1")
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]
"""
matching_jobs = []
for job_listing in self.job_listings:
if criteria.lower() in job_listing["job_title"].lower() or criteria.lower() in [r.lower() for r in job_listing["requirements"]]:
matching_jobs.append(job_listing)
return matching_jobs
@staticmethod
def matches_requirements(resume, requirements):
for skill in resume["skills"]:
if skill not in requirements:
return False
return True | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(self, job_title, company, requirements):
"""
This function is used to publish positions,and add the position information to the job_listings list.
:param job_title: The title of the position,str.
:param company: The company of the position,str.
:param requirements: The requirements of the position,list.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.post_job("Software Engineer", "ABC Company", ['requirement1', 'requirement2'])
>>> jobMarketplace.job_listings
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]
"""
def remove_job(self, job):
"""
This function is used to remove positions,and remove the position information from the job_listings list.
:param job: The position information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['requirement1', 'requirement2']}]
>>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])
>>> jobMarketplace.job_listings
[]
"""
def submit_resume(self, name, skills, experience):
"""
This function is used to submit resumes,and add the resume information to the resumes list.
:param name: The name of the resume,str.
:param skills: The skills of the resume,list.
:param experience: The experience of the resume,str.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.submit_resume("Tom", ['skill1', 'skill2'], "experience")
>>> jobMarketplace.resumes
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
"""
def withdraw_resume(self, resume):
"""
This function is used to withdraw resumes,and remove the resume information from the resumes list.
:param resume: The resume information to be removed,dict.
:return: None
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])
>>> jobMarketplace.resumes
[]
"""
def search_jobs(self, criteria):
"""
This function is used to search for positions,and return the position information that meets the requirements.
:param criteria: The requirements of the position,str.
:return: The position information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.search_jobs("skill1")
[{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]
"""
def get_job_applicants(self, job):
"""
This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.
:param job: The position information,dict.
:return: The candidate information that meets the requirements,list.
>>> jobMarketplace = JobMarketplace()
>>> jobMarketplace.resumes = [{"name": "Tom", "skills": ['skill1', 'skill2'], "experience": "experience"}]
>>> jobMarketplace.job_listings = [{"job_title": "Software Engineer", "company": "ABC Company", "requirements": ['skill1', 'skill2']}]
>>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])
[{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]
""" | def get_job_applicants(self, job):
applicants = []
for resume in self.resumes:
if self.matches_requirements(resume, job["requirements"]):
applicants.append(resume)
return applicants | This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function. |
ClassEval_50_sum | import json
import os
class JSONProcessor:
"""
This is a class to process JSON file, including reading and writing JSON files, as well as processing JSON data by removing a specified key from the JSON object.
"""
def write_json(self, data, file_path):
"""
Write data to a JSON file and save it to the given path.
:param data: dict, the data to be written to the JSON file.
:param file_path: str, the path of the JSON file.
:return: 1 if the writing process is successful, or -1, if an error occurs during the writing process.
>>> json.write_json({'key1': 'value1', 'key2': 'value2'}, 'test.json')
1
>>> json.read_json('test.json')
{'key1': 'value1', 'key2': 'value2'}
"""
try:
with open(file_path, 'w') as file:
json.dump(data, file)
return 1
except:
return -1
def process_json(self, file_path, remove_key):
"""
read a JSON file and process the data by removing a specified key and rewrite the modified data back to the file.
:param file_path: str, the path of the JSON file.
:param remove_key: str, the key to be removed.
:return: 1, if the specified key is successfully removed and the data is written back.
0, if the file does not exist or the specified key does not exist in the data.
>>> json.read_json('test.json')
{'key1': 'value1', 'key2': 'value2'}
>>> json.process_json('test.json', 'key1')
1
>>> json.read_json('test.json')
{'key2': 'value2'}
"""
data = self.read_json(file_path)
if data == 0 or data == -1:
return 0
if remove_key in data:
del data[remove_key]
self.write_json(data, file_path)
return 1
else:
return 0 | import json
import os
class JSONProcessor:
"""
This is a class to process JSON file, including reading and writing JSON files, as well as processing JSON data by removing a specified key from the JSON object.
"""
def write_json(self, data, file_path):
"""
Write data to a JSON file and save it to the given path.
:param data: dict, the data to be written to the JSON file.
:param file_path: str, the path of the JSON file.
:return: 1 if the writing process is successful, or -1, if an error occurs during the writing process.
>>> json.write_json({'key1': 'value1', 'key2': 'value2'}, 'test.json')
1
>>> json.read_json('test.json')
{'key1': 'value1', 'key2': 'value2'}
"""
def process_json(self, file_path, remove_key):
"""
read a JSON file and process the data by removing a specified key and rewrite the modified data back to the file.
:param file_path: str, the path of the JSON file.
:param remove_key: str, the key to be removed.
:return: 1, if the specified key is successfully removed and the data is written back.
0, if the file does not exist or the specified key does not exist in the data.
>>> json.read_json('test.json')
{'key1': 'value1', 'key2': 'value2'}
>>> json.process_json('test.json', 'key1')
1
>>> json.read_json('test.json')
{'key2': 'value2'}
""" | def read_json(self, file_path):
if not os.path.exists(file_path):
return 0
try:
with open(file_path, 'r') as file:
data = json.load(file)
return data
except:
return -1 | Read a JSON file and return the data. |