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_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 read_json(self, file_path): """ Read a JSON file and return the data. :param file_path: str, the path of the JSON file. :return: dict, the data from the JSON file if read successfully, or return -1 if an error occurs during the reading process. return 0 if the file does not exist. >>> json.read_json('test.json') {'name': 'test', 'age': 14} """ if not os.path.exists(file_path): return 0 try: with open(file_path, 'r') as file: data = json.load(file) return data except: return -1 def 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 read_json(self, file_path): """ Read a JSON file and return the data. :param file_path: str, the path of the JSON file. :return: dict, the data from the JSON file if read successfully, or return -1 if an error occurs during the reading process. return 0 if the file does not exist. >>> json.read_json('test.json') {'name': 'test', 'age': 14} """ def 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 write_json(self, data, file_path): try: with open(file_path, 'w') as file: json.dump(data, file) return 1 except: return -1
Write data to a JSON file and save it to the given path.
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 read_json(self, file_path): """ Read a JSON file and return the data. :param file_path: str, the path of the JSON file. :return: dict, the data from the JSON file if read successfully, or return -1 if an error occurs during the reading process. return 0 if the file does not exist. >>> json.read_json('test.json') {'name': 'test', 'age': 14} """ if not os.path.exists(file_path): return 0 try: with open(file_path, 'r') as file: data = json.load(file) return data except: return -1 def write_json(self, data, file_path): """ 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): 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 read_json(self, file_path): """ Read a JSON file and return the data. :param file_path: str, the path of the JSON file. :return: dict, the data from the JSON file if read successfully, or return -1 if an error occurs during the reading process. return 0 if the file does not exist. >>> json.read_json('test.json') {'name': 'test', 'age': 14} """ def write_json(self, data, file_path): """ Write data to a JSON file and save it to the given path. :param data: dict, the data to be written to the JSON file. :param file_path: str, the path of the JSON file. :return: 1 if the writing process is successful, or -1, if an error occurs during the writing process. >>> json.write_json({'key1': 'value1', 'key2': 'value2'}, 'test.json') 1 >>> json.read_json('test.json') {'key1': 'value1', 'key2': 'value2'} """ def process_json(self, file_path, remove_key): """ read a JSON file and process the data by removing a specified key and rewrite the modified data back to the file. :param file_path: str, the path of the JSON file. :param remove_key: str, the key to be removed. :return: 1, if the specified key is successfully removed and the data is written back. 0, if the file does not exist or the specified key does not exist in the data. >>> json.read_json('test.json') {'key1': 'value1', 'key2': 'value2'} >>> json.process_json('test.json', 'key1') 1 >>> json.read_json('test.json') {'key2': 'value2'} """
def process_json(self, file_path, remove_key): data = self.read_json(file_path) if data == 0 or data == -1: return 0 if remove_key in data: del data[remove_key] self.write_json(data, file_path) return 1 else: return 0
read a JSON file and process the data by removing a specified key and rewrite the modified data back to the file.
ClassEval_51_sum
import numpy as np class KappaCalculator: """ This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient. """ @staticmethod @staticmethod def fleiss_kappa(testData, N, k, n): """ Calculate the fliss kappa value of an N * k matrix :param testData: Input data matrix, N * k :param N: int, Number of samples :param k: int, Number of categories :param n: int, Number of raters :return: float, fleiss kappa value >>> KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14], >>> [0, 2, 6, 4, 2], >>> [0, 0, 3, 5, 6], >>> [0, 3, 9, 2, 0], >>> [2, 2, 8, 1, 1], >>> [7, 7, 0, 0, 0], >>> [3, 2, 6, 3, 0], >>> [2, 5, 3, 2, 2], >>> [6, 5, 2, 1, 0], >>> [0, 2, 2, 3, 7]], 10, 5, 14) 0.20993070442195522 """ dataMat = np.mat(testData, float) oneMat = np.ones((k, 1)) sum = 0.0 P0 = 0.0 for i in range(N): temp = 0.0 for j in range(k): sum += dataMat[i, j] temp += 1.0 * dataMat[i, j] ** 2 temp -= n temp /= (n - 1) * n P0 += temp P0 = 1.0 * P0 / N ysum = np.sum(dataMat, axis=0) for i in range(k): ysum[0, i] = (ysum[0, i] / sum) ** 2 Pe = ysum * oneMat * 1.0 ans = (P0 - Pe) / (1 - Pe) return ans[0, 0]
import numpy as np class KappaCalculator: """ This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient. """ @staticmethod @staticmethod def fleiss_kappa(testData, N, k, n): """ Calculate the fliss kappa value of an N * k matrix :param testData: Input data matrix, N * k :param N: int, Number of samples :param k: int, Number of categories :param n: int, Number of raters :return: float, fleiss kappa value >>> KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14], >>> [0, 2, 6, 4, 2], >>> [0, 0, 3, 5, 6], >>> [0, 3, 9, 2, 0], >>> [2, 2, 8, 1, 1], >>> [7, 7, 0, 0, 0], >>> [3, 2, 6, 3, 0], >>> [2, 5, 3, 2, 2], >>> [6, 5, 2, 1, 0], >>> [0, 2, 2, 3, 7]], 10, 5, 14) 0.20993070442195522 """
def kappa(testData, k): dataMat = np.mat(testData) P0 = 0.0 for i in range(k): P0 += dataMat[i, i] * 1.0 xsum = np.sum(dataMat, axis=1) ysum = np.sum(dataMat, axis=0) sum = np.sum(dataMat) Pe = float(ysum * xsum) / sum / sum P0 = float(P0 / sum * 1.0) cohens_coefficient = float((P0 - Pe) / (1 - Pe)) return cohens_coefficient
Calculate the cohens kappa value of a k-dimensional matrix
ClassEval_51_sum
import numpy as np class KappaCalculator: """ This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient. """ @staticmethod def kappa(testData, k): """ Calculate the cohens kappa value of a k-dimensional matrix :param testData: The k-dimensional matrix that needs to calculate the cohens kappa value :param k: int, Matrix dimension :return:float, the cohens kappa value of the matrix >>> KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3) 0.25 """ dataMat = np.mat(testData) P0 = 0.0 for i in range(k): P0 += dataMat[i, i] * 1.0 xsum = np.sum(dataMat, axis=1) ysum = np.sum(dataMat, axis=0) sum = np.sum(dataMat) Pe = float(ysum * xsum) / sum / sum P0 = float(P0 / sum * 1.0) cohens_coefficient = float((P0 - Pe) / (1 - Pe)) return cohens_coefficient @staticmethod def fleiss_kappa(testData, N, k, n): dataMat = np.mat(testData, float) oneMat = np.ones((k, 1)) sum = 0.0 P0 = 0.0 for i in range(N): temp = 0.0 for j in range(k): sum += dataMat[i, j] temp += 1.0 * dataMat[i, j] ** 2 temp -= n temp /= (n - 1) * n P0 += temp P0 = 1.0 * P0 / N ysum = np.sum(dataMat, axis=0) for i in range(k): ysum[0, i] = (ysum[0, i] / sum) ** 2 Pe = ysum * oneMat * 1.0 ans = (P0 - Pe) / (1 - Pe) return ans[0, 0]
import numpy as np class KappaCalculator: """ This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient. """ @staticmethod def kappa(testData, k): """ Calculate the cohens kappa value of a k-dimensional matrix :param testData: The k-dimensional matrix that needs to calculate the cohens kappa value :param k: int, Matrix dimension :return:float, the cohens kappa value of the matrix >>> KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3) 0.25 """ @staticmethod def fleiss_kappa(testData, N, k, n): """ Calculate the fliss kappa value of an N * k matrix :param testData: Input data matrix, N * k :param N: int, Number of samples :param k: int, Number of categories :param n: int, Number of raters :return: float, fleiss kappa value >>> KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14], >>> [0, 2, 6, 4, 2], >>> [0, 0, 3, 5, 6], >>> [0, 3, 9, 2, 0], >>> [2, 2, 8, 1, 1], >>> [7, 7, 0, 0, 0], >>> [3, 2, 6, 3, 0], >>> [2, 5, 3, 2, 2], >>> [6, 5, 2, 1, 0], >>> [0, 2, 2, 3, 7]], 10, 5, 14) 0.20993070442195522 """
@staticmethod def fleiss_kappa(testData, N, k, n): dataMat = np.mat(testData, float) oneMat = np.ones((k, 1)) sum = 0.0 P0 = 0.0 for i in range(N): temp = 0.0 for j in range(k): sum += dataMat[i, j] temp += 1.0 * dataMat[i, j] ** 2 temp -= n temp /= (n - 1) * n P0 += temp P0 = 1.0 * P0 / N ysum = np.sum(dataMat, axis=0) for i in range(k): ysum[0, i] = (ysum[0, i] / sum) ** 2 Pe = ysum * oneMat * 1.0 ans = (P0 - Pe) / (1 - Pe) return ans[0, 0]
Calculate the fliss kappa value of an N * k matrix
ClassEval_52_sum
import nltk from nltk.stem import WordNetLemmatizer from nltk import pos_tag, word_tokenize import string nltk.download('averaged_perceptron_tagger') nltk.download('punkt') nltk.download('wordnet') class Lemmatization: """ This is a class about Lemmatization, which utilizes the nltk library to perform lemmatization and part-of-speech tagging on sentences, as well as remove punctuation. """ def __init__(self): self.lemmatizer = WordNetLemmatizer() def get_pos_tag(self, sentence): """ Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word. :param sentence: a sentence str :return: list, part of speech tag of each word in the sentence. >>> lemmatization = Lemmatization() >>> lemmatization.get_pos_tag("I am running in a race.") ['PRP', 'VBP', 'VBG', 'IN', 'DT', 'NN'] """ pos_tags = [] sentence = self.remove_punctuation(sentence) words = word_tokenize(sentence) tagged_words = pos_tag(words) for tagged_word in tagged_words: pos_tags.append(tagged_word[1]) return pos_tags def remove_punctuation(self, sentence): """ Removes punctuation from the input text. :param sentence: a sentence str :return: str, sentence without any punctuation >>> lemmatization = Lemmatization() >>> lemmatization.remove_punctuation("I am running in a race.") 'I am running in a race' """ return sentence.translate(str.maketrans('', '', string.punctuation))
import nltk from nltk.stem import WordNetLemmatizer from nltk import pos_tag, word_tokenize import string nltk.download('averaged_perceptron_tagger') nltk.download('punkt') nltk.download('wordnet') class Lemmatization: """ This is a class about Lemmatization, which utilizes the nltk library to perform lemmatization and part-of-speech tagging on sentences, as well as remove punctuation. """ def __init__(self): """ creates a WordNetLemmatizer object and stores it in the self.lemmatizer member variable. """ self.lemmatizer = WordNetLemmatizer() def get_pos_tag(self, sentence): """ Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word. :param sentence: a sentence str :return: list, part of speech tag of each word in the sentence. >>> lemmatization = Lemmatization() >>> lemmatization.get_pos_tag("I am running in a race.") ['PRP', 'VBP', 'VBG', 'IN', 'DT', 'NN'] """ def remove_punctuation(self, sentence): """ Removes punctuation from the input text. :param sentence: a sentence str :return: str, sentence without any punctuation >>> lemmatization = Lemmatization() >>> lemmatization.remove_punctuation("I am running in a race.") 'I am running in a race' """
def lemmatize_sentence(self, sentence): lemmatized_words = [] sentence = self.remove_punctuation(sentence) words = word_tokenize(sentence) tagged_words = pos_tag(words) for word, tag in tagged_words: if tag.startswith('V'): lemmatized_word = self.lemmatizer.lemmatize(word, pos='v') elif tag.startswith('J'): lemmatized_word = self.lemmatizer.lemmatize(word, pos='a') elif tag.startswith('R'): lemmatized_word = self.lemmatizer.lemmatize(word, pos='r') else: lemmatized_word = self.lemmatizer.lemmatize(word) lemmatized_words.append(lemmatized_word) return lemmatized_words
Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word, lemmatizes the words with different parameters based on their parts of speech, and stores in a list.
ClassEval_52_sum
import nltk from nltk.stem import WordNetLemmatizer from nltk import pos_tag, word_tokenize import string nltk.download('averaged_perceptron_tagger') nltk.download('punkt') nltk.download('wordnet') class Lemmatization: """ This is a class about Lemmatization, which utilizes the nltk library to perform lemmatization and part-of-speech tagging on sentences, as well as remove punctuation. """ def __init__(self): self.lemmatizer = WordNetLemmatizer() def lemmatize_sentence(self, sentence): """ Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word, lemmatizes the words with different parameters based on their parts of speech, and stores in a list. :param sentence: a sentence str :return: a list of words which have been lemmatized. >>> lemmatization = Lemmatization() >>> lemmatization.lemmatize_sentence("I am running in a race.") ['I', 'be', 'run', 'in', 'a', 'race'] """ lemmatized_words = [] sentence = self.remove_punctuation(sentence) words = word_tokenize(sentence) tagged_words = pos_tag(words) for word, tag in tagged_words: if tag.startswith('V'): lemmatized_word = self.lemmatizer.lemmatize(word, pos='v') elif tag.startswith('J'): lemmatized_word = self.lemmatizer.lemmatize(word, pos='a') elif tag.startswith('R'): lemmatized_word = self.lemmatizer.lemmatize(word, pos='r') else: lemmatized_word = self.lemmatizer.lemmatize(word) lemmatized_words.append(lemmatized_word) return lemmatized_words def remove_punctuation(self, sentence): """ Removes punctuation from the input text. :param sentence: a sentence str :return: str, sentence without any punctuation >>> lemmatization = Lemmatization() >>> lemmatization.remove_punctuation("I am running in a race.") 'I am running in a race' """ return sentence.translate(str.maketrans('', '', string.punctuation))
import nltk from nltk.stem import WordNetLemmatizer from nltk import pos_tag, word_tokenize import string nltk.download('averaged_perceptron_tagger') nltk.download('punkt') nltk.download('wordnet') class Lemmatization: """ This is a class about Lemmatization, which utilizes the nltk library to perform lemmatization and part-of-speech tagging on sentences, as well as remove punctuation. """ def __init__(self): """ creates a WordNetLemmatizer object and stores it in the self.lemmatizer member variable. """ self.lemmatizer = WordNetLemmatizer() def lemmatize_sentence(self, sentence): """ Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word, lemmatizes the words with different parameters based on their parts of speech, and stores in a list. :param sentence: a sentence str :return: a list of words which have been lemmatized. >>> lemmatization = Lemmatization() >>> lemmatization.lemmatize_sentence("I am running in a race.") ['I', 'be', 'run', 'in', 'a', 'race'] """ def remove_punctuation(self, sentence): """ Removes punctuation from the input text. :param sentence: a sentence str :return: str, sentence without any punctuation >>> lemmatization = Lemmatization() >>> lemmatization.remove_punctuation("I am running in a race.") 'I am running in a race' """
def get_pos_tag(self, sentence): pos_tags = [] sentence = self.remove_punctuation(sentence) words = word_tokenize(sentence) tagged_words = pos_tag(words) for tagged_word in tagged_words: pos_tags.append(tagged_word[1]) return pos_tags
Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word.
ClassEval_52_sum
import nltk from nltk.stem import WordNetLemmatizer from nltk import pos_tag, word_tokenize import string nltk.download('averaged_perceptron_tagger') nltk.download('punkt') nltk.download('wordnet') class Lemmatization: """ This is a class about Lemmatization, which utilizes the nltk library to perform lemmatization and part-of-speech tagging on sentences, as well as remove punctuation. """ def __init__(self): self.lemmatizer = WordNetLemmatizer() def lemmatize_sentence(self, sentence): """ Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word, lemmatizes the words with different parameters based on their parts of speech, and stores in a list. :param sentence: a sentence str :return: a list of words which have been lemmatized. >>> lemmatization = Lemmatization() >>> lemmatization.lemmatize_sentence("I am running in a race.") ['I', 'be', 'run', 'in', 'a', 'race'] """ lemmatized_words = [] sentence = self.remove_punctuation(sentence) words = word_tokenize(sentence) tagged_words = pos_tag(words) for word, tag in tagged_words: if tag.startswith('V'): lemmatized_word = self.lemmatizer.lemmatize(word, pos='v') elif tag.startswith('J'): lemmatized_word = self.lemmatizer.lemmatize(word, pos='a') elif tag.startswith('R'): lemmatized_word = self.lemmatizer.lemmatize(word, pos='r') else: lemmatized_word = self.lemmatizer.lemmatize(word) lemmatized_words.append(lemmatized_word) return lemmatized_words def get_pos_tag(self, sentence): """ Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word. :param sentence: a sentence str :return: list, part of speech tag of each word in the sentence. >>> lemmatization = Lemmatization() >>> lemmatization.get_pos_tag("I am running in a race.") ['PRP', 'VBP', 'VBG', 'IN', 'DT', 'NN'] """ pos_tags = [] sentence = self.remove_punctuation(sentence) words = word_tokenize(sentence) tagged_words = pos_tag(words) for tagged_word in tagged_words: pos_tags.append(tagged_word[1]) return pos_tags def remove_punctuation(self, sentence): return sentence.translate(str.maketrans('', '', string.punctuation))
import nltk from nltk.stem import WordNetLemmatizer from nltk import pos_tag, word_tokenize import string nltk.download('averaged_perceptron_tagger') nltk.download('punkt') nltk.download('wordnet') class Lemmatization: """ This is a class about Lemmatization, which utilizes the nltk library to perform lemmatization and part-of-speech tagging on sentences, as well as remove punctuation. """ def __init__(self): """ creates a WordNetLemmatizer object and stores it in the self.lemmatizer member variable. """ self.lemmatizer = WordNetLemmatizer() def lemmatize_sentence(self, sentence): """ Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word, lemmatizes the words with different parameters based on their parts of speech, and stores in a list. :param sentence: a sentence str :return: a list of words which have been lemmatized. >>> lemmatization = Lemmatization() >>> lemmatization.lemmatize_sentence("I am running in a race.") ['I', 'be', 'run', 'in', 'a', 'race'] """ def get_pos_tag(self, sentence): """ Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word. :param sentence: a sentence str :return: list, part of speech tag of each word in the sentence. >>> lemmatization = Lemmatization() >>> lemmatization.get_pos_tag("I am running in a race.") ['PRP', 'VBP', 'VBG', 'IN', 'DT', 'NN'] """ def remove_punctuation(self, sentence): """ Removes punctuation from the input text. :param sentence: a sentence str :return: str, sentence without any punctuation >>> lemmatization = Lemmatization() >>> lemmatization.remove_punctuation("I am running in a race.") 'I am running in a race' """
def remove_punctuation(self, sentence): return sentence.translate(str.maketrans('', '', string.punctuation))
Removes punctuation from the input text.
ClassEval_53_sum
import re import string class LongestWord: """ This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list. """ def __init__(self): self.word_list = [] def find_longest_word(self, sentence): """ Remove punctuation marks and split a sentence into a list of word. Find the longest splited word that is in the self.word_list. Words are strictly case sensitive. :param sentence: a sentence str :return str: longest splited word that is in the self.word_list. return '' if self.word_list is empty. >>> longestWord = LongestWord() >>> longestWord.add_word('A') >>> longestWord.add_word('aM') >>> longestWord.find_longest_word('I am a student.') 'a' """ longest_word = "" sentence = sentence.lower() sentence = re.sub('[%s]' % re.escape(string.punctuation), '', sentence) sentence = re.split(' ', sentence) for word in sentence: if word in self.word_list and len(word) > len(longest_word): longest_word = word return longest_word
import re import string class LongestWord: """ This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list. """ def __init__(self): """ Initialize a list of word. """ self.word_list = [] def find_longest_word(self, sentence): """ Remove punctuation marks and split a sentence into a list of word. Find the longest splited word that is in the self.word_list. Words are strictly case sensitive. :param sentence: a sentence str :return str: longest splited word that is in the self.word_list. return '' if self.word_list is empty. >>> longestWord = LongestWord() >>> longestWord.add_word('A') >>> longestWord.add_word('aM') >>> longestWord.find_longest_word('I am a student.') 'a' """
def add_word(self, word): self.word_list.append(word)
append the input word into self.word_list
ClassEval_53_sum
import re import string class LongestWord: """ This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list. """ def __init__(self): self.word_list = [] def add_word(self, word): """ append the input word into self.word_list :param word: str, input word """ self.word_list.append(word) def find_longest_word(self, sentence): longest_word = "" sentence = sentence.lower() sentence = re.sub('[%s]' % re.escape(string.punctuation), '', sentence) sentence = re.split(' ', sentence) for word in sentence: if word in self.word_list and len(word) > len(longest_word): longest_word = word return longest_word
import re import string class LongestWord: """ This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list. """ def __init__(self): """ Initialize a list of word. """ self.word_list = [] def add_word(self, word): """ append the input word into self.word_list :param word: str, input word """ def find_longest_word(self, sentence): """ Remove punctuation marks and split a sentence into a list of word. Find the longest splited word that is in the self.word_list. Words are strictly case sensitive. :param sentence: a sentence str :return str: longest splited word that is in the self.word_list. return '' if self.word_list is empty. >>> longestWord = LongestWord() >>> longestWord.add_word('A') >>> longestWord.add_word('aM') >>> longestWord.find_longest_word('I am a student.') 'a' """
def find_longest_word(self, sentence): longest_word = "" sentence = sentence.lower() sentence = re.sub('[%s]' % re.escape(string.punctuation), '', sentence) sentence = re.split(' ', sentence) for word in sentence: if word in self.word_list and len(word) > len(longest_word): longest_word = word return longest_word
Remove punctuation marks and split a sentence into a list of word. Find the longest splited word that is in the self.word_list. Words are strictly case sensitive.
ClassEval_54_sum
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): self.BOARD_SIZE = BOARD_SIZE self.ICONS = ICONS self.board = self.create_board() def is_valid_move(self, pos1, pos2): """ check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions) :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return:True or False ,representing whether the move of two icons is valid >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ x1, y1 = pos1 x2, y2 = pos2 # Check if positions are within the game board range if not (0 <= x1 < self.BOARD_SIZE[0] and 0 <= y1 < self.BOARD_SIZE[1] and 0 <= x2 < self.BOARD_SIZE[ 0] and 0 <= y2 < self.BOARD_SIZE[1]): return False # Check if the two positions are the same if pos1 == pos2: return False # Check if the two positions have the same icon if self.board[x1][y1] != self.board[x2][y2]: return False # Check if there is a valid path between the two positions if not self.has_path(pos1, pos2): return False return True def has_path(self, pos1, pos2): """ check if there is a path between two icons :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return: True or False ,representing whether there is a path between two icons >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ visited = set() stack = [pos1] while stack: current_pos = stack.pop() if current_pos == pos2: return True if current_pos in visited: continue visited.add(current_pos) x, y = current_pos # Check adjacent positions (up, down, left, right) for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]: new_x, new_y = x + dx, y + dy if 0 <= new_x < self.BOARD_SIZE[0] and 0 <= new_y < self.BOARD_SIZE[1]: if (new_x, new_y) not in visited and self.board[new_x][new_y] == self.board[x][y]: stack.append((new_x, new_y)) return False def remove_icons(self, pos1, pos2): """ remove the connected icons on the game board :param pos1: position tuple(x, y) of the first icon to be removed :param pos2: position tuple(x, y) of the second icon to be removed :return: None >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.remove_icons((0, 0), (1, 0)) mc.board = [[' ', 'b', 'c', 'a'], [' ', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ x1, y1 = pos1 x2, y2 = pos2 self.board[x1][y1] = ' ' self.board[x2][y2] = ' ' def is_game_over(self): """ Check if the game is over (i.e., if there are no more icons on the game board) :return: True or False ,representing whether the game is over >>> mc = MahjongConnect([4, 4] ['a', 'b', 'c']) >>> mc.board = [[' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' ']] >>> mc.is_game_over() True """ for row in self.board: if any(icon != ' ' for icon in row): return False return True
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): """ initialize the board size and the icon list, create the game board :param BOARD_SIZE: list of two integer numbers, representing the number of rows and columns of the game board :param ICONS: list of string, representing the icons >>>mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.BOARD_SIZE = [4, 4] mc.ICONS = ['a', 'b', 'c'] mc.board = mc.create_board() """ self.BOARD_SIZE = BOARD_SIZE self.ICONS = ICONS self.board = self.create_board() def is_valid_move(self, pos1, pos2): """ check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions) :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return:True or False ,representing whether the move of two icons is valid >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ def has_path(self, pos1, pos2): """ check if there is a path between two icons :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return: True or False ,representing whether there is a path between two icons >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ def remove_icons(self, pos1, pos2): """ remove the connected icons on the game board :param pos1: position tuple(x, y) of the first icon to be removed :param pos2: position tuple(x, y) of the second icon to be removed :return: None >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.remove_icons((0, 0), (1, 0)) mc.board = [[' ', 'b', 'c', 'a'], [' ', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ def is_game_over(self): """ Check if the game is over (i.e., if there are no more icons on the game board) :return: True or False ,representing whether the game is over >>> mc = MahjongConnect([4, 4] ['a', 'b', 'c']) >>> mc.board = [[' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' ']] >>> mc.is_game_over() True """
def create_board(self): board = [[random.choice(self.ICONS) for _ in range(self.BOARD_SIZE[1])] for _ in range(self.BOARD_SIZE[0])] return board
create the game board with the given board size and icons
ClassEval_54_sum
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): self.BOARD_SIZE = BOARD_SIZE self.ICONS = ICONS self.board = self.create_board() def create_board(self): """ create the game board with the given board size and icons :return: 2-dimensional list, the game board >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) >>> mc.create_board() mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ board = [[random.choice(self.ICONS) for _ in range(self.BOARD_SIZE[1])] for _ in range(self.BOARD_SIZE[0])] return board def has_path(self, pos1, pos2): """ check if there is a path between two icons :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return: True or False ,representing whether there is a path between two icons >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ visited = set() stack = [pos1] while stack: current_pos = stack.pop() if current_pos == pos2: return True if current_pos in visited: continue visited.add(current_pos) x, y = current_pos # Check adjacent positions (up, down, left, right) for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]: new_x, new_y = x + dx, y + dy if 0 <= new_x < self.BOARD_SIZE[0] and 0 <= new_y < self.BOARD_SIZE[1]: if (new_x, new_y) not in visited and self.board[new_x][new_y] == self.board[x][y]: stack.append((new_x, new_y)) return False def remove_icons(self, pos1, pos2): """ remove the connected icons on the game board :param pos1: position tuple(x, y) of the first icon to be removed :param pos2: position tuple(x, y) of the second icon to be removed :return: None >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.remove_icons((0, 0), (1, 0)) mc.board = [[' ', 'b', 'c', 'a'], [' ', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ x1, y1 = pos1 x2, y2 = pos2 self.board[x1][y1] = ' ' self.board[x2][y2] = ' ' def is_game_over(self): """ Check if the game is over (i.e., if there are no more icons on the game board) :return: True or False ,representing whether the game is over >>> mc = MahjongConnect([4, 4] ['a', 'b', 'c']) >>> mc.board = [[' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' ']] >>> mc.is_game_over() True """ for row in self.board: if any(icon != ' ' for icon in row): return False return True
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): """ initialize the board size and the icon list, create the game board :param BOARD_SIZE: list of two integer numbers, representing the number of rows and columns of the game board :param ICONS: list of string, representing the icons >>>mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.BOARD_SIZE = [4, 4] mc.ICONS = ['a', 'b', 'c'] mc.board = mc.create_board() """ self.BOARD_SIZE = BOARD_SIZE self.ICONS = ICONS self.board = self.create_board() def create_board(self): """ create the game board with the given board size and icons :return: 2-dimensional list, the game board >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) >>> mc.create_board() mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ def has_path(self, pos1, pos2): """ check if there is a path between two icons :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return: True or False ,representing whether there is a path between two icons >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ def remove_icons(self, pos1, pos2): """ remove the connected icons on the game board :param pos1: position tuple(x, y) of the first icon to be removed :param pos2: position tuple(x, y) of the second icon to be removed :return: None >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.remove_icons((0, 0), (1, 0)) mc.board = [[' ', 'b', 'c', 'a'], [' ', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ def is_game_over(self): """ Check if the game is over (i.e., if there are no more icons on the game board) :return: True or False ,representing whether the game is over >>> mc = MahjongConnect([4, 4] ['a', 'b', 'c']) >>> mc.board = [[' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' ']] >>> mc.is_game_over() True """
def is_valid_move(self, pos1, pos2): x1, y1 = pos1 x2, y2 = pos2 # Check if positions are within the game board range if not (0 <= x1 < self.BOARD_SIZE[0] and 0 <= y1 < self.BOARD_SIZE[1] and 0 <= x2 < self.BOARD_SIZE[ 0] and 0 <= y2 < self.BOARD_SIZE[1]): return False # Check if the two positions are the same if pos1 == pos2: return False # Check if the two positions have the same icon if self.board[x1][y1] != self.board[x2][y2]: return False # Check if there is a valid path between the two positions if not self.has_path(pos1, pos2): return False return True
check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions)
ClassEval_54_sum
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): self.BOARD_SIZE = BOARD_SIZE self.ICONS = ICONS self.board = self.create_board() def create_board(self): """ create the game board with the given board size and icons :return: 2-dimensional list, the game board >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) >>> mc.create_board() mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ board = [[random.choice(self.ICONS) for _ in range(self.BOARD_SIZE[1])] for _ in range(self.BOARD_SIZE[0])] return board def is_valid_move(self, pos1, pos2): """ check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions) :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return:True or False ,representing whether the move of two icons is valid >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ x1, y1 = pos1 x2, y2 = pos2 # Check if positions are within the game board range if not (0 <= x1 < self.BOARD_SIZE[0] and 0 <= y1 < self.BOARD_SIZE[1] and 0 <= x2 < self.BOARD_SIZE[ 0] and 0 <= y2 < self.BOARD_SIZE[1]): return False # Check if the two positions are the same if pos1 == pos2: return False # Check if the two positions have the same icon if self.board[x1][y1] != self.board[x2][y2]: return False # Check if there is a valid path between the two positions if not self.has_path(pos1, pos2): return False return True def remove_icons(self, pos1, pos2): """ remove the connected icons on the game board :param pos1: position tuple(x, y) of the first icon to be removed :param pos2: position tuple(x, y) of the second icon to be removed :return: None >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.remove_icons((0, 0), (1, 0)) mc.board = [[' ', 'b', 'c', 'a'], [' ', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ x1, y1 = pos1 x2, y2 = pos2 self.board[x1][y1] = ' ' self.board[x2][y2] = ' ' def is_game_over(self): """ Check if the game is over (i.e., if there are no more icons on the game board) :return: True or False ,representing whether the game is over >>> mc = MahjongConnect([4, 4] ['a', 'b', 'c']) >>> mc.board = [[' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' ']] >>> mc.is_game_over() True """ for row in self.board: if any(icon != ' ' for icon in row): return False return True
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): """ initialize the board size and the icon list, create the game board :param BOARD_SIZE: list of two integer numbers, representing the number of rows and columns of the game board :param ICONS: list of string, representing the icons >>>mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.BOARD_SIZE = [4, 4] mc.ICONS = ['a', 'b', 'c'] mc.board = mc.create_board() """ self.BOARD_SIZE = BOARD_SIZE self.ICONS = ICONS self.board = self.create_board() def create_board(self): """ create the game board with the given board size and icons :return: 2-dimensional list, the game board >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) >>> mc.create_board() mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ def is_valid_move(self, pos1, pos2): """ check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions) :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return:True or False ,representing whether the move of two icons is valid >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ def remove_icons(self, pos1, pos2): """ remove the connected icons on the game board :param pos1: position tuple(x, y) of the first icon to be removed :param pos2: position tuple(x, y) of the second icon to be removed :return: None >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.remove_icons((0, 0), (1, 0)) mc.board = [[' ', 'b', 'c', 'a'], [' ', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ def is_game_over(self): """ Check if the game is over (i.e., if there are no more icons on the game board) :return: True or False ,representing whether the game is over >>> mc = MahjongConnect([4, 4] ['a', 'b', 'c']) >>> mc.board = [[' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' ']] >>> mc.is_game_over() True """
def has_path(self, pos1, pos2): visited = set() stack = [pos1] while stack: current_pos = stack.pop() if current_pos == pos2: return True if current_pos in visited: continue visited.add(current_pos) x, y = current_pos # Check adjacent positions (up, down, left, right) for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]: new_x, new_y = x + dx, y + dy if 0 <= new_x < self.BOARD_SIZE[0] and 0 <= new_y < self.BOARD_SIZE[1]: if (new_x, new_y) not in visited and self.board[new_x][new_y] == self.board[x][y]: stack.append((new_x, new_y)) return False
check if there is a path between two icons
ClassEval_54_sum
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): self.BOARD_SIZE = BOARD_SIZE self.ICONS = ICONS self.board = self.create_board() def create_board(self): """ create the game board with the given board size and icons :return: 2-dimensional list, the game board >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) >>> mc.create_board() mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ board = [[random.choice(self.ICONS) for _ in range(self.BOARD_SIZE[1])] for _ in range(self.BOARD_SIZE[0])] return board def is_valid_move(self, pos1, pos2): """ check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions) :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return:True or False ,representing whether the move of two icons is valid >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ x1, y1 = pos1 x2, y2 = pos2 # Check if positions are within the game board range if not (0 <= x1 < self.BOARD_SIZE[0] and 0 <= y1 < self.BOARD_SIZE[1] and 0 <= x2 < self.BOARD_SIZE[ 0] and 0 <= y2 < self.BOARD_SIZE[1]): return False # Check if the two positions are the same if pos1 == pos2: return False # Check if the two positions have the same icon if self.board[x1][y1] != self.board[x2][y2]: return False # Check if there is a valid path between the two positions if not self.has_path(pos1, pos2): return False return True def has_path(self, pos1, pos2): """ check if there is a path between two icons :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return: True or False ,representing whether there is a path between two icons >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ visited = set() stack = [pos1] while stack: current_pos = stack.pop() if current_pos == pos2: return True if current_pos in visited: continue visited.add(current_pos) x, y = current_pos # Check adjacent positions (up, down, left, right) for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]: new_x, new_y = x + dx, y + dy if 0 <= new_x < self.BOARD_SIZE[0] and 0 <= new_y < self.BOARD_SIZE[1]: if (new_x, new_y) not in visited and self.board[new_x][new_y] == self.board[x][y]: stack.append((new_x, new_y)) return False def is_game_over(self): """ Check if the game is over (i.e., if there are no more icons on the game board) :return: True or False ,representing whether the game is over >>> mc = MahjongConnect([4, 4] ['a', 'b', 'c']) >>> mc.board = [[' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' ']] >>> mc.is_game_over() True """ for row in self.board: if any(icon != ' ' for icon in row): return False return True
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): """ initialize the board size and the icon list, create the game board :param BOARD_SIZE: list of two integer numbers, representing the number of rows and columns of the game board :param ICONS: list of string, representing the icons >>>mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.BOARD_SIZE = [4, 4] mc.ICONS = ['a', 'b', 'c'] mc.board = mc.create_board() """ self.BOARD_SIZE = BOARD_SIZE self.ICONS = ICONS self.board = self.create_board() def create_board(self): """ create the game board with the given board size and icons :return: 2-dimensional list, the game board >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) >>> mc.create_board() mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ def is_valid_move(self, pos1, pos2): """ check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions) :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return:True or False ,representing whether the move of two icons is valid >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ def has_path(self, pos1, pos2): """ check if there is a path between two icons :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return: True or False ,representing whether there is a path between two icons >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ def is_game_over(self): """ Check if the game is over (i.e., if there are no more icons on the game board) :return: True or False ,representing whether the game is over >>> mc = MahjongConnect([4, 4] ['a', 'b', 'c']) >>> mc.board = [[' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' ']] >>> mc.is_game_over() True """
def remove_icons(self, pos1, pos2): x1, y1 = pos1 x2, y2 = pos2 self.board[x1][y1] = ' ' self.board[x2][y2] = ' '
remove the connected icons on the game board
ClassEval_54_sum
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): self.BOARD_SIZE = BOARD_SIZE self.ICONS = ICONS self.board = self.create_board() def create_board(self): """ create the game board with the given board size and icons :return: 2-dimensional list, the game board >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) >>> mc.create_board() mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ board = [[random.choice(self.ICONS) for _ in range(self.BOARD_SIZE[1])] for _ in range(self.BOARD_SIZE[0])] return board def is_valid_move(self, pos1, pos2): """ check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions) :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return:True or False ,representing whether the move of two icons is valid >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ x1, y1 = pos1 x2, y2 = pos2 # Check if positions are within the game board range if not (0 <= x1 < self.BOARD_SIZE[0] and 0 <= y1 < self.BOARD_SIZE[1] and 0 <= x2 < self.BOARD_SIZE[ 0] and 0 <= y2 < self.BOARD_SIZE[1]): return False # Check if the two positions are the same if pos1 == pos2: return False # Check if the two positions have the same icon if self.board[x1][y1] != self.board[x2][y2]: return False # Check if there is a valid path between the two positions if not self.has_path(pos1, pos2): return False return True def has_path(self, pos1, pos2): """ check if there is a path between two icons :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return: True or False ,representing whether there is a path between two icons >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ visited = set() stack = [pos1] while stack: current_pos = stack.pop() if current_pos == pos2: return True if current_pos in visited: continue visited.add(current_pos) x, y = current_pos # Check adjacent positions (up, down, left, right) for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]: new_x, new_y = x + dx, y + dy if 0 <= new_x < self.BOARD_SIZE[0] and 0 <= new_y < self.BOARD_SIZE[1]: if (new_x, new_y) not in visited and self.board[new_x][new_y] == self.board[x][y]: stack.append((new_x, new_y)) return False def remove_icons(self, pos1, pos2): """ remove the connected icons on the game board :param pos1: position tuple(x, y) of the first icon to be removed :param pos2: position tuple(x, y) of the second icon to be removed :return: None >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.remove_icons((0, 0), (1, 0)) mc.board = [[' ', 'b', 'c', 'a'], [' ', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ x1, y1 = pos1 x2, y2 = pos2 self.board[x1][y1] = ' ' self.board[x2][y2] = ' ' def is_game_over(self): for row in self.board: if any(icon != ' ' for icon in row): return False return True
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): """ initialize the board size and the icon list, create the game board :param BOARD_SIZE: list of two integer numbers, representing the number of rows and columns of the game board :param ICONS: list of string, representing the icons >>>mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.BOARD_SIZE = [4, 4] mc.ICONS = ['a', 'b', 'c'] mc.board = mc.create_board() """ self.BOARD_SIZE = BOARD_SIZE self.ICONS = ICONS self.board = self.create_board() def create_board(self): """ create the game board with the given board size and icons :return: 2-dimensional list, the game board >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) >>> mc.create_board() mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ def is_valid_move(self, pos1, pos2): """ check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions) :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return:True or False ,representing whether the move of two icons is valid >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ def has_path(self, pos1, pos2): """ check if there is a path between two icons :param pos1: position tuple(x, y) of the first icon :param pos2: position tuple(x, y) of the second icon :return: True or False ,representing whether there is a path between two icons >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.is_valid_move((0, 0), (1, 0)) True """ def remove_icons(self, pos1, pos2): """ remove the connected icons on the game board :param pos1: position tuple(x, y) of the first icon to be removed :param pos2: position tuple(x, y) of the second icon to be removed :return: None >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c']) mc.board = [['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] >>> mc.remove_icons((0, 0), (1, 0)) mc.board = [[' ', 'b', 'c', 'a'], [' ', 'b', 'c', 'a'], ['a', 'b', 'c', 'a'], ['a', 'b', 'c', 'a']] """ def is_game_over(self): """ Check if the game is over (i.e., if there are no more icons on the game board) :return: True or False ,representing whether the game is over >>> mc = MahjongConnect([4, 4] ['a', 'b', 'c']) >>> mc.board = [[' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' '], >>> [' ', ' ', ' ', ' ']] >>> mc.is_game_over() True """
def is_game_over(self): for row in self.board: if any(icon != ' ' for icon in row): return False return True
Check if the game is over (i.e., if there are no more icons on the game board)
ClassEval_55_sum
class Manacher: """ his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string. """ def __init__(self, input_string) -> None: self.input_string = input_string def palindromic_string(self): """ Finds the longest palindromic substring in the given string. :return: The longest palindromic substring, str. >>> manacher = Manacher('ababaxse') >>> manacher.palindromic_string() 'ababa' """ max_length = 0 new_input_string = "" output_string = "" for i in self.input_string[:len(self.input_string) - 1]: new_input_string += i + "|" new_input_string += self.input_string[-1] for i in range(len(new_input_string)): length =self.palindromic_length(i, 1, new_input_string) if max_length < length: max_length = length start = i for i in new_input_string[start - max_length:start + max_length + 1]: if i != "|": output_string += i return output_string
class Manacher: """ his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string. """ def __init__(self, input_string) -> None: """ Initializes the Manacher class with the given input_string. :param input_string: The input_string to be searched, str. """ self.input_string = input_string def palindromic_string(self): """ Finds the longest palindromic substring in the given string. :return: The longest palindromic substring, str. >>> manacher = Manacher('ababaxse') >>> manacher.palindromic_string() 'ababa' """
def palindromic_length(self, center, diff, string): if (center - diff == -1 or center + diff == len(string) or string[center - diff] != string[center + diff]): return 0 return 1 + self.palindromic_length(center, diff + 1, string)
Recursively calculates the length of the palindromic substring based on a given center, difference value, and input string.
ClassEval_55_sum
class Manacher: """ his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string. """ def __init__(self, input_string) -> None: self.input_string = input_string def palindromic_length(self, center, diff, string): """ Recursively calculates the length of the palindromic substring based on a given center, difference value, and input string. :param center: The center of the palindromic substring, int. :param diff: The difference between the center and the current position, int. :param string: The string to be searched, str. :return: The length of the palindromic substring, int. >>> manacher = Manacher('ababa') >>> manacher.palindromic_length(2, 1, 'a|b|a|b|a') 2 """ if (center - diff == -1 or center + diff == len(string) or string[center - diff] != string[center + diff]): return 0 return 1 + self.palindromic_length(center, diff + 1, string) def palindromic_string(self): max_length = 0 new_input_string = "" output_string = "" for i in self.input_string[:len(self.input_string) - 1]: new_input_string += i + "|" new_input_string += self.input_string[-1] for i in range(len(new_input_string)): length =self.palindromic_length(i, 1, new_input_string) if max_length < length: max_length = length start = i for i in new_input_string[start - max_length:start + max_length + 1]: if i != "|": output_string += i return output_string
class Manacher: """ his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string. """ def __init__(self, input_string) -> None: """ Initializes the Manacher class with the given input_string. :param input_string: The input_string to be searched, str. """ self.input_string = input_string def palindromic_length(self, center, diff, string): """ Recursively calculates the length of the palindromic substring based on a given center, difference value, and input string. :param center: The center of the palindromic substring, int. :param diff: The difference between the center and the current position, int. :param string: The string to be searched, str. :return: The length of the palindromic substring, int. >>> manacher = Manacher('ababa') >>> manacher.palindromic_length(2, 1, 'a|b|a|b|a') 2 """ def palindromic_string(self): """ Finds the longest palindromic substring in the given string. :return: The longest palindromic substring, str. >>> manacher = Manacher('ababaxse') >>> manacher.palindromic_string() 'ababa' """
def palindromic_string(self): max_length = 0 new_input_string = "" output_string = "" for i in self.input_string[:len(self.input_string) - 1]: new_input_string += i + "|" new_input_string += self.input_string[-1] for i in range(len(new_input_string)): length =self.palindromic_length(i, 1, new_input_string) if max_length < length: max_length = length start = i for i in new_input_string[start - max_length:start + max_length + 1]: if i != "|": output_string += i return output_string
Finds the longest palindromic substring in the given string.
ClassEval_56_sum
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def precision(self, predicted_labels, true_labels): """ Calculate precision :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.precision([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) if self.true_positives + self.false_positives == 0: return 0.0 return self.true_positives / (self.true_positives + self.false_positives) def recall(self, predicted_labels, true_labels): """ Calculate recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.recall([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) if self.true_positives + self.false_negatives == 0: return 0.0 return self.true_positives / (self.true_positives + self.false_negatives) def f1_score(self, predicted_labels, true_labels): """ Calculate f1 score, which is the harmonic mean of precision and recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) precision = self.precision(predicted_labels, true_labels) recall = self.recall(predicted_labels, true_labels) if precision + recall == 0.0: return 0.0 return (2 * precision * recall) / (precision + recall) def accuracy(self, predicted_labels, true_labels): """ Calculate accuracy :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>>mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) total = self.true_positives + self.true_negatives + self.false_positives + self.false_negatives if total == 0: return 0.0 return (self.true_positives + self.true_negatives) / total
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): """ Initialize the number of all four samples to 0 """ self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def precision(self, predicted_labels, true_labels): """ Calculate precision :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.precision([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ def recall(self, predicted_labels, true_labels): """ Calculate recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.recall([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ def f1_score(self, predicted_labels, true_labels): """ Calculate f1 score, which is the harmonic mean of precision and recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ def accuracy(self, predicted_labels, true_labels): """ Calculate accuracy :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>>mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """
def update(self, predicted_labels, true_labels): for predicted, true in zip(predicted_labels, true_labels): if predicted == 1 and true == 1: self.true_positives += 1 elif predicted == 1 and true == 0: self.false_positives += 1 elif predicted == 0 and true == 1: self.false_negatives += 1 elif predicted == 0 and true == 0: self.true_negatives += 1
Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives)
ClassEval_56_sum
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def update(self, predicted_labels, true_labels): """ Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives) :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: None, change the number of corresponding samples >>> mc = MetricsCalculator() >>> mc.update([1, 1, 0, 0], [1, 0, 0, 1]) (self.true_positives, self.false_positives, self.false_negatives, self.true_negatives) = (1, 1, 1, 1) """ for predicted, true in zip(predicted_labels, true_labels): if predicted == 1 and true == 1: self.true_positives += 1 elif predicted == 1 and true == 0: self.false_positives += 1 elif predicted == 0 and true == 1: self.false_negatives += 1 elif predicted == 0 and true == 0: self.true_negatives += 1 def recall(self, predicted_labels, true_labels): """ Calculate recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.recall([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) if self.true_positives + self.false_negatives == 0: return 0.0 return self.true_positives / (self.true_positives + self.false_negatives) def f1_score(self, predicted_labels, true_labels): """ Calculate f1 score, which is the harmonic mean of precision and recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) precision = self.precision(predicted_labels, true_labels) recall = self.recall(predicted_labels, true_labels) if precision + recall == 0.0: return 0.0 return (2 * precision * recall) / (precision + recall) def accuracy(self, predicted_labels, true_labels): """ Calculate accuracy :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>>mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) total = self.true_positives + self.true_negatives + self.false_positives + self.false_negatives if total == 0: return 0.0 return (self.true_positives + self.true_negatives) / total
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): """ Initialize the number of all four samples to 0 """ self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def update(self, predicted_labels, true_labels): """ Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives) :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: None, change the number of corresponding samples >>> mc = MetricsCalculator() >>> mc.update([1, 1, 0, 0], [1, 0, 0, 1]) (self.true_positives, self.false_positives, self.false_negatives, self.true_negatives) = (1, 1, 1, 1) """ def recall(self, predicted_labels, true_labels): """ Calculate recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.recall([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ def f1_score(self, predicted_labels, true_labels): """ Calculate f1 score, which is the harmonic mean of precision and recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ def accuracy(self, predicted_labels, true_labels): """ Calculate accuracy :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>>mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """
def precision(self, predicted_labels, true_labels): self.update(predicted_labels, true_labels) if self.true_positives + self.false_positives == 0: return 0.0 return self.true_positives / (self.true_positives + self.false_positives)
Calculate precision
ClassEval_56_sum
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def update(self, predicted_labels, true_labels): """ Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives) :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: None, change the number of corresponding samples >>> mc = MetricsCalculator() >>> mc.update([1, 1, 0, 0], [1, 0, 0, 1]) (self.true_positives, self.false_positives, self.false_negatives, self.true_negatives) = (1, 1, 1, 1) """ for predicted, true in zip(predicted_labels, true_labels): if predicted == 1 and true == 1: self.true_positives += 1 elif predicted == 1 and true == 0: self.false_positives += 1 elif predicted == 0 and true == 1: self.false_negatives += 1 elif predicted == 0 and true == 0: self.true_negatives += 1 def precision(self, predicted_labels, true_labels): """ Calculate precision :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.precision([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) if self.true_positives + self.false_positives == 0: return 0.0 return self.true_positives / (self.true_positives + self.false_positives) def f1_score(self, predicted_labels, true_labels): """ Calculate f1 score, which is the harmonic mean of precision and recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) precision = self.precision(predicted_labels, true_labels) recall = self.recall(predicted_labels, true_labels) if precision + recall == 0.0: return 0.0 return (2 * precision * recall) / (precision + recall) def accuracy(self, predicted_labels, true_labels): """ Calculate accuracy :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>>mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) total = self.true_positives + self.true_negatives + self.false_positives + self.false_negatives if total == 0: return 0.0 return (self.true_positives + self.true_negatives) / total
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): """ Initialize the number of all four samples to 0 """ self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def update(self, predicted_labels, true_labels): """ Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives) :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: None, change the number of corresponding samples >>> mc = MetricsCalculator() >>> mc.update([1, 1, 0, 0], [1, 0, 0, 1]) (self.true_positives, self.false_positives, self.false_negatives, self.true_negatives) = (1, 1, 1, 1) """ def precision(self, predicted_labels, true_labels): """ Calculate precision :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.precision([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ def f1_score(self, predicted_labels, true_labels): """ Calculate f1 score, which is the harmonic mean of precision and recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ def accuracy(self, predicted_labels, true_labels): """ Calculate accuracy :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>>mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """
def recall(self, predicted_labels, true_labels): self.update(predicted_labels, true_labels) if self.true_positives + self.false_negatives == 0: return 0.0 return self.true_positives / (self.true_positives + self.false_negatives)
Calculate recall
ClassEval_56_sum
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def update(self, predicted_labels, true_labels): """ Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives) :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: None, change the number of corresponding samples >>> mc = MetricsCalculator() >>> mc.update([1, 1, 0, 0], [1, 0, 0, 1]) (self.true_positives, self.false_positives, self.false_negatives, self.true_negatives) = (1, 1, 1, 1) """ for predicted, true in zip(predicted_labels, true_labels): if predicted == 1 and true == 1: self.true_positives += 1 elif predicted == 1 and true == 0: self.false_positives += 1 elif predicted == 0 and true == 1: self.false_negatives += 1 elif predicted == 0 and true == 0: self.true_negatives += 1 def precision(self, predicted_labels, true_labels): """ Calculate precision :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.precision([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) if self.true_positives + self.false_positives == 0: return 0.0 return self.true_positives / (self.true_positives + self.false_positives) def recall(self, predicted_labels, true_labels): """ Calculate recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.recall([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) if self.true_positives + self.false_negatives == 0: return 0.0 return self.true_positives / (self.true_positives + self.false_negatives) def accuracy(self, predicted_labels, true_labels): """ Calculate accuracy :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>>mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) total = self.true_positives + self.true_negatives + self.false_positives + self.false_negatives if total == 0: return 0.0 return (self.true_positives + self.true_negatives) / total
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): """ Initialize the number of all four samples to 0 """ self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def update(self, predicted_labels, true_labels): """ Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives) :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: None, change the number of corresponding samples >>> mc = MetricsCalculator() >>> mc.update([1, 1, 0, 0], [1, 0, 0, 1]) (self.true_positives, self.false_positives, self.false_negatives, self.true_negatives) = (1, 1, 1, 1) """ def precision(self, predicted_labels, true_labels): """ Calculate precision :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.precision([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ def recall(self, predicted_labels, true_labels): """ Calculate recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.recall([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ def accuracy(self, predicted_labels, true_labels): """ Calculate accuracy :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>>mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """
def f1_score(self, predicted_labels, true_labels): self.update(predicted_labels, true_labels) precision = self.precision(predicted_labels, true_labels) recall = self.recall(predicted_labels, true_labels) if precision + recall == 0.0: return 0.0 return (2 * precision * recall) / (precision + recall)
Calculate f1 score, which is the harmonic mean of precision and recall
ClassEval_56_sum
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def update(self, predicted_labels, true_labels): """ Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives) :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: None, change the number of corresponding samples >>> mc = MetricsCalculator() >>> mc.update([1, 1, 0, 0], [1, 0, 0, 1]) (self.true_positives, self.false_positives, self.false_negatives, self.true_negatives) = (1, 1, 1, 1) """ for predicted, true in zip(predicted_labels, true_labels): if predicted == 1 and true == 1: self.true_positives += 1 elif predicted == 1 and true == 0: self.false_positives += 1 elif predicted == 0 and true == 1: self.false_negatives += 1 elif predicted == 0 and true == 0: self.true_negatives += 1 def precision(self, predicted_labels, true_labels): """ Calculate precision :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.precision([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) if self.true_positives + self.false_positives == 0: return 0.0 return self.true_positives / (self.true_positives + self.false_positives) def recall(self, predicted_labels, true_labels): """ Calculate recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.recall([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) if self.true_positives + self.false_negatives == 0: return 0.0 return self.true_positives / (self.true_positives + self.false_negatives) def f1_score(self, predicted_labels, true_labels): """ Calculate f1 score, which is the harmonic mean of precision and recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ self.update(predicted_labels, true_labels) precision = self.precision(predicted_labels, true_labels) recall = self.recall(predicted_labels, true_labels) if precision + recall == 0.0: return 0.0 return (2 * precision * recall) / (precision + recall) def accuracy(self, predicted_labels, true_labels): self.update(predicted_labels, true_labels) total = self.true_positives + self.true_negatives + self.false_positives + self.false_negatives if total == 0: return 0.0 return (self.true_positives + self.true_negatives) / total
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): """ Initialize the number of all four samples to 0 """ self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def update(self, predicted_labels, true_labels): """ Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives) :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: None, change the number of corresponding samples >>> mc = MetricsCalculator() >>> mc.update([1, 1, 0, 0], [1, 0, 0, 1]) (self.true_positives, self.false_positives, self.false_negatives, self.true_negatives) = (1, 1, 1, 1) """ def precision(self, predicted_labels, true_labels): """ Calculate precision :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.precision([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ def recall(self, predicted_labels, true_labels): """ Calculate recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.recall([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ def f1_score(self, predicted_labels, true_labels): """ Calculate f1 score, which is the harmonic mean of precision and recall :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>> mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """ def accuracy(self, predicted_labels, true_labels): """ Calculate accuracy :param predicted_labels: list, predicted results :param true_labels: list, true labels :return: float >>> mc = MetricsCalculator() >>>mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1]) 0.5 """
def accuracy(self, predicted_labels, true_labels): self.update(predicted_labels, true_labels) total = self.true_positives + self.true_negatives + self.false_positives + self.false_negatives if total == 0: return 0.0 return (self.true_positives + self.true_negatives) / total
Calculate accuracy
ClassEval_57_sum
import numpy as np class MetricsCalculator2: """ The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision. """ def __init__(self): pass @staticmethod @staticmethod def map(data): """ compute the MAP of the input data. MAP is a widely used evaluation index. It is the mean of AP (average precision). :param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground truth num),ground truth num is the total ground num. ([1,0,...],5), or list of tuple eg. [([1,0,1,...],5),([1,0,...],6),([0,0,...],5)]. 1 stands for a correct answer, 0 stands for a wrong answer. :return: if input data is list, return the recall of this list. if the input data is list of list, return the average recall on all list. The second return value is a list of precision for each input. >>> MetricsCalculator2.map(([1, 0, 1, 0], 4)) >>> MetricsCalculator2.map([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)]) 0.41666666666666663, [0.41666666666666663] 0.3333333333333333, [0.41666666666666663, 0.25] """ if type(data) != list and type(data) != tuple: raise Exception("the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple") if len(data) == 0: return 0.0, [0.0] if type(data) == tuple: (sub_list, total_num) = data sub_list = np.array(sub_list) if total_num == 0: return 0.0, [0.0] else: ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1) right_ranking_list = [] count = 1 for t in sub_list: if t == 0: right_ranking_list.append(0) else: right_ranking_list.append(count) count += 1 ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num return ap, [ap] if type(data) == list: separate_result = [] for (sub_list, total_num) in data: sub_list = np.array(sub_list) if total_num == 0: ap = 0.0 else: ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1) right_ranking_list = [] count = 1 for t in sub_list: if t == 0: right_ranking_list.append(0) else: right_ranking_list.append(count) count += 1 ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num separate_result.append(ap) return np.mean(separate_result), separate_result
import numpy as np class MetricsCalculator2: """ The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision. """ def __init__(self): pass @staticmethod @staticmethod def map(data): """ compute the MAP of the input data. MAP is a widely used evaluation index. It is the mean of AP (average precision). :param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground truth num),ground truth num is the total ground num. ([1,0,...],5), or list of tuple eg. [([1,0,1,...],5),([1,0,...],6),([0,0,...],5)]. 1 stands for a correct answer, 0 stands for a wrong answer. :return: if input data is list, return the recall of this list. if the input data is list of list, return the average recall on all list. The second return value is a list of precision for each input. >>> MetricsCalculator2.map(([1, 0, 1, 0], 4)) >>> MetricsCalculator2.map([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)]) 0.41666666666666663, [0.41666666666666663] 0.3333333333333333, [0.41666666666666663, 0.25] """
def mrr(data): if type(data) != list and type(data) != tuple: raise Exception("the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple") if len(data) == 0: return 0.0, [0.0] if type(data) == tuple: (sub_list, total_num) = data sub_list = np.array(sub_list) if total_num == 0: return 0.0, [0.0] else: ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1) mr_np = sub_list * ranking_array mr = 0.0 for team in mr_np: if team > 0: mr = team break return mr, [mr] if type(data) == list: separate_result = [] for (sub_list, total_num) in data: sub_list = np.array(sub_list) if total_num == 0: mr = 0.0 else: ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1) mr_np = sub_list * ranking_array mr = 0.0 for team in mr_np: if team > 0: mr = team break separate_result.append(mr) return np.mean(separate_result), separate_result
compute the MRR of the input data. MRR is a widely used evaluation index. It is the mean of reciprocal rank.
ClassEval_57_sum
import numpy as np class MetricsCalculator2: """ The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision. """ def __init__(self): pass @staticmethod def mrr(data): """ compute the MRR of the input data. MRR is a widely used evaluation index. It is the mean of reciprocal rank. :param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground truth num),ground truth num is the total ground num. ([1,0,...],5), or list of tuple eg. [([1,0,1,...],5),([1,0,...],6),([0,0,...],5)]. 1 stands for a correct answer, 0 stands for a wrong answer. :return: if input data is list, return the recall of this list. if the input data is list of list, return the average recall on all list. The second return value is a list of precision for each input. >>> MetricsCalculator2.mrr(([1, 0, 1, 0], 4)) >>> MetricsCalculator2.mrr([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)]) 1.0, [1.0] 0.75, [1.0, 0.5] """ if type(data) != list and type(data) != tuple: raise Exception("the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple") if len(data) == 0: return 0.0, [0.0] if type(data) == tuple: (sub_list, total_num) = data sub_list = np.array(sub_list) if total_num == 0: return 0.0, [0.0] else: ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1) mr_np = sub_list * ranking_array mr = 0.0 for team in mr_np: if team > 0: mr = team break return mr, [mr] if type(data) == list: separate_result = [] for (sub_list, total_num) in data: sub_list = np.array(sub_list) if total_num == 0: mr = 0.0 else: ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1) mr_np = sub_list * ranking_array mr = 0.0 for team in mr_np: if team > 0: mr = team break separate_result.append(mr) return np.mean(separate_result), separate_result @staticmethod def map(data): if type(data) != list and type(data) != tuple: raise Exception("the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple") if len(data) == 0: return 0.0, [0.0] if type(data) == tuple: (sub_list, total_num) = data sub_list = np.array(sub_list) if total_num == 0: return 0.0, [0.0] else: ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1) right_ranking_list = [] count = 1 for t in sub_list: if t == 0: right_ranking_list.append(0) else: right_ranking_list.append(count) count += 1 ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num return ap, [ap] if type(data) == list: separate_result = [] for (sub_list, total_num) in data: sub_list = np.array(sub_list) if total_num == 0: ap = 0.0 else: ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1) right_ranking_list = [] count = 1 for t in sub_list: if t == 0: right_ranking_list.append(0) else: right_ranking_list.append(count) count += 1 ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num separate_result.append(ap) return np.mean(separate_result), separate_result
import numpy as np class MetricsCalculator2: """ The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision. """ def __init__(self): pass @staticmethod def mrr(data): """ compute the MRR of the input data. MRR is a widely used evaluation index. It is the mean of reciprocal rank. :param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground truth num),ground truth num is the total ground num. ([1,0,...],5), or list of tuple eg. [([1,0,1,...],5),([1,0,...],6),([0,0,...],5)]. 1 stands for a correct answer, 0 stands for a wrong answer. :return: if input data is list, return the recall of this list. if the input data is list of list, return the average recall on all list. The second return value is a list of precision for each input. >>> MetricsCalculator2.mrr(([1, 0, 1, 0], 4)) >>> MetricsCalculator2.mrr([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)]) 1.0, [1.0] 0.75, [1.0, 0.5] """ @staticmethod def map(data): """ compute the MAP of the input data. MAP is a widely used evaluation index. It is the mean of AP (average precision). :param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground truth num),ground truth num is the total ground num. ([1,0,...],5), or list of tuple eg. [([1,0,1,...],5),([1,0,...],6),([0,0,...],5)]. 1 stands for a correct answer, 0 stands for a wrong answer. :return: if input data is list, return the recall of this list. if the input data is list of list, return the average recall on all list. The second return value is a list of precision for each input. >>> MetricsCalculator2.map(([1, 0, 1, 0], 4)) >>> MetricsCalculator2.map([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)]) 0.41666666666666663, [0.41666666666666663] 0.3333333333333333, [0.41666666666666663, 0.25] """
@staticmethod def map(data): if type(data) != list and type(data) != tuple: raise Exception("the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple") if len(data) == 0: return 0.0, [0.0] if type(data) == tuple: (sub_list, total_num) = data sub_list = np.array(sub_list) if total_num == 0: return 0.0, [0.0] else: ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1) right_ranking_list = [] count = 1 for t in sub_list: if t == 0: right_ranking_list.append(0) else: right_ranking_list.append(count) count += 1 ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num return ap, [ap] if type(data) == list: separate_result = [] for (sub_list, total_num) in data: sub_list = np.array(sub_list) if total_num == 0: ap = 0.0 else: ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1) right_ranking_list = [] count = 1 for t in sub_list: if t == 0: right_ranking_list.append(0) else: right_ranking_list.append(count) count += 1 ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num separate_result.append(ap) return np.mean(separate_result), separate_result
compute the MAP of the input data. MAP is a widely used evaluation index. It is the mean of AP (average precision).
ClassEval_58_sum
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: self.n = n self.k = k self.minesweeper_map = self.generate_mine_sweeper_map() self.player_map = self.generate_playerMap() self.score = 0 def generate_mine_sweeper_map(self): arr = [[0 for row in range(self.n)] for column in range(self.n)] for num in range(self.k): x = random.randint(0, self.n-1) y = random.randint(0, self.n-1) arr[y][x] = 'X' if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-1): if arr[y][x+1] != 'X': arr[y][x+1] += 1 if (x >=1 and x <= self.n-1) and (y >= 0 and y <= self.n-1): if arr[y][x-1] != 'X': arr[y][x-1] += 1 if (x >= 1 and x <= self.n-1) and (y >= 1 and y <= self.n-1): if arr[y-1][x-1] != 'X': arr[y-1][x-1] += 1 if (x >= 0 and x <= self.n-2) and (y >= 1 and y <= self.n-1): if arr[y-1][x+1] != 'X': arr[y-1][x+1] += 1 if (x >= 0 and x <= self.n-1) and (y >= 1 and y <= self.n-1): if arr[y-1][x] != 'X': arr[y-1][x] += 1 if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-2): if arr[y+1][x+1] != 'X': arr[y+1][x+1] += 1 if (x >= 1 and x <= self.n-1) and (y >= 0 and y <= self.n-2): if arr[y+1][x-1] != 'X': arr[y+1][x-1] += 1 if (x >= 0 and x <= self.n-1) and (y >= 0 and y <= self.n-2): if arr[y+1][x] != 'X': arr[y+1][x] += 1 return arr def generate_playerMap(self): """ Generates a player map with the given size of the board, the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'-' represents the unknown position. :return: The player map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.generate_playerMap() [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] """ arr = [['-' for row in range(self.n)] for column in range(self.n)] return arr def check_won(self, map): for i in range(self.n): for j in range(self.n): if map[i][j] == '-' and self.minesweeper_map[i][j] != 'X': return False return True def sweep(self, x, y): """ Sweeps the given position. :param x: The x coordinate of the position, int. :param y: The y coordinate of the position, int. :return: True if the player has won the game, False otherwise,if the game still continues, return the player map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]] >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] >>> minesweeper_game.sweep(1, 1) [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']] """ if (self.minesweeper_map[x][y] == 'X'): return False else: self.player_map[x][y] = self.minesweeper_map[x][y] self.score += 1 if self.check_won(self.player_map) == True: return True return self.player_map
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: """ Initializes the MinesweeperGame class with the size of the board and the number of mines. :param n: The size of the board, int. :param k: The number of mines, int. """ self.n = n self.k = k self.minesweeper_map = self.generate_mine_sweeper_map() self.player_map = self.generate_playerMap() self.score = 0 def generate_playerMap(self): """ Generates a player map with the given size of the board, the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'-' represents the unknown position. :return: The player map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.generate_playerMap() [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] """ def check_won(self,map): """ Checks whether the player has won the game,if there are just mines in the player map,return True,otherwise return False. :return: True if the player has won the game, False otherwise. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]] >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] >>> minesweeper_game.check_won(minesweeper_game.player_map) False """ def sweep(self, x, y): """ Sweeps the given position. :param x: The x coordinate of the position, int. :param y: The y coordinate of the position, int. :return: True if the player has won the game, False otherwise,if the game still continues, return the player map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]] >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] >>> minesweeper_game.sweep(1, 1) [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']] """
def generate_mine_sweeper_map(self): arr = [[0 for row in range(self.n)] for column in range(self.n)] for num in range(self.k): x = random.randint(0, self.n-1) y = random.randint(0, self.n-1) arr[y][x] = 'X' if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-1): if arr[y][x+1] != 'X': arr[y][x+1] += 1 if (x >=1 and x <= self.n-1) and (y >= 0 and y <= self.n-1): if arr[y][x-1] != 'X': arr[y][x-1] += 1 if (x >= 1 and x <= self.n-1) and (y >= 1 and y <= self.n-1): if arr[y-1][x-1] != 'X': arr[y-1][x-1] += 1 if (x >= 0 and x <= self.n-2) and (y >= 1 and y <= self.n-1): if arr[y-1][x+1] != 'X': arr[y-1][x+1] += 1 if (x >= 0 and x <= self.n-1) and (y >= 1 and y <= self.n-1): if arr[y-1][x] != 'X': arr[y-1][x] += 1 if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-2): if arr[y+1][x+1] != 'X': arr[y+1][x+1] += 1 if (x >= 1 and x <= self.n-1) and (y >= 0 and y <= self.n-2): if arr[y+1][x-1] != 'X': arr[y+1][x-1] += 1 if (x >= 0 and x <= self.n-1) and (y >= 0 and y <= self.n-2): if arr[y+1][x] != 'X': arr[y+1][x] += 1 return arr
Generates a minesweeper map with the given size of the board and the number of mines,the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'X' represents the mine,other numbers represent the number of mines around the position.
ClassEval_58_sum
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: self.n = n self.k = k self.minesweeper_map = self.generate_mine_sweeper_map() self.player_map = self.generate_playerMap() self.score = 0 def generate_mine_sweeper_map(self): """ Generates a minesweeper map with the given size of the board and the number of mines,the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'X' represents the mine,other numbers represent the number of mines around the position. :return: The minesweeper map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.generate_mine_sweeper_map() [['X', 1, 0], [1, 1, 0], [0, 0, 0]] """ arr = [[0 for row in range(self.n)] for column in range(self.n)] for num in range(self.k): x = random.randint(0, self.n-1) y = random.randint(0, self.n-1) arr[y][x] = 'X' if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-1): if arr[y][x+1] != 'X': arr[y][x+1] += 1 if (x >=1 and x <= self.n-1) and (y >= 0 and y <= self.n-1): if arr[y][x-1] != 'X': arr[y][x-1] += 1 if (x >= 1 and x <= self.n-1) and (y >= 1 and y <= self.n-1): if arr[y-1][x-1] != 'X': arr[y-1][x-1] += 1 if (x >= 0 and x <= self.n-2) and (y >= 1 and y <= self.n-1): if arr[y-1][x+1] != 'X': arr[y-1][x+1] += 1 if (x >= 0 and x <= self.n-1) and (y >= 1 and y <= self.n-1): if arr[y-1][x] != 'X': arr[y-1][x] += 1 if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-2): if arr[y+1][x+1] != 'X': arr[y+1][x+1] += 1 if (x >= 1 and x <= self.n-1) and (y >= 0 and y <= self.n-2): if arr[y+1][x-1] != 'X': arr[y+1][x-1] += 1 if (x >= 0 and x <= self.n-1) and (y >= 0 and y <= self.n-2): if arr[y+1][x] != 'X': arr[y+1][x] += 1 return arr def check_won(self, map): for i in range(self.n): for j in range(self.n): if map[i][j] == '-' and self.minesweeper_map[i][j] != 'X': return False return True def sweep(self, x, y): """ Sweeps the given position. :param x: The x coordinate of the position, int. :param y: The y coordinate of the position, int. :return: True if the player has won the game, False otherwise,if the game still continues, return the player map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]] >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] >>> minesweeper_game.sweep(1, 1) [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']] """ if (self.minesweeper_map[x][y] == 'X'): return False else: self.player_map[x][y] = self.minesweeper_map[x][y] self.score += 1 if self.check_won(self.player_map) == True: return True return self.player_map
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: """ Initializes the MinesweeperGame class with the size of the board and the number of mines. :param n: The size of the board, int. :param k: The number of mines, int. """ self.n = n self.k = k self.minesweeper_map = self.generate_mine_sweeper_map() self.player_map = self.generate_playerMap() self.score = 0 def generate_mine_sweeper_map(self): """ Generates a minesweeper map with the given size of the board and the number of mines,the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'X' represents the mine,other numbers represent the number of mines around the position. :return: The minesweeper map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.generate_mine_sweeper_map() [['X', 1, 0], [1, 1, 0], [0, 0, 0]] """ def check_won(self,map): """ Checks whether the player has won the game,if there are just mines in the player map,return True,otherwise return False. :return: True if the player has won the game, False otherwise. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]] >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] >>> minesweeper_game.check_won(minesweeper_game.player_map) False """ def sweep(self, x, y): """ Sweeps the given position. :param x: The x coordinate of the position, int. :param y: The y coordinate of the position, int. :return: True if the player has won the game, False otherwise,if the game still continues, return the player map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]] >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] >>> minesweeper_game.sweep(1, 1) [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']] """
def generate_playerMap(self): arr = [['-' for row in range(self.n)] for column in range(self.n)] return arr
Generates a player map with the given size of the board, the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'-' represents the unknown position.
ClassEval_58_sum
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: self.n = n self.k = k self.minesweeper_map = self.generate_mine_sweeper_map() self.player_map = self.generate_playerMap() self.score = 0 def generate_mine_sweeper_map(self): """ Generates a minesweeper map with the given size of the board and the number of mines,the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'X' represents the mine,other numbers represent the number of mines around the position. :return: The minesweeper map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.generate_mine_sweeper_map() [['X', 1, 0], [1, 1, 0], [0, 0, 0]] """ arr = [[0 for row in range(self.n)] for column in range(self.n)] for num in range(self.k): x = random.randint(0, self.n-1) y = random.randint(0, self.n-1) arr[y][x] = 'X' if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-1): if arr[y][x+1] != 'X': arr[y][x+1] += 1 if (x >=1 and x <= self.n-1) and (y >= 0 and y <= self.n-1): if arr[y][x-1] != 'X': arr[y][x-1] += 1 if (x >= 1 and x <= self.n-1) and (y >= 1 and y <= self.n-1): if arr[y-1][x-1] != 'X': arr[y-1][x-1] += 1 if (x >= 0 and x <= self.n-2) and (y >= 1 and y <= self.n-1): if arr[y-1][x+1] != 'X': arr[y-1][x+1] += 1 if (x >= 0 and x <= self.n-1) and (y >= 1 and y <= self.n-1): if arr[y-1][x] != 'X': arr[y-1][x] += 1 if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-2): if arr[y+1][x+1] != 'X': arr[y+1][x+1] += 1 if (x >= 1 and x <= self.n-1) and (y >= 0 and y <= self.n-2): if arr[y+1][x-1] != 'X': arr[y+1][x-1] += 1 if (x >= 0 and x <= self.n-1) and (y >= 0 and y <= self.n-2): if arr[y+1][x] != 'X': arr[y+1][x] += 1 return arr def generate_playerMap(self): """ Generates a player map with the given size of the board, the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'-' represents the unknown position. :return: The player map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.generate_playerMap() [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] """ arr = [['-' for row in range(self.n)] for column in range(self.n)] return arr def check_won(self, map): for i in range(self.n): for j in range(self.n): if map[i][j] == '-' and self.minesweeper_map[i][j] != 'X': return False return True def sweep(self, x, y): """ Sweeps the given position. :param x: The x coordinate of the position, int. :param y: The y coordinate of the position, int. :return: True if the player has won the game, False otherwise,if the game still continues, return the player map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]] >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] >>> minesweeper_game.sweep(1, 1) [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']] """ if (self.minesweeper_map[x][y] == 'X'): return False else: self.player_map[x][y] = self.minesweeper_map[x][y] self.score += 1 if self.check_won(self.player_map) == True: return True return self.player_map
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: """ Initializes the MinesweeperGame class with the size of the board and the number of mines. :param n: The size of the board, int. :param k: The number of mines, int. """ self.n = n self.k = k self.minesweeper_map = self.generate_mine_sweeper_map() self.player_map = self.generate_playerMap() self.score = 0 def generate_mine_sweeper_map(self): """ Generates a minesweeper map with the given size of the board and the number of mines,the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'X' represents the mine,other numbers represent the number of mines around the position. :return: The minesweeper map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.generate_mine_sweeper_map() [['X', 1, 0], [1, 1, 0], [0, 0, 0]] """ def generate_playerMap(self): """ Generates a player map with the given size of the board, the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'-' represents the unknown position. :return: The player map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.generate_playerMap() [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] """ def sweep(self, x, y): """ Sweeps the given position. :param x: The x coordinate of the position, int. :param y: The y coordinate of the position, int. :return: True if the player has won the game, False otherwise,if the game still continues, return the player map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]] >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] >>> minesweeper_game.sweep(1, 1) [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']] """
def check_won(self, map): for i in range(self.n): for j in range(self.n): if map[i][j] == '-' and self.minesweeper_map[i][j] != 'X': return False return True
Checks whether the player has won the game,if there are just mines in the player map,return True,otherwise return False.
ClassEval_58_sum
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: self.n = n self.k = k self.minesweeper_map = self.generate_mine_sweeper_map() self.player_map = self.generate_playerMap() self.score = 0 def generate_mine_sweeper_map(self): """ Generates a minesweeper map with the given size of the board and the number of mines,the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'X' represents the mine,other numbers represent the number of mines around the position. :return: The minesweeper map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.generate_mine_sweeper_map() [['X', 1, 0], [1, 1, 0], [0, 0, 0]] """ arr = [[0 for row in range(self.n)] for column in range(self.n)] for num in range(self.k): x = random.randint(0, self.n-1) y = random.randint(0, self.n-1) arr[y][x] = 'X' if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-1): if arr[y][x+1] != 'X': arr[y][x+1] += 1 if (x >=1 and x <= self.n-1) and (y >= 0 and y <= self.n-1): if arr[y][x-1] != 'X': arr[y][x-1] += 1 if (x >= 1 and x <= self.n-1) and (y >= 1 and y <= self.n-1): if arr[y-1][x-1] != 'X': arr[y-1][x-1] += 1 if (x >= 0 and x <= self.n-2) and (y >= 1 and y <= self.n-1): if arr[y-1][x+1] != 'X': arr[y-1][x+1] += 1 if (x >= 0 and x <= self.n-1) and (y >= 1 and y <= self.n-1): if arr[y-1][x] != 'X': arr[y-1][x] += 1 if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-2): if arr[y+1][x+1] != 'X': arr[y+1][x+1] += 1 if (x >= 1 and x <= self.n-1) and (y >= 0 and y <= self.n-2): if arr[y+1][x-1] != 'X': arr[y+1][x-1] += 1 if (x >= 0 and x <= self.n-1) and (y >= 0 and y <= self.n-2): if arr[y+1][x] != 'X': arr[y+1][x] += 1 return arr def generate_playerMap(self): """ Generates a player map with the given size of the board, the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'-' represents the unknown position. :return: The player map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.generate_playerMap() [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] """ arr = [['-' for row in range(self.n)] for column in range(self.n)] return arr def check_won(self, map): for i in range(self.n): for j in range(self.n): if map[i][j] == '-' and self.minesweeper_map[i][j] != 'X': return False return True def sweep(self, x, y): if (self.minesweeper_map[x][y] == 'X'): return False else: self.player_map[x][y] = self.minesweeper_map[x][y] self.score += 1 if self.check_won(self.player_map) == True: return True return self.player_map
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: """ Initializes the MinesweeperGame class with the size of the board and the number of mines. :param n: The size of the board, int. :param k: The number of mines, int. """ self.n = n self.k = k self.minesweeper_map = self.generate_mine_sweeper_map() self.player_map = self.generate_playerMap() self.score = 0 def generate_mine_sweeper_map(self): """ Generates a minesweeper map with the given size of the board and the number of mines,the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'X' represents the mine,other numbers represent the number of mines around the position. :return: The minesweeper map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.generate_mine_sweeper_map() [['X', 1, 0], [1, 1, 0], [0, 0, 0]] """ def generate_playerMap(self): """ Generates a player map with the given size of the board, the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'-' represents the unknown position. :return: The player map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.generate_playerMap() [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] """ def check_won(self,map): """ Checks whether the player has won the game,if there are just mines in the player map,return True,otherwise return False. :return: True if the player has won the game, False otherwise. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]] >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] >>> minesweeper_game.check_won(minesweeper_game.player_map) False """ def sweep(self, x, y): """ Sweeps the given position. :param x: The x coordinate of the position, int. :param y: The y coordinate of the position, int. :return: True if the player has won the game, False otherwise,if the game still continues, return the player map, list. >>> minesweeper_game = MinesweeperGame(3, 1) >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]] >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] >>> minesweeper_game.sweep(1, 1) [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']] """
def sweep(self, x, y): if (self.minesweeper_map[x][y] == 'X'): return False else: self.player_map[x][y] = self.minesweeper_map[x][y] self.score += 1 if self.check_won(self.player_map) == True: return True return self.player_map
Sweeps the given position.
ClassEval_59_sum
from datetime import datetime import numpy as np class MovieBookingSystem: """ this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. """ def __init__(self): self.movies = [] def book_ticket(self, name, seats_to_book): """ Book tickets for a movie. Change the seats value in self.movies if book successfully. :param name: str, movie name :param seats_to_book: list of tuples, representing seats to book [(row1, col1), (row2, col2), ...] :return: str, booking status message. "Movie not found." for no such movie. "Booking success." for successfully booking, or "Booking failed." otherwise >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3) >>> system.book_ticket('Batman', [(0, 0), (0, 1)]) 'Booking success.' >>> system.book_ticket('Batman', [(0, 0)]) 'Booking failed.' >>> system.book_ticket('batman', [(0, 0)]) 'Movie not found.' """ for movie in self.movies: if movie['name'] == name: for seat in seats_to_book: if movie['seats'][seat[0]][seat[1]] == 0: movie['seats'][seat[0]][seat[1]] = 1 else: return "Booking failed." return "Booking success." return "Movie not found." def available_movies(self, start_time, end_time): """ Get a list of available movies within the specified time range :param start_time: str, start time in HH:MM format :param end_time: str, end time in HH:MM format :return: list of str, names of available movies >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3) >>> system.available_movies('12:00', '22:00') ['Batman'] """ start_time = datetime.strptime(start_time, '%H:%M') end_time = datetime.strptime(end_time, '%H:%M') available_movies = [] for movie in self.movies: if start_time <= movie['start_time'] and movie['end_time'] <= end_time: available_movies.append(movie['name']) return available_movies
from datetime import datetime import numpy as np class MovieBookingSystem: """ this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. """ def __init__(self): """ Initialize movies contains the information about movies >>> system.movies [{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25), 'seats': array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])}] """ self.movies = [] def book_ticket(self, name, seats_to_book): """ Book tickets for a movie. Change the seats value in self.movies if book successfully. :param name: str, movie name :param seats_to_book: list of tuples, representing seats to book [(row1, col1), (row2, col2), ...] :return: str, booking status message. "Movie not found." for no such movie. "Booking success." for successfully booking, or "Booking failed." otherwise >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3) >>> system.book_ticket('Batman', [(0, 0), (0, 1)]) 'Booking success.' >>> system.book_ticket('Batman', [(0, 0)]) 'Booking failed.' >>> system.book_ticket('batman', [(0, 0)]) 'Movie not found.' """ def available_movies(self, start_time, end_time): """ Get a list of available movies within the specified time range :param start_time: str, start time in HH:MM format :param end_time: str, end time in HH:MM format :return: list of str, names of available movies >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3) >>> system.available_movies('12:00', '22:00') ['Batman'] """
def add_movie(self, name, price, start_time, end_time, n): movie = { 'name': name, 'price': price, 'start_time': datetime.strptime(start_time, '%H:%M'), 'end_time': datetime.strptime(end_time, '%H:%M'), 'seats': np.zeros((n, n)) } self.movies.append(movie)
Add a new movie into self.movies
ClassEval_59_sum
from datetime import datetime import numpy as np class MovieBookingSystem: """ this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. """ def __init__(self): self.movies = [] def add_movie(self, name, price, start_time, end_time, n): """ Add a new movie into self.movies :param name: str, movie name :param price: float, price for one ticket :param start_time: str :param end_time: str :param n: int, the size of seats(n*n) >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3) >>> system.movies [{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25), 'seats': array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])}] """ movie = { 'name': name, 'price': price, 'start_time': datetime.strptime(start_time, '%H:%M'), 'end_time': datetime.strptime(end_time, '%H:%M'), 'seats': np.zeros((n, n)) } self.movies.append(movie) def available_movies(self, start_time, end_time): """ Get a list of available movies within the specified time range :param start_time: str, start time in HH:MM format :param end_time: str, end time in HH:MM format :return: list of str, names of available movies >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3) >>> system.available_movies('12:00', '22:00') ['Batman'] """ start_time = datetime.strptime(start_time, '%H:%M') end_time = datetime.strptime(end_time, '%H:%M') available_movies = [] for movie in self.movies: if start_time <= movie['start_time'] and movie['end_time'] <= end_time: available_movies.append(movie['name']) return available_movies
from datetime import datetime import numpy as np class MovieBookingSystem: """ this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. """ def __init__(self): """ Initialize movies contains the information about movies >>> system.movies [{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25), 'seats': array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])}] """ self.movies = [] def add_movie(self, name, price, start_time, end_time, n): """ Add a new movie into self.movies :param name: str, movie name :param price: float, price for one ticket :param start_time: str :param end_time: str :param n: int, the size of seats(n*n) >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3) >>> system.movies [{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25), 'seats': array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])}] """ def available_movies(self, start_time, end_time): """ Get a list of available movies within the specified time range :param start_time: str, start time in HH:MM format :param end_time: str, end time in HH:MM format :return: list of str, names of available movies >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3) >>> system.available_movies('12:00', '22:00') ['Batman'] """
def book_ticket(self, name, seats_to_book): for movie in self.movies: if movie['name'] == name: for seat in seats_to_book: if movie['seats'][seat[0]][seat[1]] == 0: movie['seats'][seat[0]][seat[1]] = 1 else: return "Booking failed." return "Booking success." return "Movie not found."
Book tickets for a movie. Change the seats value in self.movies if book successfully.
ClassEval_59_sum
from datetime import datetime import numpy as np class MovieBookingSystem: """ this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. """ def __init__(self): self.movies = [] def add_movie(self, name, price, start_time, end_time, n): """ Add a new movie into self.movies :param name: str, movie name :param price: float, price for one ticket :param start_time: str :param end_time: str :param n: int, the size of seats(n*n) >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3) >>> system.movies [{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25), 'seats': array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])}] """ movie = { 'name': name, 'price': price, 'start_time': datetime.strptime(start_time, '%H:%M'), 'end_time': datetime.strptime(end_time, '%H:%M'), 'seats': np.zeros((n, n)) } self.movies.append(movie) def book_ticket(self, name, seats_to_book): """ Book tickets for a movie. Change the seats value in self.movies if book successfully. :param name: str, movie name :param seats_to_book: list of tuples, representing seats to book [(row1, col1), (row2, col2), ...] :return: str, booking status message. "Movie not found." for no such movie. "Booking success." for successfully booking, or "Booking failed." otherwise >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3) >>> system.book_ticket('Batman', [(0, 0), (0, 1)]) 'Booking success.' >>> system.book_ticket('Batman', [(0, 0)]) 'Booking failed.' >>> system.book_ticket('batman', [(0, 0)]) 'Movie not found.' """ for movie in self.movies: if movie['name'] == name: for seat in seats_to_book: if movie['seats'][seat[0]][seat[1]] == 0: movie['seats'][seat[0]][seat[1]] = 1 else: return "Booking failed." return "Booking success." return "Movie not found." def available_movies(self, start_time, end_time): start_time = datetime.strptime(start_time, '%H:%M') end_time = datetime.strptime(end_time, '%H:%M') available_movies = [] for movie in self.movies: if start_time <= movie['start_time'] and movie['end_time'] <= end_time: available_movies.append(movie['name']) return available_movies
from datetime import datetime import numpy as np class MovieBookingSystem: """ this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. """ def __init__(self): """ Initialize movies contains the information about movies >>> system.movies [{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25), 'seats': array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])}] """ self.movies = [] def add_movie(self, name, price, start_time, end_time, n): """ Add a new movie into self.movies :param name: str, movie name :param price: float, price for one ticket :param start_time: str :param end_time: str :param n: int, the size of seats(n*n) >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3) >>> system.movies [{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25), 'seats': array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])}] """ def book_ticket(self, name, seats_to_book): """ Book tickets for a movie. Change the seats value in self.movies if book successfully. :param name: str, movie name :param seats_to_book: list of tuples, representing seats to book [(row1, col1), (row2, col2), ...] :return: str, booking status message. "Movie not found." for no such movie. "Booking success." for successfully booking, or "Booking failed." otherwise >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3) >>> system.book_ticket('Batman', [(0, 0), (0, 1)]) 'Booking success.' >>> system.book_ticket('Batman', [(0, 0)]) 'Booking failed.' >>> system.book_ticket('batman', [(0, 0)]) 'Movie not found.' """ def available_movies(self, start_time, end_time): """ Get a list of available movies within the specified time range :param start_time: str, start time in HH:MM format :param end_time: str, end time in HH:MM format :return: list of str, names of available movies >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3) >>> system.available_movies('12:00', '22:00') ['Batman'] """
def available_movies(self, start_time, end_time): start_time = datetime.strptime(start_time, '%H:%M') end_time = datetime.strptime(end_time, '%H:%M') available_movies = [] for movie in self.movies: if start_time <= movie['start_time'] and movie['end_time'] <= end_time: available_movies.append(movie['name']) return available_movies
Get a list of available movies within the specified time range
ClassEval_60_sum
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() self.create_table() def insert_ticket(self, movie_name, theater_name, seat_number, customer_name): """ Inserts a new ticket into the "tickets" table. :param movie_name: str, the name of the movie. :param theater_name: str, the name of the theater. :param seat_number: str, the seat number. :param customer_name: str, the name of the customer. :return: None """ self.cursor.execute(''' INSERT INTO tickets (movie_name, theater_name, seat_number, customer_name) VALUES (?, ?, ?, ?) ''', (movie_name, theater_name, seat_number, customer_name)) self.connection.commit() def search_tickets_by_customer(self, customer_name): """ Searches for tickets in the "tickets" table by customer name. :param customer_name: str, the name of the customer to search for. :return: list of tuples, the rows from the "tickets" table that match the search criteria. >>> ticket_db = MovieTicketDB("ticket_database.db") >>> ticket_db.create_table() >>> ticket_db.insert_ticket("Movie A", "Theater 1", "A1", "John Doe") >>> result = ticket_db.search_tickets_by_customer("John Doe") len(result) = 1 """ self.cursor.execute(''' SELECT * FROM tickets WHERE customer_name = ? ''', (customer_name,)) tickets = self.cursor.fetchall() return tickets def delete_ticket(self, ticket_id): """ Deletes a ticket from the "tickets" table by ticket ID. :param ticket_id: int, the ID of the ticket to delete. :return: None """ self.cursor.execute(''' DELETE FROM tickets WHERE id = ? ''', (ticket_id,)) self.connection.commit()
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): """ Initializes the MovieTicketDB object with the specified database name. :param db_name: str, the name of the SQLite database. """ self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() self.create_table() def insert_ticket(self, movie_name, theater_name, seat_number, customer_name): """ Inserts a new ticket into the "tickets" table. :param movie_name: str, the name of the movie. :param theater_name: str, the name of the theater. :param seat_number: str, the seat number. :param customer_name: str, the name of the customer. :return: None """ def search_tickets_by_customer(self, customer_name): """ Searches for tickets in the "tickets" table by customer name. :param customer_name: str, the name of the customer to search for. :return: list of tuples, the rows from the "tickets" table that match the search criteria. >>> ticket_db = MovieTicketDB("ticket_database.db") >>> ticket_db.create_table() >>> ticket_db.insert_ticket("Movie A", "Theater 1", "A1", "John Doe") >>> result = ticket_db.search_tickets_by_customer("John Doe") len(result) = 1 """ def delete_ticket(self, ticket_id): """ Deletes a ticket from the "tickets" table by ticket ID. :param ticket_id: int, the ID of the ticket to delete. :return: None """
def create_table(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS tickets ( id INTEGER PRIMARY KEY, movie_name TEXT, theater_name TEXT, seat_number TEXT, customer_name TEXT ) ''') self.connection.commit()
Creates a "tickets" table in the database if it does not exist already.Fields include ID of type int, movie name of type str, theater name of type str, seat number of type str, and customer name of type str
ClassEval_60_sum
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() self.create_table() def create_table(self): """ Creates a "tickets" table in the database if it does not exist already.Fields include ID of type int, movie name of type str, theater name of type str, seat number of type str, and customer name of type str :return: None """ self.cursor.execute(''' CREATE TABLE IF NOT EXISTS tickets ( id INTEGER PRIMARY KEY, movie_name TEXT, theater_name TEXT, seat_number TEXT, customer_name TEXT ) ''') self.connection.commit() def search_tickets_by_customer(self, customer_name): """ Searches for tickets in the "tickets" table by customer name. :param customer_name: str, the name of the customer to search for. :return: list of tuples, the rows from the "tickets" table that match the search criteria. >>> ticket_db = MovieTicketDB("ticket_database.db") >>> ticket_db.create_table() >>> ticket_db.insert_ticket("Movie A", "Theater 1", "A1", "John Doe") >>> result = ticket_db.search_tickets_by_customer("John Doe") len(result) = 1 """ self.cursor.execute(''' SELECT * FROM tickets WHERE customer_name = ? ''', (customer_name,)) tickets = self.cursor.fetchall() return tickets def delete_ticket(self, ticket_id): """ Deletes a ticket from the "tickets" table by ticket ID. :param ticket_id: int, the ID of the ticket to delete. :return: None """ self.cursor.execute(''' DELETE FROM tickets WHERE id = ? ''', (ticket_id,)) self.connection.commit()
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): """ Initializes the MovieTicketDB object with the specified database name. :param db_name: str, the name of the SQLite database. """ self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() self.create_table() def create_table(self): """ Creates a "tickets" table in the database if it does not exist already.Fields include ID of type int, movie name of type str, theater name of type str, seat number of type str, and customer name of type str :return: None """ def search_tickets_by_customer(self, customer_name): """ Searches for tickets in the "tickets" table by customer name. :param customer_name: str, the name of the customer to search for. :return: list of tuples, the rows from the "tickets" table that match the search criteria. >>> ticket_db = MovieTicketDB("ticket_database.db") >>> ticket_db.create_table() >>> ticket_db.insert_ticket("Movie A", "Theater 1", "A1", "John Doe") >>> result = ticket_db.search_tickets_by_customer("John Doe") len(result) = 1 """ def delete_ticket(self, ticket_id): """ Deletes a ticket from the "tickets" table by ticket ID. :param ticket_id: int, the ID of the ticket to delete. :return: None """
def insert_ticket(self, movie_name, theater_name, seat_number, customer_name): self.cursor.execute(''' INSERT INTO tickets (movie_name, theater_name, seat_number, customer_name) VALUES (?, ?, ?, ?) ''', (movie_name, theater_name, seat_number, customer_name)) self.connection.commit()
Inserts a new ticket into the "tickets" table.
ClassEval_60_sum
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() self.create_table() def create_table(self): """ Creates a "tickets" table in the database if it does not exist already.Fields include ID of type int, movie name of type str, theater name of type str, seat number of type str, and customer name of type str :return: None """ self.cursor.execute(''' CREATE TABLE IF NOT EXISTS tickets ( id INTEGER PRIMARY KEY, movie_name TEXT, theater_name TEXT, seat_number TEXT, customer_name TEXT ) ''') self.connection.commit() def insert_ticket(self, movie_name, theater_name, seat_number, customer_name): """ Inserts a new ticket into the "tickets" table. :param movie_name: str, the name of the movie. :param theater_name: str, the name of the theater. :param seat_number: str, the seat number. :param customer_name: str, the name of the customer. :return: None """ self.cursor.execute(''' INSERT INTO tickets (movie_name, theater_name, seat_number, customer_name) VALUES (?, ?, ?, ?) ''', (movie_name, theater_name, seat_number, customer_name)) self.connection.commit() def delete_ticket(self, ticket_id): """ Deletes a ticket from the "tickets" table by ticket ID. :param ticket_id: int, the ID of the ticket to delete. :return: None """ self.cursor.execute(''' DELETE FROM tickets WHERE id = ? ''', (ticket_id,)) self.connection.commit()
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): """ Initializes the MovieTicketDB object with the specified database name. :param db_name: str, the name of the SQLite database. """ self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() self.create_table() def create_table(self): """ Creates a "tickets" table in the database if it does not exist already.Fields include ID of type int, movie name of type str, theater name of type str, seat number of type str, and customer name of type str :return: None """ def insert_ticket(self, movie_name, theater_name, seat_number, customer_name): """ Inserts a new ticket into the "tickets" table. :param movie_name: str, the name of the movie. :param theater_name: str, the name of the theater. :param seat_number: str, the seat number. :param customer_name: str, the name of the customer. :return: None """ def delete_ticket(self, ticket_id): """ Deletes a ticket from the "tickets" table by ticket ID. :param ticket_id: int, the ID of the ticket to delete. :return: None """
def search_tickets_by_customer(self, customer_name): self.cursor.execute(''' SELECT * FROM tickets WHERE customer_name = ? ''', (customer_name,)) tickets = self.cursor.fetchall() return tickets
Searches for tickets in the "tickets" table by customer name.
ClassEval_60_sum
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() self.create_table() def create_table(self): """ Creates a "tickets" table in the database if it does not exist already.Fields include ID of type int, movie name of type str, theater name of type str, seat number of type str, and customer name of type str :return: None """ self.cursor.execute(''' CREATE TABLE IF NOT EXISTS tickets ( id INTEGER PRIMARY KEY, movie_name TEXT, theater_name TEXT, seat_number TEXT, customer_name TEXT ) ''') self.connection.commit() def insert_ticket(self, movie_name, theater_name, seat_number, customer_name): """ Inserts a new ticket into the "tickets" table. :param movie_name: str, the name of the movie. :param theater_name: str, the name of the theater. :param seat_number: str, the seat number. :param customer_name: str, the name of the customer. :return: None """ self.cursor.execute(''' INSERT INTO tickets (movie_name, theater_name, seat_number, customer_name) VALUES (?, ?, ?, ?) ''', (movie_name, theater_name, seat_number, customer_name)) self.connection.commit() def search_tickets_by_customer(self, customer_name): """ Searches for tickets in the "tickets" table by customer name. :param customer_name: str, the name of the customer to search for. :return: list of tuples, the rows from the "tickets" table that match the search criteria. >>> ticket_db = MovieTicketDB("ticket_database.db") >>> ticket_db.create_table() >>> ticket_db.insert_ticket("Movie A", "Theater 1", "A1", "John Doe") >>> result = ticket_db.search_tickets_by_customer("John Doe") len(result) = 1 """ self.cursor.execute(''' SELECT * FROM tickets WHERE customer_name = ? ''', (customer_name,)) tickets = self.cursor.fetchall() return tickets def delete_ticket(self, ticket_id): self.cursor.execute(''' DELETE FROM tickets WHERE id = ? ''', (ticket_id,)) self.connection.commit()
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): """ Initializes the MovieTicketDB object with the specified database name. :param db_name: str, the name of the SQLite database. """ self.connection = sqlite3.connect(db_name) self.cursor = self.connection.cursor() self.create_table() def create_table(self): """ Creates a "tickets" table in the database if it does not exist already.Fields include ID of type int, movie name of type str, theater name of type str, seat number of type str, and customer name of type str :return: None """ def insert_ticket(self, movie_name, theater_name, seat_number, customer_name): """ Inserts a new ticket into the "tickets" table. :param movie_name: str, the name of the movie. :param theater_name: str, the name of the theater. :param seat_number: str, the seat number. :param customer_name: str, the name of the customer. :return: None """ def search_tickets_by_customer(self, customer_name): """ Searches for tickets in the "tickets" table by customer name. :param customer_name: str, the name of the customer to search for. :return: list of tuples, the rows from the "tickets" table that match the search criteria. >>> ticket_db = MovieTicketDB("ticket_database.db") >>> ticket_db.create_table() >>> ticket_db.insert_ticket("Movie A", "Theater 1", "A1", "John Doe") >>> result = ticket_db.search_tickets_by_customer("John Doe") len(result) = 1 """ def delete_ticket(self, ticket_id): """ Deletes a ticket from the "tickets" table by ticket ID. :param ticket_id: int, the ID of the ticket to delete. :return: None """
def delete_ticket(self, ticket_id): self.cursor.execute(''' DELETE FROM tickets WHERE id = ? ''', (ticket_id,)) self.connection.commit()
Deletes a ticket from the "tickets" table by ticket ID.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ if song in self.playlist: self.playlist.remove(song) if self.current_song == song: self.stop() def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ if self.playlist and self.current_song: return self.playlist[0] elif len(self.playlist): return False def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ if self.current_song: self.current_song = None return True else: return False def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index < len(self.playlist) - 1: self.current_song = self.playlist[current_index + 1] return True else: return False else: return False def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index > 0: self.current_song = self.playlist[current_index - 1] return True else: return False else: return False def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ if 0 <= volume <= 100: self.volume = volume else: return False def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """ if self.playlist: import random random.shuffle(self.playlist) return True else: return False
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default volume of 50. """ self.playlist = [] self.current_song = None self.volume = 50 def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """
def add_song(self, song): self.playlist.append(song)
Adds a song to the playlist.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ self.playlist.append(song) def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ if self.playlist and self.current_song: return self.playlist[0] elif len(self.playlist): return False def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ if self.current_song: self.current_song = None return True else: return False def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index < len(self.playlist) - 1: self.current_song = self.playlist[current_index + 1] return True else: return False else: return False def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index > 0: self.current_song = self.playlist[current_index - 1] return True else: return False else: return False def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ if 0 <= volume <= 100: self.volume = volume else: return False def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """ if self.playlist: import random random.shuffle(self.playlist) return True else: return False
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default volume of 50. """ self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """
def remove_song(self, song): if song in self.playlist: self.playlist.remove(song) if self.current_song == song: self.stop()
Removes a song from the playlist.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ self.playlist.append(song) def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ if song in self.playlist: self.playlist.remove(song) if self.current_song == song: self.stop() def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ if self.current_song: self.current_song = None return True else: return False def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index < len(self.playlist) - 1: self.current_song = self.playlist[current_index + 1] return True else: return False else: return False def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index > 0: self.current_song = self.playlist[current_index - 1] return True else: return False else: return False def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ if 0 <= volume <= 100: self.volume = volume else: return False def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """ if self.playlist: import random random.shuffle(self.playlist) return True else: return False
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default volume of 50. """ self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """
def play(self): if self.playlist and self.current_song: return self.playlist[0] elif len(self.playlist): return False
Plays the current song in the playlist.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ self.playlist.append(song) def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ if song in self.playlist: self.playlist.remove(song) if self.current_song == song: self.stop() def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ if self.playlist and self.current_song: return self.playlist[0] elif len(self.playlist): return False def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index < len(self.playlist) - 1: self.current_song = self.playlist[current_index + 1] return True else: return False else: return False def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index > 0: self.current_song = self.playlist[current_index - 1] return True else: return False else: return False def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ if 0 <= volume <= 100: self.volume = volume else: return False def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """ if self.playlist: import random random.shuffle(self.playlist) return True else: return False
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default volume of 50. """ self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """
def stop(self): if self.current_song: self.current_song = None return True else: return False
Stops the current song in the playlist.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ self.playlist.append(song) def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ if song in self.playlist: self.playlist.remove(song) if self.current_song == song: self.stop() def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ if self.playlist and self.current_song: return self.playlist[0] elif len(self.playlist): return False def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ if self.current_song: self.current_song = None return True else: return False def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index > 0: self.current_song = self.playlist[current_index - 1] return True else: return False else: return False def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ if 0 <= volume <= 100: self.volume = volume else: return False def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """ if self.playlist: import random random.shuffle(self.playlist) return True else: return False
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default volume of 50. """ self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """
def switch_song(self): if self.current_song: current_index = self.playlist.index(self.current_song) if current_index < len(self.playlist) - 1: self.current_song = self.playlist[current_index + 1] return True else: return False else: return False
Switches to the next song in the playlist.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ self.playlist.append(song) def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ if song in self.playlist: self.playlist.remove(song) if self.current_song == song: self.stop() def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ if self.playlist and self.current_song: return self.playlist[0] elif len(self.playlist): return False def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ if self.current_song: self.current_song = None return True else: return False def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index < len(self.playlist) - 1: self.current_song = self.playlist[current_index + 1] return True else: return False else: return False def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ if 0 <= volume <= 100: self.volume = volume else: return False def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """ if self.playlist: import random random.shuffle(self.playlist) return True else: return False
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default volume of 50. """ self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """
def previous_song(self): if self.current_song: current_index = self.playlist.index(self.current_song) if current_index > 0: self.current_song = self.playlist[current_index - 1] return True else: return False else: return False
Switches to the previous song in the playlist.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ self.playlist.append(song) def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ if song in self.playlist: self.playlist.remove(song) if self.current_song == song: self.stop() def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ if self.playlist and self.current_song: return self.playlist[0] elif len(self.playlist): return False def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ if self.current_song: self.current_song = None return True else: return False def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index < len(self.playlist) - 1: self.current_song = self.playlist[current_index + 1] return True else: return False else: return False def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index > 0: self.current_song = self.playlist[current_index - 1] return True else: return False else: return False def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """ if self.playlist: import random random.shuffle(self.playlist) return True else: return False
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default volume of 50. """ self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """
def set_volume(self, volume): if 0 <= volume <= 100: self.volume = volume else: return False
Sets the volume of the music player,ifthe volume is between 0 and 100 is valid.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ self.playlist.append(song) def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ if song in self.playlist: self.playlist.remove(song) if self.current_song == song: self.stop() def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ if self.playlist and self.current_song: return self.playlist[0] elif len(self.playlist): return False def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ if self.current_song: self.current_song = None return True else: return False def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index < len(self.playlist) - 1: self.current_song = self.playlist[current_index + 1] return True else: return False else: return False def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ if self.current_song: current_index = self.playlist.index(self.current_song) if current_index > 0: self.current_song = self.playlist[current_index - 1] return True else: return False else: return False def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ if 0 <= volume <= 100: self.volume = volume else: return False def shuffle(self): if self.playlist: import random random.shuffle(self.playlist) return True else: return False
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default volume of 50. """ self.playlist = [] self.current_song = None self.volume = 50 def add_song(self, song): """ Adds a song to the playlist. :param song: The song to add to the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.add_song("song1") >>> musicPlayer.playlist ['song1'] """ def remove_song(self, song): """ Removes a song from the playlist. :param song: The song to remove from the playlist, str. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.remove_song("song1") >>> musicPlayer.playlist ['song2'] """ def play(self): """ Plays the current song in the playlist. :return: The current song in the playlist, or False if there is no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.play() 'song1' """ def stop(self): """ Stops the current song in the playlist. :return: True if the current song was stopped, False if there was no current song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.stop() True """ def switch_song(self): """ Switches to the next song in the playlist. :return: True if the next song was switched to, False if there was no next song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song1" >>> musicPlayer.switch_song() True """ def previous_song(self): """ Switches to the previous song in the playlist. :return: True if the previous song was switched to, False if there was no previous song. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.current_song = "song2" >>> musicPlayer.previous_song() True """ def set_volume(self, volume): """ Sets the volume of the music player,ifthe volume is between 0 and 100 is valid. :param volume: The volume to set the music player to,int. :return: True if the volume was set, False if the volume was invalid. >>> musicPlayer = MusicPlayer() >>> musicPlayer.set_volume(50) >>> musicPlayer.volume 50 """ def shuffle(self): """ Shuffles the playlist. :return: True if the playlist was shuffled, False if the playlist was empty. >>> musicPlayer = MusicPlayer() >>> musicPlayer.playlist = ["song1", "song2"] >>> musicPlayer.shuffle() True """
def shuffle(self): if self.playlist: import random random.shuffle(self.playlist) return True else: return False
Shuffles the playlist.
ClassEval_62_sum
class NLPDataProcessor: """ The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list. """ def remove_stop_words(self, string_list, stop_word_list): """ Remove all the stop words from the list of strings. :param string_list: a list of strings :param stop_word_list: a list of stop words :return: a list of words without stop words >>> NLPDataProcessor.process(['This is a test.']) [['This', 'is', 'test.']] """ answer = [] for string in string_list: string_split = string.split() for word in string_split: if word in stop_word_list: string_split.remove(word) answer.append(string_split) return answer def process(self, string_list): """ Construct a stop word list including 'a', 'an', 'the', and remove all the stop words from the list of strings. :param string_list: a list of strings :return: a list of words without stop words >>> NLPDataProcessor.process(['This is a test.']) [['This', 'is', 'test.']] """ stop_word_list = self.construct_stop_word_list() words_list = self.remove_stop_words(string_list, stop_word_list) return words_list
class NLPDataProcessor: """ The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list. """ def remove_stop_words(self, string_list, stop_word_list): """ Remove all the stop words from the list of strings. :param string_list: a list of strings :param stop_word_list: a list of stop words :return: a list of words without stop words >>> NLPDataProcessor.process(['This is a test.']) [['This', 'is', 'test.']] """ def process(self, string_list): """ Construct a stop word list including 'a', 'an', 'the', and remove all the stop words from the list of strings. :param string_list: a list of strings :return: a list of words without stop words >>> NLPDataProcessor.process(['This is a test.']) [['This', 'is', 'test.']] """
def construct_stop_word_list(self): stop_word_list = ['a', 'an', 'the'] return stop_word_list
Construct a stop word list including 'a', 'an', 'the'.
ClassEval_62_sum
class NLPDataProcessor: """ The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list. """ def construct_stop_word_list(self): """ Construct a stop word list including 'a', 'an', 'the'. :return: a list of stop words >>> NLPDataProcessor.construct_stop_word_list() ['a', 'an', 'the'] """ stop_word_list = ['a', 'an', 'the'] return stop_word_list def process(self, string_list): """ Construct a stop word list including 'a', 'an', 'the', and remove all the stop words from the list of strings. :param string_list: a list of strings :return: a list of words without stop words >>> NLPDataProcessor.process(['This is a test.']) [['This', 'is', 'test.']] """ stop_word_list = self.construct_stop_word_list() words_list = self.remove_stop_words(string_list, stop_word_list) return words_list
class NLPDataProcessor: """ The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list. """ def construct_stop_word_list(self): """ Construct a stop word list including 'a', 'an', 'the'. :return: a list of stop words >>> NLPDataProcessor.construct_stop_word_list() ['a', 'an', 'the'] """ def process(self, string_list): """ Construct a stop word list including 'a', 'an', 'the', and remove all the stop words from the list of strings. :param string_list: a list of strings :return: a list of words without stop words >>> NLPDataProcessor.process(['This is a test.']) [['This', 'is', 'test.']] """
def remove_stop_words(self, string_list, stop_word_list): answer = [] for string in string_list: string_split = string.split() for word in string_split: if word in stop_word_list: string_split.remove(word) answer.append(string_split) return answer
Remove all the stop words from the list of strings.
ClassEval_62_sum
class NLPDataProcessor: """ The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list. """ def construct_stop_word_list(self): """ Construct a stop word list including 'a', 'an', 'the'. :return: a list of stop words >>> NLPDataProcessor.construct_stop_word_list() ['a', 'an', 'the'] """ stop_word_list = ['a', 'an', 'the'] return stop_word_list def remove_stop_words(self, string_list, stop_word_list): """ Remove all the stop words from the list of strings. :param string_list: a list of strings :param stop_word_list: a list of stop words :return: a list of words without stop words >>> NLPDataProcessor.process(['This is a test.']) [['This', 'is', 'test.']] """ answer = [] for string in string_list: string_split = string.split() for word in string_split: if word in stop_word_list: string_split.remove(word) answer.append(string_split) return answer def process(self, string_list): stop_word_list = self.construct_stop_word_list() words_list = self.remove_stop_words(string_list, stop_word_list) return words_list
class NLPDataProcessor: """ The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list. """ def construct_stop_word_list(self): """ Construct a stop word list including 'a', 'an', 'the'. :return: a list of stop words >>> NLPDataProcessor.construct_stop_word_list() ['a', 'an', 'the'] """ def remove_stop_words(self, string_list, stop_word_list): """ Remove all the stop words from the list of strings. :param string_list: a list of strings :param stop_word_list: a list of stop words :return: a list of words without stop words >>> NLPDataProcessor.process(['This is a test.']) [['This', 'is', 'test.']] """ def process(self, string_list): """ Construct a stop word list including 'a', 'an', 'the', and remove all the stop words from the list of strings. :param string_list: a list of strings :return: a list of words without stop words >>> NLPDataProcessor.process(['This is a test.']) [['This', 'is', 'test.']] """
def process(self, string_list): stop_word_list = self.construct_stop_word_list() words_list = self.remove_stop_words(string_list, stop_word_list) return words_list
Construct a stop word list including 'a', 'an', 'the', and remove all the stop words from the list of strings.
ClassEval_63_sum
from collections import Counter import re class NLPDataProcessor2: """ The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words. """ def calculate_word_frequency(self, words_list): """ Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order. :param words_list: a list of words lists :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency >>> NLPDataProcessor.calculate_word_frequency([['this', 'is', 'a', 'test'], ['this', 'is', 'another', 'test']]) {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1} """ word_frequency = Counter() for words in words_list: word_frequency.update(words) sorted_word_frequency = dict(sorted(word_frequency.items(), key=lambda x: x[1], reverse=True)) top_5_word_frequency = dict(list(sorted_word_frequency.items())[:5]) return top_5_word_frequency def process(self, string_list): """ keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order. :param string_list: a list of strings :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency >>> NLPDataProcessor.process(['This is a test.', 'This is another test.']) {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1} """ words_list = self.process_data(string_list) word_frequency_dict = self.calculate_word_frequency(words_list) return word_frequency_dict
import re from collections import Counter class NLPDataProcessor2: """ The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words. """ def calculate_word_frequency(self, words_list): """ Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order. :param words_list: a list of words lists :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency >>> NLPDataProcessor.calculate_word_frequency([['this', 'is', 'a', 'test'], ['this', 'is', 'another', 'test']]) {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1} """ def process(self, string_list): """ keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order. :param string_list: a list of strings :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency >>> NLPDataProcessor.process(['This is a test.', 'This is another test.']) {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1} """
def process_data(self, string_list): words_list = [] for string in string_list: # Remove non-English letters and convert to lowercase processed_string = re.sub(r'[^a-zA-Z\s]', '', string.lower()) # Split the string into words words = processed_string.split() words_list.append(words) return words_list
keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words.
ClassEval_63_sum
from collections import Counter import re class NLPDataProcessor2: """ The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words. """ def process_data(self, string_list): """ keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. :param string_list: a list of strings :return: words_list: a list of words lists >>> NLPDataProcessor.process_data(['This is a test.']) [['this', 'is', 'a', 'test']] """ words_list = [] for string in string_list: # Remove non-English letters and convert to lowercase processed_string = re.sub(r'[^a-zA-Z\s]', '', string.lower()) # Split the string into words words = processed_string.split() words_list.append(words) return words_list def process(self, string_list): """ keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order. :param string_list: a list of strings :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency >>> NLPDataProcessor.process(['This is a test.', 'This is another test.']) {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1} """ words_list = self.process_data(string_list) word_frequency_dict = self.calculate_word_frequency(words_list) return word_frequency_dict
import re from collections import Counter class NLPDataProcessor2: """ The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words. """ def process_data(self, string_list): """ keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. :param string_list: a list of strings :return: words_list: a list of words lists >>> NLPDataProcessor.process_data(['This is a test.']) [['this', 'is', 'a', 'test']] """ def process(self, string_list): """ keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order. :param string_list: a list of strings :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency >>> NLPDataProcessor.process(['This is a test.', 'This is another test.']) {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1} """
def calculate_word_frequency(self, words_list): word_frequency = Counter() for words in words_list: word_frequency.update(words) sorted_word_frequency = dict(sorted(word_frequency.items(), key=lambda x: x[1], reverse=True)) top_5_word_frequency = dict(list(sorted_word_frequency.items())[:5]) return top_5_word_frequency
Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order.
ClassEval_63_sum
from collections import Counter import re class NLPDataProcessor2: """ The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words. """ def process_data(self, string_list): """ keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. :param string_list: a list of strings :return: words_list: a list of words lists >>> NLPDataProcessor.process_data(['This is a test.']) [['this', 'is', 'a', 'test']] """ words_list = [] for string in string_list: # Remove non-English letters and convert to lowercase processed_string = re.sub(r'[^a-zA-Z\s]', '', string.lower()) # Split the string into words words = processed_string.split() words_list.append(words) return words_list def calculate_word_frequency(self, words_list): """ Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order. :param words_list: a list of words lists :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency >>> NLPDataProcessor.calculate_word_frequency([['this', 'is', 'a', 'test'], ['this', 'is', 'another', 'test']]) {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1} """ word_frequency = Counter() for words in words_list: word_frequency.update(words) sorted_word_frequency = dict(sorted(word_frequency.items(), key=lambda x: x[1], reverse=True)) top_5_word_frequency = dict(list(sorted_word_frequency.items())[:5]) return top_5_word_frequency def process(self, string_list): words_list = self.process_data(string_list) word_frequency_dict = self.calculate_word_frequency(words_list) return word_frequency_dict
import re from collections import Counter class NLPDataProcessor2: """ The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words. """ def process_data(self, string_list): """ keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. :param string_list: a list of strings :return: words_list: a list of words lists >>> NLPDataProcessor.process_data(['This is a test.']) [['this', 'is', 'a', 'test']] """ def calculate_word_frequency(self, words_list): """ Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order. :param words_list: a list of words lists :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency >>> NLPDataProcessor.calculate_word_frequency([['this', 'is', 'a', 'test'], ['this', 'is', 'another', 'test']]) {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1} """ def process(self, string_list): """ keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order. :param string_list: a list of strings :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency >>> NLPDataProcessor.process(['This is a test.', 'This is another test.']) {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1} """
def process(self, string_list): words_list = self.process_data(string_list) word_frequency_dict = self.calculate_word_frequency(words_list) return word_frequency_dict
keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order.
ClassEval_64_sum
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod @staticmethod def binary_to_decimal(binary_num): """ Convert a number from binary format to decimal format. :param binary_num: str, binary number :return: int, the decimal representation of binary number str. >>> NumberConverter.binary_to_decimal('1010010110110111') 42423 """ decimal_num = int(binary_num, 2) return decimal_num @staticmethod def decimal_to_octal(decimal_num): """ Convert a number from decimal format to octal format. :param decimal_num: int, decimal number :return: str, the octal representation of an integer. >>> NumberConverter.decimal_to_octal(42423) '122667' """ octal_num = oct(decimal_num)[2:] return octal_num @staticmethod def octal_to_decimal(octal_num): """ Convert a number from octal format to decimal format. :param octal_num: str, octal num :return: int, the decimal representation of octal number str. >>> NumberConverter.octal_to_decimal('122667') 42423 """ decimal_num = int(octal_num, 8) return decimal_num @staticmethod def decimal_to_hex(decimal_num): """ Convert a number from decimal format to hex format. :param decimal_num: int, decimal number :return hex_num: str, the hex representation of an integer. >>> NumberConverter.decimal_to_hex(42423) 'a5b7' """ hex_num = hex(decimal_num)[2:] return hex_num @staticmethod def hex_to_decimal(hex_num): """ Convert a number from hex format to decimal format. :param hex_num: str, hex num :return: int, the decimal representation of hex number str. >>> NumberConverter.hex_to_decimal('a5b7') 42423 """ decimal_num = int(hex_num, 16) return decimal_num
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod @staticmethod def binary_to_decimal(binary_num): """ Convert a number from binary format to decimal format. :param binary_num: str, binary number :return: int, the decimal representation of binary number str. >>> NumberConverter.binary_to_decimal('1010010110110111') 42423 """ @staticmethod def decimal_to_octal(decimal_num): """ Convert a number from decimal format to octal format. :param decimal_num: int, decimal number :return: str, the octal representation of an integer. >>> NumberConverter.decimal_to_octal(42423) '122667' """ @staticmethod def octal_to_decimal(octal_num): """ Convert a number from octal format to decimal format. :param octal_num: str, octal num :return: int, the decimal representation of octal number str. >>> NumberConverter.octal_to_decimal('122667') 42423 """ @staticmethod def decimal_to_hex(decimal_num): """ Convert a number from decimal format to hex format. :param decimal_num: int, decimal number :return hex_num: str, the hex representation of an integer. >>> NumberConverter.decimal_to_hex(42423) 'a5b7' """ @staticmethod def hex_to_decimal(hex_num): """ Convert a number from hex format to decimal format. :param hex_num: str, hex num :return: int, the decimal representation of hex number str. >>> NumberConverter.hex_to_decimal('a5b7') 42423 """
def decimal_to_binary(decimal_num): binary_num = bin(decimal_num)[2:] return binary_num
Convert a number from decimal format to binary format.
ClassEval_64_sum
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number :return: str, the binary representation of an integer. >>> NumberConverter.decimal_to_binary(42423) '1010010110110111' """ binary_num = bin(decimal_num)[2:] return binary_num @staticmethod def decimal_to_octal(decimal_num): """ Convert a number from decimal format to octal format. :param decimal_num: int, decimal number :return: str, the octal representation of an integer. >>> NumberConverter.decimal_to_octal(42423) '122667' """ octal_num = oct(decimal_num)[2:] return octal_num @staticmethod def octal_to_decimal(octal_num): """ Convert a number from octal format to decimal format. :param octal_num: str, octal num :return: int, the decimal representation of octal number str. >>> NumberConverter.octal_to_decimal('122667') 42423 """ decimal_num = int(octal_num, 8) return decimal_num @staticmethod def decimal_to_hex(decimal_num): """ Convert a number from decimal format to hex format. :param decimal_num: int, decimal number :return hex_num: str, the hex representation of an integer. >>> NumberConverter.decimal_to_hex(42423) 'a5b7' """ hex_num = hex(decimal_num)[2:] return hex_num @staticmethod def hex_to_decimal(hex_num): """ Convert a number from hex format to decimal format. :param hex_num: str, hex num :return: int, the decimal representation of hex number str. >>> NumberConverter.hex_to_decimal('a5b7') 42423 """ decimal_num = int(hex_num, 16) return decimal_num
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number :return: str, the binary representation of an integer. >>> NumberConverter.decimal_to_binary(42423) '1010010110110111' """ @staticmethod def decimal_to_octal(decimal_num): """ Convert a number from decimal format to octal format. :param decimal_num: int, decimal number :return: str, the octal representation of an integer. >>> NumberConverter.decimal_to_octal(42423) '122667' """ @staticmethod def octal_to_decimal(octal_num): """ Convert a number from octal format to decimal format. :param octal_num: str, octal num :return: int, the decimal representation of octal number str. >>> NumberConverter.octal_to_decimal('122667') 42423 """ @staticmethod def decimal_to_hex(decimal_num): """ Convert a number from decimal format to hex format. :param decimal_num: int, decimal number :return hex_num: str, the hex representation of an integer. >>> NumberConverter.decimal_to_hex(42423) 'a5b7' """ @staticmethod def hex_to_decimal(hex_num): """ Convert a number from hex format to decimal format. :param hex_num: str, hex num :return: int, the decimal representation of hex number str. >>> NumberConverter.hex_to_decimal('a5b7') 42423 """
@staticmethod def binary_to_decimal(binary_num): decimal_num = int(binary_num, 2) return decimal_num
Convert a number from binary format to decimal format.
ClassEval_64_sum
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number :return: str, the binary representation of an integer. >>> NumberConverter.decimal_to_binary(42423) '1010010110110111' """ binary_num = bin(decimal_num)[2:] return binary_num @staticmethod def binary_to_decimal(binary_num): """ Convert a number from binary format to decimal format. :param binary_num: str, binary number :return: int, the decimal representation of binary number str. >>> NumberConverter.binary_to_decimal('1010010110110111') 42423 """ decimal_num = int(binary_num, 2) return decimal_num @staticmethod def octal_to_decimal(octal_num): """ Convert a number from octal format to decimal format. :param octal_num: str, octal num :return: int, the decimal representation of octal number str. >>> NumberConverter.octal_to_decimal('122667') 42423 """ decimal_num = int(octal_num, 8) return decimal_num @staticmethod def decimal_to_hex(decimal_num): """ Convert a number from decimal format to hex format. :param decimal_num: int, decimal number :return hex_num: str, the hex representation of an integer. >>> NumberConverter.decimal_to_hex(42423) 'a5b7' """ hex_num = hex(decimal_num)[2:] return hex_num @staticmethod def hex_to_decimal(hex_num): """ Convert a number from hex format to decimal format. :param hex_num: str, hex num :return: int, the decimal representation of hex number str. >>> NumberConverter.hex_to_decimal('a5b7') 42423 """ decimal_num = int(hex_num, 16) return decimal_num
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number :return: str, the binary representation of an integer. >>> NumberConverter.decimal_to_binary(42423) '1010010110110111' """ @staticmethod def binary_to_decimal(binary_num): """ Convert a number from binary format to decimal format. :param binary_num: str, binary number :return: int, the decimal representation of binary number str. >>> NumberConverter.binary_to_decimal('1010010110110111') 42423 """ @staticmethod def octal_to_decimal(octal_num): """ Convert a number from octal format to decimal format. :param octal_num: str, octal num :return: int, the decimal representation of octal number str. >>> NumberConverter.octal_to_decimal('122667') 42423 """ @staticmethod def decimal_to_hex(decimal_num): """ Convert a number from decimal format to hex format. :param decimal_num: int, decimal number :return hex_num: str, the hex representation of an integer. >>> NumberConverter.decimal_to_hex(42423) 'a5b7' """ @staticmethod def hex_to_decimal(hex_num): """ Convert a number from hex format to decimal format. :param hex_num: str, hex num :return: int, the decimal representation of hex number str. >>> NumberConverter.hex_to_decimal('a5b7') 42423 """
@staticmethod def decimal_to_octal(decimal_num): octal_num = oct(decimal_num)[2:] return octal_num
Convert a number from decimal format to octal format.
ClassEval_64_sum
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number :return: str, the binary representation of an integer. >>> NumberConverter.decimal_to_binary(42423) '1010010110110111' """ binary_num = bin(decimal_num)[2:] return binary_num @staticmethod def binary_to_decimal(binary_num): """ Convert a number from binary format to decimal format. :param binary_num: str, binary number :return: int, the decimal representation of binary number str. >>> NumberConverter.binary_to_decimal('1010010110110111') 42423 """ decimal_num = int(binary_num, 2) return decimal_num @staticmethod def decimal_to_octal(decimal_num): """ Convert a number from decimal format to octal format. :param decimal_num: int, decimal number :return: str, the octal representation of an integer. >>> NumberConverter.decimal_to_octal(42423) '122667' """ octal_num = oct(decimal_num)[2:] return octal_num @staticmethod def decimal_to_hex(decimal_num): """ Convert a number from decimal format to hex format. :param decimal_num: int, decimal number :return hex_num: str, the hex representation of an integer. >>> NumberConverter.decimal_to_hex(42423) 'a5b7' """ hex_num = hex(decimal_num)[2:] return hex_num @staticmethod def hex_to_decimal(hex_num): """ Convert a number from hex format to decimal format. :param hex_num: str, hex num :return: int, the decimal representation of hex number str. >>> NumberConverter.hex_to_decimal('a5b7') 42423 """ decimal_num = int(hex_num, 16) return decimal_num
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number :return: str, the binary representation of an integer. >>> NumberConverter.decimal_to_binary(42423) '1010010110110111' """ @staticmethod def binary_to_decimal(binary_num): """ Convert a number from binary format to decimal format. :param binary_num: str, binary number :return: int, the decimal representation of binary number str. >>> NumberConverter.binary_to_decimal('1010010110110111') 42423 """ @staticmethod def decimal_to_octal(decimal_num): """ Convert a number from decimal format to octal format. :param decimal_num: int, decimal number :return: str, the octal representation of an integer. >>> NumberConverter.decimal_to_octal(42423) '122667' """ @staticmethod def decimal_to_hex(decimal_num): """ Convert a number from decimal format to hex format. :param decimal_num: int, decimal number :return hex_num: str, the hex representation of an integer. >>> NumberConverter.decimal_to_hex(42423) 'a5b7' """ @staticmethod def hex_to_decimal(hex_num): """ Convert a number from hex format to decimal format. :param hex_num: str, hex num :return: int, the decimal representation of hex number str. >>> NumberConverter.hex_to_decimal('a5b7') 42423 """
@staticmethod def octal_to_decimal(octal_num): decimal_num = int(octal_num, 8) return decimal_num
Convert a number from octal format to decimal format.
ClassEval_64_sum
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number :return: str, the binary representation of an integer. >>> NumberConverter.decimal_to_binary(42423) '1010010110110111' """ binary_num = bin(decimal_num)[2:] return binary_num @staticmethod def binary_to_decimal(binary_num): """ Convert a number from binary format to decimal format. :param binary_num: str, binary number :return: int, the decimal representation of binary number str. >>> NumberConverter.binary_to_decimal('1010010110110111') 42423 """ decimal_num = int(binary_num, 2) return decimal_num @staticmethod def decimal_to_octal(decimal_num): """ Convert a number from decimal format to octal format. :param decimal_num: int, decimal number :return: str, the octal representation of an integer. >>> NumberConverter.decimal_to_octal(42423) '122667' """ octal_num = oct(decimal_num)[2:] return octal_num @staticmethod def octal_to_decimal(octal_num): """ Convert a number from octal format to decimal format. :param octal_num: str, octal num :return: int, the decimal representation of octal number str. >>> NumberConverter.octal_to_decimal('122667') 42423 """ decimal_num = int(octal_num, 8) return decimal_num @staticmethod def hex_to_decimal(hex_num): """ Convert a number from hex format to decimal format. :param hex_num: str, hex num :return: int, the decimal representation of hex number str. >>> NumberConverter.hex_to_decimal('a5b7') 42423 """ decimal_num = int(hex_num, 16) return decimal_num
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number :return: str, the binary representation of an integer. >>> NumberConverter.decimal_to_binary(42423) '1010010110110111' """ @staticmethod def binary_to_decimal(binary_num): """ Convert a number from binary format to decimal format. :param binary_num: str, binary number :return: int, the decimal representation of binary number str. >>> NumberConverter.binary_to_decimal('1010010110110111') 42423 """ @staticmethod def decimal_to_octal(decimal_num): """ Convert a number from decimal format to octal format. :param decimal_num: int, decimal number :return: str, the octal representation of an integer. >>> NumberConverter.decimal_to_octal(42423) '122667' """ @staticmethod def octal_to_decimal(octal_num): """ Convert a number from octal format to decimal format. :param octal_num: str, octal num :return: int, the decimal representation of octal number str. >>> NumberConverter.octal_to_decimal('122667') 42423 """ @staticmethod def hex_to_decimal(hex_num): """ Convert a number from hex format to decimal format. :param hex_num: str, hex num :return: int, the decimal representation of hex number str. >>> NumberConverter.hex_to_decimal('a5b7') 42423 """
@staticmethod def decimal_to_hex(decimal_num): hex_num = hex(decimal_num)[2:] return hex_num
Convert a number from decimal format to hex format.
ClassEval_64_sum
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number :return: str, the binary representation of an integer. >>> NumberConverter.decimal_to_binary(42423) '1010010110110111' """ binary_num = bin(decimal_num)[2:] return binary_num @staticmethod def binary_to_decimal(binary_num): """ Convert a number from binary format to decimal format. :param binary_num: str, binary number :return: int, the decimal representation of binary number str. >>> NumberConverter.binary_to_decimal('1010010110110111') 42423 """ decimal_num = int(binary_num, 2) return decimal_num @staticmethod def decimal_to_octal(decimal_num): """ Convert a number from decimal format to octal format. :param decimal_num: int, decimal number :return: str, the octal representation of an integer. >>> NumberConverter.decimal_to_octal(42423) '122667' """ octal_num = oct(decimal_num)[2:] return octal_num @staticmethod def octal_to_decimal(octal_num): """ Convert a number from octal format to decimal format. :param octal_num: str, octal num :return: int, the decimal representation of octal number str. >>> NumberConverter.octal_to_decimal('122667') 42423 """ decimal_num = int(octal_num, 8) return decimal_num @staticmethod def decimal_to_hex(decimal_num): """ Convert a number from decimal format to hex format. :param decimal_num: int, decimal number :return hex_num: str, the hex representation of an integer. >>> NumberConverter.decimal_to_hex(42423) 'a5b7' """ hex_num = hex(decimal_num)[2:] return hex_num @staticmethod def hex_to_decimal(hex_num): decimal_num = int(hex_num, 16) return decimal_num
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number :return: str, the binary representation of an integer. >>> NumberConverter.decimal_to_binary(42423) '1010010110110111' """ @staticmethod def binary_to_decimal(binary_num): """ Convert a number from binary format to decimal format. :param binary_num: str, binary number :return: int, the decimal representation of binary number str. >>> NumberConverter.binary_to_decimal('1010010110110111') 42423 """ @staticmethod def decimal_to_octal(decimal_num): """ Convert a number from decimal format to octal format. :param decimal_num: int, decimal number :return: str, the octal representation of an integer. >>> NumberConverter.decimal_to_octal(42423) '122667' """ @staticmethod def octal_to_decimal(octal_num): """ Convert a number from octal format to decimal format. :param octal_num: str, octal num :return: int, the decimal representation of octal number str. >>> NumberConverter.octal_to_decimal('122667') 42423 """ @staticmethod def decimal_to_hex(decimal_num): """ Convert a number from decimal format to hex format. :param decimal_num: int, decimal number :return hex_num: str, the hex representation of an integer. >>> NumberConverter.decimal_to_hex(42423) 'a5b7' """ @staticmethod def hex_to_decimal(hex_num): """ Convert a number from hex format to decimal format. :param hex_num: str, hex num :return: int, the decimal representation of hex number str. >>> NumberConverter.hex_to_decimal('a5b7') 42423 """
@staticmethod def hex_to_decimal(hex_num): decimal_num = int(hex_num, 16) return decimal_num
Convert a number from hex format to decimal format.
ClassEval_65_sum
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"] self.NUMBER_TEN = ["TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"] self.NUMBER_MORE = ["", "THOUSAND", "MILLION", "BILLION"] self.NUMBER_SUFFIX = ["k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"] def format_string(self, x): """ Converts a string representation of a number into words format :param x: str, the string representation of a number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format_string("123456") "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ lstr, rstr = (x.split('.') + [''])[:2] lstrrev = lstr[::-1] a = [''] * 5 if len(lstrrev) % 3 == 1: lstrrev += "00" elif len(lstrrev) % 3 == 2: lstrrev += "0" lm = "" for i in range(len(lstrrev) // 3): a[i] = lstrrev[3 * i:3 * i + 3][::-1] if a[i] != "000": lm = self.trans_three(a[i]) + " " + self.parse_more(i) + " " + lm else: lm += self.trans_three(a[i]) xs = f"AND CENTS {self.trans_two(rstr)} " if rstr else "" if not lm.strip(): return "ZERO ONLY" else: return f"{lm.strip()} {xs}ONLY" def trans_two(self, s): """ Converts a two-digit number into words format :param s: str, the two-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_two("23") "TWENTY THREE" """ s = s.zfill(2) if s[0] == "0": return self.NUMBER[int(s[-1])] elif s[0] == "1": return self.NUMBER_TEEN[int(s) - 10] elif s[1] == "0": return self.NUMBER_TEN[int(s[0]) - 1] else: return self.NUMBER_TEN[int(s[0]) - 1] + " " + self.NUMBER[int(s[-1])] def trans_three(self, s): """ Converts a three-digit number into words format :param s: str, the three-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_three("123") "ONE HUNDRED AND TWENTY THREE" """ if s[0] == "0": return self.trans_two(s[1:]) elif s[1:] == "00": return f"{self.NUMBER[int(s[0])]} HUNDRED" else: return f"{self.NUMBER[int(s[0])]} HUNDRED AND {self.trans_two(s[1:])}" def parse_more(self, i): """ Parses the thousand/million/billion suffix based on the index :param i: int, the index representing the magnitude (thousand, million, billion) :return: str, the corresponding suffix for the magnitude >>> formatter = NumberWordFormatter() >>> formatter.parse_more(1) "THOUSAND" """ return self.NUMBER_MORE[i]
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): """ Initialize NumberWordFormatter object. """ self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"] self.NUMBER_TEN = ["TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"] self.NUMBER_MORE = ["", "THOUSAND", "MILLION", "BILLION"] self.NUMBER_SUFFIX = ["k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"] def format_string(self, x): """ Converts a string representation of a number into words format :param x: str, the string representation of a number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format_string("123456") "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ def trans_two(self, s): """ Converts a two-digit number into words format :param s: str, the two-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_two("23") "TWENTY THREE" """ def trans_three(self, s): """ Converts a three-digit number into words format :param s: str, the three-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_three("123") "ONE HUNDRED AND TWENTY THREE" """ def parse_more(self, i): """ Parses the thousand/million/billion suffix based on the index :param i: int, the index representing the magnitude (thousand, million, billion) :return: str, the corresponding suffix for the magnitude >>> formatter = NumberWordFormatter() >>> formatter.parse_more(1) "THOUSAND" """
def format(self, x): if x is not None: return self.format_string(str(x)) else: return ""
Converts a number into words format
ClassEval_65_sum
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"] self.NUMBER_TEN = ["TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"] self.NUMBER_MORE = ["", "THOUSAND", "MILLION", "BILLION"] self.NUMBER_SUFFIX = ["k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"] def format(self, x): """ Converts a number into words format :param x: int or float, the number to be converted into words format :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format(123456) "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ if x is not None: return self.format_string(str(x)) else: return "" def trans_two(self, s): """ Converts a two-digit number into words format :param s: str, the two-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_two("23") "TWENTY THREE" """ s = s.zfill(2) if s[0] == "0": return self.NUMBER[int(s[-1])] elif s[0] == "1": return self.NUMBER_TEEN[int(s) - 10] elif s[1] == "0": return self.NUMBER_TEN[int(s[0]) - 1] else: return self.NUMBER_TEN[int(s[0]) - 1] + " " + self.NUMBER[int(s[-1])] def trans_three(self, s): """ Converts a three-digit number into words format :param s: str, the three-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_three("123") "ONE HUNDRED AND TWENTY THREE" """ if s[0] == "0": return self.trans_two(s[1:]) elif s[1:] == "00": return f"{self.NUMBER[int(s[0])]} HUNDRED" else: return f"{self.NUMBER[int(s[0])]} HUNDRED AND {self.trans_two(s[1:])}" def parse_more(self, i): """ Parses the thousand/million/billion suffix based on the index :param i: int, the index representing the magnitude (thousand, million, billion) :return: str, the corresponding suffix for the magnitude >>> formatter = NumberWordFormatter() >>> formatter.parse_more(1) "THOUSAND" """ return self.NUMBER_MORE[i]
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): """ Initialize NumberWordFormatter object. """ self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"] self.NUMBER_TEN = ["TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"] self.NUMBER_MORE = ["", "THOUSAND", "MILLION", "BILLION"] self.NUMBER_SUFFIX = ["k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"] def format(self, x): """ Converts a number into words format :param x: int or float, the number to be converted into words format :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format(123456) "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ def trans_two(self, s): """ Converts a two-digit number into words format :param s: str, the two-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_two("23") "TWENTY THREE" """ def trans_three(self, s): """ Converts a three-digit number into words format :param s: str, the three-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_three("123") "ONE HUNDRED AND TWENTY THREE" """ def parse_more(self, i): """ Parses the thousand/million/billion suffix based on the index :param i: int, the index representing the magnitude (thousand, million, billion) :return: str, the corresponding suffix for the magnitude >>> formatter = NumberWordFormatter() >>> formatter.parse_more(1) "THOUSAND" """
def format_string(self, x): lstr, rstr = (x.split('.') + [''])[:2] lstrrev = lstr[::-1] a = [''] * 5 if len(lstrrev) % 3 == 1: lstrrev += "00" elif len(lstrrev) % 3 == 2: lstrrev += "0" lm = "" for i in range(len(lstrrev) // 3): a[i] = lstrrev[3 * i:3 * i + 3][::-1] if a[i] != "000": lm = self.trans_three(a[i]) + " " + self.parse_more(i) + " " + lm else: lm += self.trans_three(a[i]) xs = f"AND CENTS {self.trans_two(rstr)} " if rstr else "" if not lm.strip(): return "ZERO ONLY" else: return f"{lm.strip()} {xs}ONLY"
Converts a string representation of a number into words format
ClassEval_65_sum
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"] self.NUMBER_TEN = ["TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"] self.NUMBER_MORE = ["", "THOUSAND", "MILLION", "BILLION"] self.NUMBER_SUFFIX = ["k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"] def format(self, x): """ Converts a number into words format :param x: int or float, the number to be converted into words format :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format(123456) "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ if x is not None: return self.format_string(str(x)) else: return "" def format_string(self, x): """ Converts a string representation of a number into words format :param x: str, the string representation of a number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format_string("123456") "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ lstr, rstr = (x.split('.') + [''])[:2] lstrrev = lstr[::-1] a = [''] * 5 if len(lstrrev) % 3 == 1: lstrrev += "00" elif len(lstrrev) % 3 == 2: lstrrev += "0" lm = "" for i in range(len(lstrrev) // 3): a[i] = lstrrev[3 * i:3 * i + 3][::-1] if a[i] != "000": lm = self.trans_three(a[i]) + " " + self.parse_more(i) + " " + lm else: lm += self.trans_three(a[i]) xs = f"AND CENTS {self.trans_two(rstr)} " if rstr else "" if not lm.strip(): return "ZERO ONLY" else: return f"{lm.strip()} {xs}ONLY" def trans_three(self, s): """ Converts a three-digit number into words format :param s: str, the three-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_three("123") "ONE HUNDRED AND TWENTY THREE" """ if s[0] == "0": return self.trans_two(s[1:]) elif s[1:] == "00": return f"{self.NUMBER[int(s[0])]} HUNDRED" else: return f"{self.NUMBER[int(s[0])]} HUNDRED AND {self.trans_two(s[1:])}" def parse_more(self, i): """ Parses the thousand/million/billion suffix based on the index :param i: int, the index representing the magnitude (thousand, million, billion) :return: str, the corresponding suffix for the magnitude >>> formatter = NumberWordFormatter() >>> formatter.parse_more(1) "THOUSAND" """ return self.NUMBER_MORE[i]
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): """ Initialize NumberWordFormatter object. """ self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"] self.NUMBER_TEN = ["TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"] self.NUMBER_MORE = ["", "THOUSAND", "MILLION", "BILLION"] self.NUMBER_SUFFIX = ["k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"] def format(self, x): """ Converts a number into words format :param x: int or float, the number to be converted into words format :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format(123456) "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ def format_string(self, x): """ Converts a string representation of a number into words format :param x: str, the string representation of a number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format_string("123456") "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ def trans_three(self, s): """ Converts a three-digit number into words format :param s: str, the three-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_three("123") "ONE HUNDRED AND TWENTY THREE" """ def parse_more(self, i): """ Parses the thousand/million/billion suffix based on the index :param i: int, the index representing the magnitude (thousand, million, billion) :return: str, the corresponding suffix for the magnitude >>> formatter = NumberWordFormatter() >>> formatter.parse_more(1) "THOUSAND" """
def trans_two(self, s): s = s.zfill(2) if s[0] == "0": return self.NUMBER[int(s[-1])] elif s[0] == "1": return self.NUMBER_TEEN[int(s) - 10] elif s[1] == "0": return self.NUMBER_TEN[int(s[0]) - 1] else: return self.NUMBER_TEN[int(s[0]) - 1] + " " + self.NUMBER[int(s[-1])]
Converts a two-digit number into words format
ClassEval_65_sum
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"] self.NUMBER_TEN = ["TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"] self.NUMBER_MORE = ["", "THOUSAND", "MILLION", "BILLION"] self.NUMBER_SUFFIX = ["k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"] def format(self, x): """ Converts a number into words format :param x: int or float, the number to be converted into words format :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format(123456) "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ if x is not None: return self.format_string(str(x)) else: return "" def format_string(self, x): """ Converts a string representation of a number into words format :param x: str, the string representation of a number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format_string("123456") "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ lstr, rstr = (x.split('.') + [''])[:2] lstrrev = lstr[::-1] a = [''] * 5 if len(lstrrev) % 3 == 1: lstrrev += "00" elif len(lstrrev) % 3 == 2: lstrrev += "0" lm = "" for i in range(len(lstrrev) // 3): a[i] = lstrrev[3 * i:3 * i + 3][::-1] if a[i] != "000": lm = self.trans_three(a[i]) + " " + self.parse_more(i) + " " + lm else: lm += self.trans_three(a[i]) xs = f"AND CENTS {self.trans_two(rstr)} " if rstr else "" if not lm.strip(): return "ZERO ONLY" else: return f"{lm.strip()} {xs}ONLY" def trans_two(self, s): """ Converts a two-digit number into words format :param s: str, the two-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_two("23") "TWENTY THREE" """ s = s.zfill(2) if s[0] == "0": return self.NUMBER[int(s[-1])] elif s[0] == "1": return self.NUMBER_TEEN[int(s) - 10] elif s[1] == "0": return self.NUMBER_TEN[int(s[0]) - 1] else: return self.NUMBER_TEN[int(s[0]) - 1] + " " + self.NUMBER[int(s[-1])] def parse_more(self, i): """ Parses the thousand/million/billion suffix based on the index :param i: int, the index representing the magnitude (thousand, million, billion) :return: str, the corresponding suffix for the magnitude >>> formatter = NumberWordFormatter() >>> formatter.parse_more(1) "THOUSAND" """ return self.NUMBER_MORE[i]
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): """ Initialize NumberWordFormatter object. """ self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"] self.NUMBER_TEN = ["TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"] self.NUMBER_MORE = ["", "THOUSAND", "MILLION", "BILLION"] self.NUMBER_SUFFIX = ["k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"] def format(self, x): """ Converts a number into words format :param x: int or float, the number to be converted into words format :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format(123456) "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ def format_string(self, x): """ Converts a string representation of a number into words format :param x: str, the string representation of a number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format_string("123456") "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ def trans_two(self, s): """ Converts a two-digit number into words format :param s: str, the two-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_two("23") "TWENTY THREE" """ def parse_more(self, i): """ Parses the thousand/million/billion suffix based on the index :param i: int, the index representing the magnitude (thousand, million, billion) :return: str, the corresponding suffix for the magnitude >>> formatter = NumberWordFormatter() >>> formatter.parse_more(1) "THOUSAND" """
def trans_three(self, s): if s[0] == "0": return self.trans_two(s[1:]) elif s[1:] == "00": return f"{self.NUMBER[int(s[0])]} HUNDRED" else: return f"{self.NUMBER[int(s[0])]} HUNDRED AND {self.trans_two(s[1:])}"
Converts a three-digit number into words format
ClassEval_65_sum
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"] self.NUMBER_TEN = ["TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"] self.NUMBER_MORE = ["", "THOUSAND", "MILLION", "BILLION"] self.NUMBER_SUFFIX = ["k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"] def format(self, x): """ Converts a number into words format :param x: int or float, the number to be converted into words format :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format(123456) "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ if x is not None: return self.format_string(str(x)) else: return "" def format_string(self, x): """ Converts a string representation of a number into words format :param x: str, the string representation of a number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format_string("123456") "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ lstr, rstr = (x.split('.') + [''])[:2] lstrrev = lstr[::-1] a = [''] * 5 if len(lstrrev) % 3 == 1: lstrrev += "00" elif len(lstrrev) % 3 == 2: lstrrev += "0" lm = "" for i in range(len(lstrrev) // 3): a[i] = lstrrev[3 * i:3 * i + 3][::-1] if a[i] != "000": lm = self.trans_three(a[i]) + " " + self.parse_more(i) + " " + lm else: lm += self.trans_three(a[i]) xs = f"AND CENTS {self.trans_two(rstr)} " if rstr else "" if not lm.strip(): return "ZERO ONLY" else: return f"{lm.strip()} {xs}ONLY" def trans_two(self, s): """ Converts a two-digit number into words format :param s: str, the two-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_two("23") "TWENTY THREE" """ s = s.zfill(2) if s[0] == "0": return self.NUMBER[int(s[-1])] elif s[0] == "1": return self.NUMBER_TEEN[int(s) - 10] elif s[1] == "0": return self.NUMBER_TEN[int(s[0]) - 1] else: return self.NUMBER_TEN[int(s[0]) - 1] + " " + self.NUMBER[int(s[-1])] def trans_three(self, s): """ Converts a three-digit number into words format :param s: str, the three-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_three("123") "ONE HUNDRED AND TWENTY THREE" """ if s[0] == "0": return self.trans_two(s[1:]) elif s[1:] == "00": return f"{self.NUMBER[int(s[0])]} HUNDRED" else: return f"{self.NUMBER[int(s[0])]} HUNDRED AND {self.trans_two(s[1:])}" def parse_more(self, i): return self.NUMBER_MORE[i]
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): """ Initialize NumberWordFormatter object. """ self.NUMBER = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] self.NUMBER_TEEN = ["TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"] self.NUMBER_TEN = ["TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"] self.NUMBER_MORE = ["", "THOUSAND", "MILLION", "BILLION"] self.NUMBER_SUFFIX = ["k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"] def format(self, x): """ Converts a number into words format :param x: int or float, the number to be converted into words format :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format(123456) "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ def format_string(self, x): """ Converts a string representation of a number into words format :param x: str, the string representation of a number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.format_string("123456") "ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY" """ def trans_two(self, s): """ Converts a two-digit number into words format :param s: str, the two-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_two("23") "TWENTY THREE" """ def trans_three(self, s): """ Converts a three-digit number into words format :param s: str, the three-digit number :return: str, the number in words format >>> formatter = NumberWordFormatter() >>> formatter.trans_three("123") "ONE HUNDRED AND TWENTY THREE" """ def parse_more(self, i): """ Parses the thousand/million/billion suffix based on the index :param i: int, the index representing the magnitude (thousand, million, billion) :return: str, the corresponding suffix for the magnitude >>> formatter = NumberWordFormatter() >>> formatter.parse_more(1) "THOUSAND" """
def parse_more(self, i): return self.NUMBER_MORE[i]
Parses the thousand/million/billion suffix based on the index
ClassEval_66_sum
class NumericEntityUnescaper: """ This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string. """ def __init__(self): pass @staticmethod def is_hex_char(char): """ Determines whether a given character is a hexadecimal digit. :param char: str, the character to check. :return: bool, True if the character is a hexadecimal digit, False otherwise. >>> NumericEntityUnescaper.is_hex_char('a') True """ return char.isdigit() or ('a' <= char.lower() <= 'f')
class NumericEntityUnescaper: """ This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string. """ def __init__(self): pass @staticmethod def is_hex_char(char): """ Determines whether a given character is a hexadecimal digit. :param char: str, the character to check. :return: bool, True if the character is a hexadecimal digit, False otherwise. >>> NumericEntityUnescaper.is_hex_char('a') True """
def replace(self, string): out = [] pos = 0 length = len(string) while pos < length - 2: if string[pos] == '&' and string[pos + 1] == '#': start = pos + 2 is_hex = False first_char = string[start] if first_char == 'x' or first_char == 'X': start += 1 is_hex = True if start == length: return ''.join(out) end = start while end < length and self.is_hex_char(string[end]): end += 1 if end < length and string[end] == ';': try: entity_value = int(string[start:end], 16 if is_hex else 10) except: return ''.join(out) out.append(chr(entity_value)) pos = end + 1 continue out.append(string[pos]) pos += 1 return ''.join(out)
Replaces numeric character references (HTML entities) in the input string with their corresponding Unicode characters.
ClassEval_66_sum
class NumericEntityUnescaper: """ This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string. """ def __init__(self): pass def replace(self, string): """ Replaces numeric character references (HTML entities) in the input string with their corresponding Unicode characters. :param string: str, the input string containing numeric character references. :return: str, the input string with numeric character references replaced with their corresponding Unicode characters. >>> unescaper = NumericEntityUnescaper() >>> unescaper.replace("&#65;&#66;&#67;") 'ABC' """ out = [] pos = 0 length = len(string) while pos < length - 2: if string[pos] == '&' and string[pos + 1] == '#': start = pos + 2 is_hex = False first_char = string[start] if first_char == 'x' or first_char == 'X': start += 1 is_hex = True if start == length: return ''.join(out) end = start while end < length and self.is_hex_char(string[end]): end += 1 if end < length and string[end] == ';': try: entity_value = int(string[start:end], 16 if is_hex else 10) except: return ''.join(out) out.append(chr(entity_value)) pos = end + 1 continue out.append(string[pos]) pos += 1 return ''.join(out) @staticmethod def is_hex_char(char): return char.isdigit() or ('a' <= char.lower() <= 'f')
class NumericEntityUnescaper: """ This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string. """ def __init__(self): pass def replace(self, string): """ Replaces numeric character references (HTML entities) in the input string with their corresponding Unicode characters. :param string: str, the input string containing numeric character references. :return: str, the input string with numeric character references replaced with their corresponding Unicode characters. >>> unescaper = NumericEntityUnescaper() >>> unescaper.replace("&#65;&#66;&#67;") 'ABC' """ @staticmethod def is_hex_char(char): """ Determines whether a given character is a hexadecimal digit. :param char: str, the character to check. :return: bool, True if the character is a hexadecimal digit, False otherwise. >>> NumericEntityUnescaper.is_hex_char('a') True """
@staticmethod def is_hex_char(char): return char.isdigit() or ('a' <= char.lower() <= 'f')
Determines whether a given character is a hexadecimal digit.
ClassEval_67_sum
class Order: """ The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout. """ def __init__(self): self.menu = [] # menu = [{"dish": dish name, "price": price, "count": count}, ...] self.selected_dishes = [] # selected_dish = {"dish": dish name, "count": count, price: price} self.sales = {} # def calculate_total(self): """ Calculate the total price of dishes that have been ordered. Multiply the count, price and sales. :return total: float, the final total price. >>> order = Order() >>> order.menu.append({"dish": "dish1", "price": 10, "count": 5}) >>> order.sales = {"dish1": 0.8} >>> order.add_dish({"dish": "dish1", "price": 10, "count": 4}) True >>> order.calculate_total() 32.0 """ total = 0 for dish in self.selected_dishes: total += dish["price"] * dish["count"] * self.sales[dish["dish"]] return total def checkout(self): """ Check out the dished ordered. IF the self.selected_dishes is not empty, invoke the calculate_total method to check out. :return Flase if the self.selected_dishes is empty, or total(return value of calculate_total) otherwise. >>> order = Order() >>> order.menu.append({"dish": "dish1", "price": 10, "count": 5}) >>> order.sales = {"dish1": 0.8} >>> order.add_dish({"dish": "dish1", "price": 10, "count": 4}) True >>> order.checkout() 32.0 """ if len(self.selected_dishes) == 0: return False total = self.calculate_total() self.selected_dishes = [] return total
class Order: """ The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout. """ def __init__(self): """ Initialize the order management system self.menu stores the dishes of resturant inventory menu = [{"dish": dish name, "price": price, "count": count}, ...] self.selected_dishes stores the dished selected by customer selected_dish = {"dish": dish name, "count": count, price: price} self.sales stores the sales of each dish sales = {dish name: sales} """ self.menu = [] self.selected_dishes = [] self.sales = {} def calculate_total(self): """ Calculate the total price of dishes that have been ordered. Multiply the count, price and sales. :return total: float, the final total price. >>> order = Order() >>> order.menu.append({"dish": "dish1", "price": 10, "count": 5}) >>> order.sales = {"dish1": 0.8} >>> order.add_dish({"dish": "dish1", "price": 10, "count": 4}) True >>> order.calculate_total() 32.0 """ def checkout(self): """ Check out the dished ordered. IF the self.selected_dishes is not empty, invoke the calculate_total method to check out. :return Flase if the self.selected_dishes is empty, or total(return value of calculate_total) otherwise. >>> order = Order() >>> order.menu.append({"dish": "dish1", "price": 10, "count": 5}) >>> order.sales = {"dish1": 0.8} >>> order.add_dish({"dish": "dish1", "price": 10, "count": 4}) True >>> order.checkout() 32.0 """
def add_dish(self, dish): for menu_dish in self.menu: if dish["dish"] == menu_dish["dish"]: if menu_dish["count"] < dish["count"]: return False else: menu_dish["count"] -= dish["count"] break self.selected_dishes.append(dish) return True
Check the self.menu and add into self.selected_dish if the dish count is valid. And if the dish has successfully been added, change the count in self.menu.
ClassEval_67_sum
class Order: """ The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout. """ def __init__(self): self.menu = [] # menu = [{"dish": dish name, "price": price, "count": count}, ...] self.selected_dishes = [] # selected_dish = {"dish": dish name, "count": count, price: price} self.sales = {} # def add_dish(self, dish): """ Check the self.menu and add into self.selected_dish if the dish count is valid. And if the dish has successfully been added, change the count in self.menu. :param dish: dict, the information of dish. dish = {"dish": dish name, "count": count, price: price} :return: True if successfully added, or False otherwise. >>> order = Order() >>> order.menu.append({"dish": "dish1", "price": 10, "count": 5}) >>> order.add_dish({"dish": "dish1", "price": 10, "count": 3}) True """ for menu_dish in self.menu: if dish["dish"] == menu_dish["dish"]: if menu_dish["count"] < dish["count"]: return False else: menu_dish["count"] -= dish["count"] break self.selected_dishes.append(dish) return True def checkout(self): """ Check out the dished ordered. IF the self.selected_dishes is not empty, invoke the calculate_total method to check out. :return Flase if the self.selected_dishes is empty, or total(return value of calculate_total) otherwise. >>> order = Order() >>> order.menu.append({"dish": "dish1", "price": 10, "count": 5}) >>> order.sales = {"dish1": 0.8} >>> order.add_dish({"dish": "dish1", "price": 10, "count": 4}) True >>> order.checkout() 32.0 """ if len(self.selected_dishes) == 0: return False total = self.calculate_total() self.selected_dishes = [] return total
class Order: """ The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout. """ def __init__(self): """ Initialize the order management system self.menu stores the dishes of resturant inventory menu = [{"dish": dish name, "price": price, "count": count}, ...] self.selected_dishes stores the dished selected by customer selected_dish = {"dish": dish name, "count": count, price: price} self.sales stores the sales of each dish sales = {dish name: sales} """ self.menu = [] self.selected_dishes = [] self.sales = {} def add_dish(self, dish): """ Check the self.menu and add into self.selected_dish if the dish count is valid. And if the dish has successfully been added, change the count in self.menu. :param dish: dict, the information of dish. dish = {"dish": dish name, "count": count, price: price} :return: True if successfully added, or False otherwise. >>> order = Order() >>> order.menu.append({"dish": "dish1", "price": 10, "count": 5}) >>> order.add_dish({"dish": "dish1", "price": 10, "count": 3}) True """ def checkout(self): """ Check out the dished ordered. IF the self.selected_dishes is not empty, invoke the calculate_total method to check out. :return Flase if the self.selected_dishes is empty, or total(return value of calculate_total) otherwise. >>> order = Order() >>> order.menu.append({"dish": "dish1", "price": 10, "count": 5}) >>> order.sales = {"dish1": 0.8} >>> order.add_dish({"dish": "dish1", "price": 10, "count": 4}) True >>> order.checkout() 32.0 """
def calculate_total(self): total = 0 for dish in self.selected_dishes: total += dish["price"] * dish["count"] * self.sales[dish["dish"]] return total
Calculate the total price of dishes that have been ordered. Multiply the count, price and sales.
ClassEval_67_sum
class Order: """ The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout. """ def __init__(self): self.menu = [] # menu = [{"dish": dish name, "price": price, "count": count}, ...] self.selected_dishes = [] # selected_dish = {"dish": dish name, "count": count, price: price} self.sales = {} # def add_dish(self, dish): """ Check the self.menu and add into self.selected_dish if the dish count is valid. And if the dish has successfully been added, change the count in self.menu. :param dish: dict, the information of dish. dish = {"dish": dish name, "count": count, price: price} :return: True if successfully added, or False otherwise. >>> order = Order() >>> order.menu.append({"dish": "dish1", "price": 10, "count": 5}) >>> order.add_dish({"dish": "dish1", "price": 10, "count": 3}) True """ for menu_dish in self.menu: if dish["dish"] == menu_dish["dish"]: if menu_dish["count"] < dish["count"]: return False else: menu_dish["count"] -= dish["count"] break self.selected_dishes.append(dish) return True def calculate_total(self): """ Calculate the total price of dishes that have been ordered. Multiply the count, price and sales. :return total: float, the final total price. >>> order = Order() >>> order.menu.append({"dish": "dish1", "price": 10, "count": 5}) >>> order.sales = {"dish1": 0.8} >>> order.add_dish({"dish": "dish1", "price": 10, "count": 4}) True >>> order.calculate_total() 32.0 """ total = 0 for dish in self.selected_dishes: total += dish["price"] * dish["count"] * self.sales[dish["dish"]] return total def checkout(self): if len(self.selected_dishes) == 0: return False total = self.calculate_total() self.selected_dishes = [] return total
class Order: """ The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout. """ def __init__(self): """ Initialize the order management system self.menu stores the dishes of resturant inventory menu = [{"dish": dish name, "price": price, "count": count}, ...] self.selected_dishes stores the dished selected by customer selected_dish = {"dish": dish name, "count": count, price: price} self.sales stores the sales of each dish sales = {dish name: sales} """ self.menu = [] self.selected_dishes = [] self.sales = {} def add_dish(self, dish): """ Check the self.menu and add into self.selected_dish if the dish count is valid. And if the dish has successfully been added, change the count in self.menu. :param dish: dict, the information of dish. dish = {"dish": dish name, "count": count, price: price} :return: True if successfully added, or False otherwise. >>> order = Order() >>> order.menu.append({"dish": "dish1", "price": 10, "count": 5}) >>> order.add_dish({"dish": "dish1", "price": 10, "count": 3}) True """ def calculate_total(self): """ Calculate the total price of dishes that have been ordered. Multiply the count, price and sales. :return total: float, the final total price. >>> order = Order() >>> order.menu.append({"dish": "dish1", "price": 10, "count": 5}) >>> order.sales = {"dish1": 0.8} >>> order.add_dish({"dish": "dish1", "price": 10, "count": 4}) True >>> order.calculate_total() 32.0 """ def checkout(self): """ Check out the dished ordered. IF the self.selected_dishes is not empty, invoke the calculate_total method to check out. :return Flase if the self.selected_dishes is empty, or total(return value of calculate_total) otherwise. >>> order = Order() >>> order.menu.append({"dish": "dish1", "price": 10, "count": 5}) >>> order.sales = {"dish1": 0.8} >>> order.add_dish({"dish": "dish1", "price": 10, "count": 4}) True >>> order.checkout() 32.0 """
def checkout(self): if len(self.selected_dishes) == 0: return False total = self.calculate_total() self.selected_dishes = [] return total
Check out the dished ordered. IF the self.selected_dishes is not empty, invoke the calculate_total method to check out.
ClassEval_68_sum
class PageUtil: """ PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner. """ def __init__(self, data, page_size): self.data = data self.page_size = page_size self.total_items = len(data) self.total_pages = (self.total_items + page_size - 1) // page_size def get_page_info(self, page_number): """ Retrieve information about a specific page. :param page_number: int, the page number to fetch information about :return: dict, containing page information such as current page number, total pages, etc. >>> page_util = PageUtil([1, 2, 3, 4], 1) >>> page_util.get_page_info(1) >>> { >>> "current_page": 1, >>> "per_page": 1, >>> "total_pages": 4, >>> "total_items": 4, >>> "has_previous": False, >>> "has_next": True, >>> "data": [1] >>> } """ if page_number < 1 or page_number > self.total_pages: return {} start_index = (page_number - 1) * self.page_size end_index = min(start_index + self.page_size, self.total_items) page_data = self.data[start_index:end_index] page_info = { "current_page": page_number, "per_page": self.page_size, "total_pages": self.total_pages, "total_items": self.total_items, "has_previous": page_number > 1, "has_next": page_number < self.total_pages, "data": page_data } return page_info def search(self, keyword): """ Search for items in the data that contain the given keyword. :param keyword: str, the keyword to search for :return: dict, containing search information such as total results and matching items >>> page_util = PageUtil([1, 2, 3, 4], 1) >>> page_util.search("1") >>> search_info = { >>> "keyword": "1", >>> "total_results": 1, >>> "total_pages": 1, >>> "results": [1] >>> } """ results = [item for item in self.data if keyword in str(item)] num_results = len(results) num_pages = (num_results + self.page_size - 1) // self.page_size search_info = { "keyword": keyword, "total_results": num_results, "total_pages": num_pages, "results": results } return search_info
class PageUtil: """ PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner. """ def __init__(self, data, page_size): """ Initialize the PageUtil object with the given data and page size. :param data: list, the data to be paginated :param page_size: int, the number of items per page """ self.data = data self.page_size = page_size self.total_items = len(data) self.total_pages = (self.total_items + page_size - 1) // page_size def get_page_info(self, page_number): """ Retrieve information about a specific page. :param page_number: int, the page number to fetch information about :return: dict, containing page information such as current page number, total pages, etc. >>> page_util = PageUtil([1, 2, 3, 4], 1) >>> page_util.get_page_info(1) >>> { >>> "current_page": 1, >>> "per_page": 1, >>> "total_pages": 4, >>> "total_items": 4, >>> "has_previous": False, >>> "has_next": True, >>> "data": [1] >>> } """ def search(self, keyword): """ Search for items in the data that contain the given keyword. :param keyword: str, the keyword to search for :return: dict, containing search information such as total results and matching items >>> page_util = PageUtil([1, 2, 3, 4], 1) >>> page_util.search("1") >>> search_info = { >>> "keyword": "1", >>> "total_results": 1, >>> "total_pages": 1, >>> "results": [1] >>> } """
def get_page(self, page_number): if page_number < 1 or page_number > self.total_pages: return [] start_index = (page_number - 1) * self.page_size end_index = start_index + self.page_size return self.data[start_index:end_index]
Retrieve a specific page of data.
ClassEval_68_sum
class PageUtil: """ PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner. """ def __init__(self, data, page_size): self.data = data self.page_size = page_size self.total_items = len(data) self.total_pages = (self.total_items + page_size - 1) // page_size def get_page(self, page_number): """ Retrieve a specific page of data. :param page_number: int, the page number to fetch :return: list, the data on the specified page >>> page_util = PageUtil([1, 2, 3, 4], 1) >>> page_util.get_page(1) [1] """ if page_number < 1 or page_number > self.total_pages: return [] start_index = (page_number - 1) * self.page_size end_index = start_index + self.page_size return self.data[start_index:end_index] def search(self, keyword): """ Search for items in the data that contain the given keyword. :param keyword: str, the keyword to search for :return: dict, containing search information such as total results and matching items >>> page_util = PageUtil([1, 2, 3, 4], 1) >>> page_util.search("1") >>> search_info = { >>> "keyword": "1", >>> "total_results": 1, >>> "total_pages": 1, >>> "results": [1] >>> } """ results = [item for item in self.data if keyword in str(item)] num_results = len(results) num_pages = (num_results + self.page_size - 1) // self.page_size search_info = { "keyword": keyword, "total_results": num_results, "total_pages": num_pages, "results": results } return search_info
class PageUtil: """ PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner. """ def __init__(self, data, page_size): """ Initialize the PageUtil object with the given data and page size. :param data: list, the data to be paginated :param page_size: int, the number of items per page """ self.data = data self.page_size = page_size self.total_items = len(data) self.total_pages = (self.total_items + page_size - 1) // page_size def get_page(self, page_number): """ Retrieve a specific page of data. :param page_number: int, the page number to fetch :return: list, the data on the specified page >>> page_util = PageUtil([1, 2, 3, 4], 1) >>> page_util.get_page(1) [1] """ def search(self, keyword): """ Search for items in the data that contain the given keyword. :param keyword: str, the keyword to search for :return: dict, containing search information such as total results and matching items >>> page_util = PageUtil([1, 2, 3, 4], 1) >>> page_util.search("1") >>> search_info = { >>> "keyword": "1", >>> "total_results": 1, >>> "total_pages": 1, >>> "results": [1] >>> } """
def get_page_info(self, page_number): if page_number < 1 or page_number > self.total_pages: return {} start_index = (page_number - 1) * self.page_size end_index = min(start_index + self.page_size, self.total_items) page_data = self.data[start_index:end_index] page_info = { "current_page": page_number, "per_page": self.page_size, "total_pages": self.total_pages, "total_items": self.total_items, "has_previous": page_number > 1, "has_next": page_number < self.total_pages, "data": page_data } return page_info
Retrieve information about a specific page.
ClassEval_68_sum
class PageUtil: """ PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner. """ def __init__(self, data, page_size): self.data = data self.page_size = page_size self.total_items = len(data) self.total_pages = (self.total_items + page_size - 1) // page_size def get_page(self, page_number): """ Retrieve a specific page of data. :param page_number: int, the page number to fetch :return: list, the data on the specified page >>> page_util = PageUtil([1, 2, 3, 4], 1) >>> page_util.get_page(1) [1] """ if page_number < 1 or page_number > self.total_pages: return [] start_index = (page_number - 1) * self.page_size end_index = start_index + self.page_size return self.data[start_index:end_index] def get_page_info(self, page_number): """ Retrieve information about a specific page. :param page_number: int, the page number to fetch information about :return: dict, containing page information such as current page number, total pages, etc. >>> page_util = PageUtil([1, 2, 3, 4], 1) >>> page_util.get_page_info(1) >>> { >>> "current_page": 1, >>> "per_page": 1, >>> "total_pages": 4, >>> "total_items": 4, >>> "has_previous": False, >>> "has_next": True, >>> "data": [1] >>> } """ if page_number < 1 or page_number > self.total_pages: return {} start_index = (page_number - 1) * self.page_size end_index = min(start_index + self.page_size, self.total_items) page_data = self.data[start_index:end_index] page_info = { "current_page": page_number, "per_page": self.page_size, "total_pages": self.total_pages, "total_items": self.total_items, "has_previous": page_number > 1, "has_next": page_number < self.total_pages, "data": page_data } return page_info def search(self, keyword): results = [item for item in self.data if keyword in str(item)] num_results = len(results) num_pages = (num_results + self.page_size - 1) // self.page_size search_info = { "keyword": keyword, "total_results": num_results, "total_pages": num_pages, "results": results } return search_info
class PageUtil: """ PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner. """ def __init__(self, data, page_size): """ Initialize the PageUtil object with the given data and page size. :param data: list, the data to be paginated :param page_size: int, the number of items per page """ self.data = data self.page_size = page_size self.total_items = len(data) self.total_pages = (self.total_items + page_size - 1) // page_size def get_page(self, page_number): """ Retrieve a specific page of data. :param page_number: int, the page number to fetch :return: list, the data on the specified page >>> page_util = PageUtil([1, 2, 3, 4], 1) >>> page_util.get_page(1) [1] """ def get_page_info(self, page_number): """ Retrieve information about a specific page. :param page_number: int, the page number to fetch information about :return: dict, containing page information such as current page number, total pages, etc. >>> page_util = PageUtil([1, 2, 3, 4], 1) >>> page_util.get_page_info(1) >>> { >>> "current_page": 1, >>> "per_page": 1, >>> "total_pages": 4, >>> "total_items": 4, >>> "has_previous": False, >>> "has_next": True, >>> "data": [1] >>> } """ def search(self, keyword): """ Search for items in the data that contain the given keyword. :param keyword: str, the keyword to search for :return: dict, containing search information such as total results and matching items >>> page_util = PageUtil([1, 2, 3, 4], 1) >>> page_util.search("1") >>> search_info = { >>> "keyword": "1", >>> "total_results": 1, >>> "total_pages": 1, >>> "results": [1] >>> } """
def search(self, keyword): results = [item for item in self.data if keyword in str(item)] num_results = len(results) num_pages = (num_results + self.page_size - 1) // self.page_size search_info = { "keyword": keyword, "total_results": num_results, "total_pages": num_pages, "results": results } return search_info
Search for items in the data that contain the given keyword.
ClassEval_69_sum
import PyPDF2 class PDFHandler: """ The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library. """ def __init__(self, filepaths): self.filepaths = filepaths # PdfFileReader is deprecated and was removed in PyPDF2 3.0.0. Use PdfReader instead. self.readers = [PyPDF2.PdfReader(fp) for fp in filepaths] def extract_text_from_pdfs(self): """ Extract text from pdf files in self.readers :return pdf_texts: list of str, each element is the text of one pdf file >>> handler = PDFHandler(['a.pdf', 'b.pdf']) >>> handler.extract_text_from_pdfs() ['Test a.pdf', 'Test b.pdf'] """ pdf_texts = [] for reader in self.readers: for page_num in range(len(reader.pages)): page = reader.pages[page_num] pdf_texts.append(page.extract_text()) return pdf_texts
import PyPDF2 class PDFHandler: """ The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library. """ def __init__(self, filepaths): """ takes a list of file paths filepaths as a parameter. It creates a list named readers using PyPDF2, where each reader opens a file from the given paths. """ self.filepaths = filepaths self.readers = [PyPDF2.PdfFileReader(fp) for fp in filepaths] def extract_text_from_pdfs(self): """ Extract text from pdf files in self.readers :return pdf_texts: list of str, each element is the text of one pdf file >>> handler = PDFHandler(['a.pdf', 'b.pdf']) >>> handler.extract_text_from_pdfs() ['Test a.pdf', 'Test b.pdf'] """
def merge_pdfs(self, output_filepath): pdf_writer = PyPDF2.PdfWriter() for reader in self.readers: # reader.getNumPages is deprecated and was removed in PyPDF2 3.0.0. Use len(reader.pages) instead. for page_num in range(len(reader.pages)): # reader.getPage(pageNumber) is deprecated and was removed in PyPDF2 3.0.0. Use reader.pages[page_number] instead. page = reader.pages[page_num] # addPage is deprecated and was removed in PyPDF2 3.0.0. Use add_page instead. pdf_writer.add_page(page) with open(output_filepath, 'wb') as out: pdf_writer.write(out) return f"Merged PDFs saved at {output_filepath}"
Read files in self.readers which stores handles to multiple PDF files. Merge them to one pdf and update the page number, then save in disk.
ClassEval_69_sum
import PyPDF2 class PDFHandler: """ The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library. """ def __init__(self, filepaths): self.filepaths = filepaths # PdfFileReader is deprecated and was removed in PyPDF2 3.0.0. Use PdfReader instead. self.readers = [PyPDF2.PdfReader(fp) for fp in filepaths] def merge_pdfs(self, output_filepath): """ Read files in self.readers which stores handles to multiple PDF files. Merge them to one pdf and update the page number, then save in disk. :param output_filepath: str, ouput file path to save to :return: str, "Merged PDFs saved at {output_filepath}" if successfully merged >>> handler = PDFHandler(['a.pdf', 'b.pdf']) >>> handler.merge_pdfs('out.pdf') Merged PDFs saved at out.pdf """ pdf_writer = PyPDF2.PdfWriter() for reader in self.readers: # reader.getNumPages is deprecated and was removed in PyPDF2 3.0.0. Use len(reader.pages) instead. for page_num in range(len(reader.pages)): # reader.getPage(pageNumber) is deprecated and was removed in PyPDF2 3.0.0. Use reader.pages[page_number] instead. page = reader.pages[page_num] # addPage is deprecated and was removed in PyPDF2 3.0.0. Use add_page instead. pdf_writer.add_page(page) with open(output_filepath, 'wb') as out: pdf_writer.write(out) return f"Merged PDFs saved at {output_filepath}" def extract_text_from_pdfs(self): pdf_texts = [] for reader in self.readers: for page_num in range(len(reader.pages)): page = reader.pages[page_num] pdf_texts.append(page.extract_text()) return pdf_texts
import PyPDF2 class PDFHandler: """ The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library. """ def __init__(self, filepaths): """ takes a list of file paths filepaths as a parameter. It creates a list named readers using PyPDF2, where each reader opens a file from the given paths. """ self.filepaths = filepaths self.readers = [PyPDF2.PdfFileReader(fp) for fp in filepaths] def merge_pdfs(self, output_filepath): """ Read files in self.readers which stores handles to multiple PDF files. Merge them to one pdf and update the page number, then save in disk. :param output_filepath: str, ouput file path to save to :return: str, "Merged PDFs saved at {output_filepath}" if successfully merged >>> handler = PDFHandler(['a.pdf', 'b.pdf']) >>> handler.merge_pdfs('out.pdf') Merged PDFs saved at out.pdf """ def extract_text_from_pdfs(self): """ Extract text from pdf files in self.readers :return pdf_texts: list of str, each element is the text of one pdf file >>> handler = PDFHandler(['a.pdf', 'b.pdf']) >>> handler.extract_text_from_pdfs() ['Test a.pdf', 'Test b.pdf'] """
def extract_text_from_pdfs(self): pdf_texts = [] for reader in self.readers: for page_num in range(len(reader.pages)): page = reader.pages[page_num] pdf_texts.append(page.extract_text()) return pdf_texts
Extract text from pdf files in self.readers
ClassEval_70_sum
class PersonRequest: """ This class validates input personal information data and sets invalid fields to None based to specific rules. """ def __init__(self, name: str, sex: str, phoneNumber: str): self.name = self._validate_name(name) self.sex = self._validate_sex(sex) self.phoneNumber = self._validate_phoneNumber(phoneNumber) def _validate_sex(self, sex: str) -> str: """ Validate the sex and return it. If sex is not Man, Woman, or UGM, set to None. :param sex: str, the sex to validate :return: str, the validated sex or None if invalid """ str) -> str: if sex not in ["Man", "Woman", "UGM"]: return None return sex def _validate_phoneNumber(self, phoneNumber: str) -> str: """ Validate the phone number and return it. If phoneNumber is empty or not an 11 digit number, set to None. :param phoneNumber: str, the phone number to validate :return: str, the validated phone number or None if invalid """ str) -> str: if not phoneNumber: return None if len(phoneNumber) != 11 or not phoneNumber.isdigit(): return None return phoneNumber
class PersonRequest: """ This class validates input personal information data and sets invalid fields to None based to specific rules. """ def __init__(self, name: str, sex: str, phoneNumber: str): """ Initialize PersonRequest object with the provided information. :param name: str, the name of the person :param sex: str, the sex of the person :param phoneNumber: str, the phone number of the person """ self.name = self._validate_name(name) self.sex = self._validate_sex(sex) self.phoneNumber = self._validate_phoneNumber(phoneNumber) def _validate_sex(self, sex: str) -> str: """ Validate the sex and return it. If sex is not Man, Woman, or UGM, set to None. :param sex: str, the sex to validate :return: str, the validated sex or None if invalid """ def _validate_phoneNumber(self, phoneNumber: str) -> str: """ Validate the phone number and return it. If phoneNumber is empty or not an 11 digit number, set to None. :param phoneNumber: str, the phone number to validate :return: str, the validated phone number or None if invalid """
def _validate_name(self, name: str) -> str: if not name: return None if len(name) > 33: return None return name
Validate the name and return it. If name is empty or exceeds 33 characters in length, set to None.
ClassEval_70_sum
class PersonRequest: """ This class validates input personal information data and sets invalid fields to None based to specific rules. """ def __init__(self, name: str, sex: str, phoneNumber: str): self.name = self._validate_name(name) self.sex = self._validate_sex(sex) self.phoneNumber = self._validate_phoneNumber(phoneNumber) def _validate_name(self, name: str) -> str: """ Validate the name and return it. If name is empty or exceeds 33 characters in length, set to None. :param name: str, the name to validate :return: str, the validated name or None if invalid """ str) -> str: if not name: return None if len(name) > 33: return None return name def _validate_phoneNumber(self, phoneNumber: str) -> str: """ Validate the phone number and return it. If phoneNumber is empty or not an 11 digit number, set to None. :param phoneNumber: str, the phone number to validate :return: str, the validated phone number or None if invalid """ str) -> str: if not phoneNumber: return None if len(phoneNumber) != 11 or not phoneNumber.isdigit(): return None return phoneNumber
class PersonRequest: """ This class validates input personal information data and sets invalid fields to None based to specific rules. """ def __init__(self, name: str, sex: str, phoneNumber: str): """ Initialize PersonRequest object with the provided information. :param name: str, the name of the person :param sex: str, the sex of the person :param phoneNumber: str, the phone number of the person """ self.name = self._validate_name(name) self.sex = self._validate_sex(sex) self.phoneNumber = self._validate_phoneNumber(phoneNumber) def _validate_name(self, name: str) -> str: """ Validate the name and return it. If name is empty or exceeds 33 characters in length, set to None. :param name: str, the name to validate :return: str, the validated name or None if invalid """ def _validate_phoneNumber(self, phoneNumber: str) -> str: """ Validate the phone number and return it. If phoneNumber is empty or not an 11 digit number, set to None. :param phoneNumber: str, the phone number to validate :return: str, the validated phone number or None if invalid """
def _validate_sex(self, sex: str) -> str: if sex not in ["Man", "Woman", "UGM"]: return None return sex
Validate the sex and return it. If sex is not Man, Woman, or UGM, set to None.
ClassEval_70_sum
class PersonRequest: """ This class validates input personal information data and sets invalid fields to None based to specific rules. """ def __init__(self, name: str, sex: str, phoneNumber: str): self.name = self._validate_name(name) self.sex = self._validate_sex(sex) self.phoneNumber = self._validate_phoneNumber(phoneNumber) def _validate_name(self, name: str) -> str: """ Validate the name and return it. If name is empty or exceeds 33 characters in length, set to None. :param name: str, the name to validate :return: str, the validated name or None if invalid """ str) -> str: if not name: return None if len(name) > 33: return None return name def _validate_sex(self, sex: str) -> str: """ Validate the sex and return it. If sex is not Man, Woman, or UGM, set to None. :param sex: str, the sex to validate :return: str, the validated sex or None if invalid """ str) -> str: if sex not in ["Man", "Woman", "UGM"]: return None return sex def _validate_phoneNumber(self, phoneNumber: str) -> str: if not phoneNumber: return None if len(phoneNumber) != 11 or not phoneNumber.isdigit(): return None return phoneNumber
class PersonRequest: """ This class validates input personal information data and sets invalid fields to None based to specific rules. """ def __init__(self, name: str, sex: str, phoneNumber: str): """ Initialize PersonRequest object with the provided information. :param name: str, the name of the person :param sex: str, the sex of the person :param phoneNumber: str, the phone number of the person """ self.name = self._validate_name(name) self.sex = self._validate_sex(sex) self.phoneNumber = self._validate_phoneNumber(phoneNumber) def _validate_name(self, name: str) -> str: """ Validate the name and return it. If name is empty or exceeds 33 characters in length, set to None. :param name: str, the name to validate :return: str, the validated name or None if invalid """ def _validate_sex(self, sex: str) -> str: """ Validate the sex and return it. If sex is not Man, Woman, or UGM, set to None. :param sex: str, the sex to validate :return: str, the validated sex or None if invalid """ def _validate_phoneNumber(self, phoneNumber: str) -> str: """ Validate the phone number and return it. If phoneNumber is empty or not an 11 digit number, set to None. :param phoneNumber: str, the phone number to validate :return: str, the validated phone number or None if invalid """
def _validate_phoneNumber(self, phoneNumber: str) -> str: if not phoneNumber: return None if len(phoneNumber) != 11 or not phoneNumber.isdigit(): return None return phoneNumber
Validate the phone number and return it. If phoneNumber is empty or not an 11 digit number, set to None.
ClassEval_71_sum
class PushBoxGame: """ This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win. """ def __init__(self, map): self.map = map self.player_row = 0 self.player_col = 0 self.targets = [] self.boxes = [] self.target_count = 0 self.is_game_over = False self.init_game() def check_win(self): """ Check if the game is won. The game is won when all the boxes are placed on target positions. And update the value of self.is_game_over. :return self.is_game_over: True if all the boxes are placed on target positions, or False otherwise. >>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"]) >>> game.check_win() """ box_on_target_count = 0 for box in self.boxes: if box in self.targets: box_on_target_count += 1 if box_on_target_count == self.target_count: self.is_game_over = True return self.is_game_over def move(self, direction): """ Move the player based on the specified direction and check if the game is won. :param direction: str, the direction of the player's movement. It can be 'w', 's', 'a', or 'd' representing up, down, left, or right respectively. :return: True if the game is won, False otherwise. >>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"]) >>> game.print_map() # # # # # # O # # X # # G # # # # # # >>> game.move('d') False >>> game.move('s') False >>> game.move('a') False >>> game.move('s') False >>> game.move('d') True """ new_player_row = self.player_row new_player_col = self.player_col if direction == "w": new_player_row -= 1 elif direction == "s": new_player_row += 1 elif direction == "a": new_player_col -= 1 elif direction == "d": new_player_col += 1 if self.map[new_player_row][new_player_col] != "#": if (new_player_row, new_player_col) in self.boxes: new_box_row = new_player_row + (new_player_row - self.player_row) new_box_col = new_player_col + (new_player_col - self.player_col) if self.map[new_box_row][new_box_col] != "#": self.boxes.remove((new_player_row, new_player_col)) self.boxes.append((new_box_row, new_box_col)) self.player_row = new_player_row self.player_col = new_player_col else: self.player_row = new_player_row self.player_col = new_player_col return self.check_win()
class PushBoxGame: """ This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win. """ def __init__(self, map): """ Initialize the push box game with the map and various attributes. :param map: list[str], the map of the push box game, represented as a list of strings. Each character on the map represents a different element, including the following: - '#' represents a wall that neither the player nor the box can pass through; - 'O' represents the initial position of the player; - 'G' represents the target position; - 'X' represents the initial position of the box. >>> map = ["#####", "#O #", "# X #", "# G#", "#####"] >>> game = PushBoxGame(map) """ self.map = map self.player_row = 0 self.player_col = 0 self.targets = [] self.boxes = [] self.target_count = 0 self.is_game_over = False self.init_game() def check_win(self): """ Check if the game is won. The game is won when all the boxes are placed on target positions. And update the value of self.is_game_over. :return self.is_game_over: True if all the boxes are placed on target positions, or False otherwise. >>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"]) >>> game.check_win() """ def move(self, direction): """ Move the player based on the specified direction and check if the game is won. :param direction: str, the direction of the player's movement. It can be 'w', 's', 'a', or 'd' representing up, down, left, or right respectively. :return: True if the game is won, False otherwise. >>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"]) >>> game.print_map() # # # # # # O # # X # # G # # # # # # >>> game.move('d') False >>> game.move('s') False >>> game.move('a') False >>> game.move('s') False >>> game.move('d') True """
def init_game(self): for row in range(len(self.map)): for col in range(len(self.map[row])): if self.map[row][col] == "O": self.player_row = row self.player_col = col elif self.map[row][col] == "G": self.targets.append((row, col)) self.target_count += 1 elif self.map[row][col] == "X": self.boxes.append((row, col))
Initialize the game by setting the positions of the player, targets, and boxes based on the map.
ClassEval_71_sum
class PushBoxGame: """ This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win. """ def __init__(self, map): self.map = map self.player_row = 0 self.player_col = 0 self.targets = [] self.boxes = [] self.target_count = 0 self.is_game_over = False self.init_game() def init_game(self): """ Initialize the game by setting the positions of the player, targets, and boxes based on the map. >>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"]) >>> game.targets [(3, 3)] >>> game.boxes [(2, 2)] >>> game.player_row 1 >>> game.player_col 1 """ for row in range(len(self.map)): for col in range(len(self.map[row])): if self.map[row][col] == "O": self.player_row = row self.player_col = col elif self.map[row][col] == "G": self.targets.append((row, col)) self.target_count += 1 elif self.map[row][col] == "X": self.boxes.append((row, col)) def move(self, direction): """ Move the player based on the specified direction and check if the game is won. :param direction: str, the direction of the player's movement. It can be 'w', 's', 'a', or 'd' representing up, down, left, or right respectively. :return: True if the game is won, False otherwise. >>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"]) >>> game.print_map() # # # # # # O # # X # # G # # # # # # >>> game.move('d') False >>> game.move('s') False >>> game.move('a') False >>> game.move('s') False >>> game.move('d') True """ new_player_row = self.player_row new_player_col = self.player_col if direction == "w": new_player_row -= 1 elif direction == "s": new_player_row += 1 elif direction == "a": new_player_col -= 1 elif direction == "d": new_player_col += 1 if self.map[new_player_row][new_player_col] != "#": if (new_player_row, new_player_col) in self.boxes: new_box_row = new_player_row + (new_player_row - self.player_row) new_box_col = new_player_col + (new_player_col - self.player_col) if self.map[new_box_row][new_box_col] != "#": self.boxes.remove((new_player_row, new_player_col)) self.boxes.append((new_box_row, new_box_col)) self.player_row = new_player_row self.player_col = new_player_col else: self.player_row = new_player_row self.player_col = new_player_col return self.check_win()
class PushBoxGame: """ This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win. """ def __init__(self, map): """ Initialize the push box game with the map and various attributes. :param map: list[str], the map of the push box game, represented as a list of strings. Each character on the map represents a different element, including the following: - '#' represents a wall that neither the player nor the box can pass through; - 'O' represents the initial position of the player; - 'G' represents the target position; - 'X' represents the initial position of the box. >>> map = ["#####", "#O #", "# X #", "# G#", "#####"] >>> game = PushBoxGame(map) """ self.map = map self.player_row = 0 self.player_col = 0 self.targets = [] self.boxes = [] self.target_count = 0 self.is_game_over = False self.init_game() def init_game(self): """ Initialize the game by setting the positions of the player, targets, and boxes based on the map. >>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"]) >>> game.targets [(3, 3)] >>> game.boxes [(2, 2)] >>> game.player_row 1 >>> game.player_col 1 """ def move(self, direction): """ Move the player based on the specified direction and check if the game is won. :param direction: str, the direction of the player's movement. It can be 'w', 's', 'a', or 'd' representing up, down, left, or right respectively. :return: True if the game is won, False otherwise. >>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"]) >>> game.print_map() # # # # # # O # # X # # G # # # # # # >>> game.move('d') False >>> game.move('s') False >>> game.move('a') False >>> game.move('s') False >>> game.move('d') True """
def check_win(self): box_on_target_count = 0 for box in self.boxes: if box in self.targets: box_on_target_count += 1 if box_on_target_count == self.target_count: self.is_game_over = True return self.is_game_over
Check if the game is won. The game is won when all the boxes are placed on target positions. And update the value of self.is_game_over.
ClassEval_71_sum
class PushBoxGame: """ This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win. """ def __init__(self, map): self.map = map self.player_row = 0 self.player_col = 0 self.targets = [] self.boxes = [] self.target_count = 0 self.is_game_over = False self.init_game() def init_game(self): """ Initialize the game by setting the positions of the player, targets, and boxes based on the map. >>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"]) >>> game.targets [(3, 3)] >>> game.boxes [(2, 2)] >>> game.player_row 1 >>> game.player_col 1 """ for row in range(len(self.map)): for col in range(len(self.map[row])): if self.map[row][col] == "O": self.player_row = row self.player_col = col elif self.map[row][col] == "G": self.targets.append((row, col)) self.target_count += 1 elif self.map[row][col] == "X": self.boxes.append((row, col)) def check_win(self): """ Check if the game is won. The game is won when all the boxes are placed on target positions. And update the value of self.is_game_over. :return self.is_game_over: True if all the boxes are placed on target positions, or False otherwise. >>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"]) >>> game.check_win() """ box_on_target_count = 0 for box in self.boxes: if box in self.targets: box_on_target_count += 1 if box_on_target_count == self.target_count: self.is_game_over = True return self.is_game_over def move(self, direction): new_player_row = self.player_row new_player_col = self.player_col if direction == "w": new_player_row -= 1 elif direction == "s": new_player_row += 1 elif direction == "a": new_player_col -= 1 elif direction == "d": new_player_col += 1 if self.map[new_player_row][new_player_col] != "#": if (new_player_row, new_player_col) in self.boxes: new_box_row = new_player_row + (new_player_row - self.player_row) new_box_col = new_player_col + (new_player_col - self.player_col) if self.map[new_box_row][new_box_col] != "#": self.boxes.remove((new_player_row, new_player_col)) self.boxes.append((new_box_row, new_box_col)) self.player_row = new_player_row self.player_col = new_player_col else: self.player_row = new_player_row self.player_col = new_player_col return self.check_win()
class PushBoxGame: """ This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win. """ def __init__(self, map): """ Initialize the push box game with the map and various attributes. :param map: list[str], the map of the push box game, represented as a list of strings. Each character on the map represents a different element, including the following: - '#' represents a wall that neither the player nor the box can pass through; - 'O' represents the initial position of the player; - 'G' represents the target position; - 'X' represents the initial position of the box. >>> map = ["#####", "#O #", "# X #", "# G#", "#####"] >>> game = PushBoxGame(map) """ self.map = map self.player_row = 0 self.player_col = 0 self.targets = [] self.boxes = [] self.target_count = 0 self.is_game_over = False self.init_game() def init_game(self): """ Initialize the game by setting the positions of the player, targets, and boxes based on the map. >>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"]) >>> game.targets [(3, 3)] >>> game.boxes [(2, 2)] >>> game.player_row 1 >>> game.player_col 1 """ def check_win(self): """ Check if the game is won. The game is won when all the boxes are placed on target positions. And update the value of self.is_game_over. :return self.is_game_over: True if all the boxes are placed on target positions, or False otherwise. >>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"]) >>> game.check_win() """ def move(self, direction): """ Move the player based on the specified direction and check if the game is won. :param direction: str, the direction of the player's movement. It can be 'w', 's', 'a', or 'd' representing up, down, left, or right respectively. :return: True if the game is won, False otherwise. >>> game = PushBoxGame(["#####", "#O #", "# X #", "# G#", "#####"]) >>> game.print_map() # # # # # # O # # X # # G # # # # # # >>> game.move('d') False >>> game.move('s') False >>> game.move('a') False >>> game.move('s') False >>> game.move('d') True """
def move(self, direction): new_player_row = self.player_row new_player_col = self.player_col if direction == "w": new_player_row -= 1 elif direction == "s": new_player_row += 1 elif direction == "a": new_player_col -= 1 elif direction == "d": new_player_col += 1 if self.map[new_player_row][new_player_col] != "#": if (new_player_row, new_player_col) in self.boxes: new_box_row = new_player_row + (new_player_row - self.player_row) new_box_col = new_player_col + (new_player_col - self.player_col) if self.map[new_box_row][new_box_col] != "#": self.boxes.remove((new_player_row, new_player_col)) self.boxes.append((new_box_row, new_box_col)) self.player_row = new_player_row self.player_col = new_player_col else: self.player_row = new_player_row self.player_col = new_player_col return self.check_win()
Move the player based on the specified direction and check if the game is won.
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ return re.findall(pattern, text) def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ return re.split(pattern, text) def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ return re.sub(pattern, replacement, text) def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' return pattern def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ pattern = r'\b\d{3}-\d{3}-\d{4}\b' return pattern def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ pattern = r'[.!?][\s]{1,2}(?=[A-Z])' return pattern def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ pattern = self.generate_split_sentences_pattern() return self.split(pattern, text) def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ pattern = self.generate_phone_number_pattern() return self.match(pattern, phone_number) def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """ pattern = self.generate_email_pattern() return self.findall(pattern, text)
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """
def match(self, pattern, text): ans = re.match(pattern, text) if ans: return True else: return False
Check if the text matches the regular expression
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ ans = re.match(pattern, text) if ans: return True else: return False def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ return re.split(pattern, text) def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ return re.sub(pattern, replacement, text) def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' return pattern def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ pattern = r'\b\d{3}-\d{3}-\d{4}\b' return pattern def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ pattern = r'[.!?][\s]{1,2}(?=[A-Z])' return pattern def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ pattern = self.generate_split_sentences_pattern() return self.split(pattern, text) def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ pattern = self.generate_phone_number_pattern() return self.match(pattern, phone_number) def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """ pattern = self.generate_email_pattern() return self.findall(pattern, text)
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """
def findall(self, pattern, text): return re.findall(pattern, text)
Find all matching substrings and return a list of all matching substrings
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ ans = re.match(pattern, text) if ans: return True else: return False def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ return re.findall(pattern, text) def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ return re.sub(pattern, replacement, text) def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' return pattern def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ pattern = r'\b\d{3}-\d{3}-\d{4}\b' return pattern def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ pattern = r'[.!?][\s]{1,2}(?=[A-Z])' return pattern def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ pattern = self.generate_split_sentences_pattern() return self.split(pattern, text) def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ pattern = self.generate_phone_number_pattern() return self.match(pattern, phone_number) def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """ pattern = self.generate_email_pattern() return self.findall(pattern, text)
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """
def split(self, pattern, text): return re.split(pattern, text)
Split text based on regular expression patterns and return a list of substrings
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ ans = re.match(pattern, text) if ans: return True else: return False def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ return re.findall(pattern, text) def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ return re.split(pattern, text) def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' return pattern def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ pattern = r'\b\d{3}-\d{3}-\d{4}\b' return pattern def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ pattern = r'[.!?][\s]{1,2}(?=[A-Z])' return pattern def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ pattern = self.generate_split_sentences_pattern() return self.split(pattern, text) def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ pattern = self.generate_phone_number_pattern() return self.match(pattern, phone_number) def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """ pattern = self.generate_email_pattern() return self.findall(pattern, text)
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """
def sub(self, pattern, replacement, text): return re.sub(pattern, replacement, text)
Replace the substring matched by a regular expression with the specified string
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ ans = re.match(pattern, text) if ans: return True else: return False def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ return re.findall(pattern, text) def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ return re.split(pattern, text) def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ return re.sub(pattern, replacement, text) def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ pattern = r'\b\d{3}-\d{3}-\d{4}\b' return pattern def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ pattern = r'[.!?][\s]{1,2}(?=[A-Z])' return pattern def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ pattern = self.generate_split_sentences_pattern() return self.split(pattern, text) def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ pattern = self.generate_phone_number_pattern() return self.match(pattern, phone_number) def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """ pattern = self.generate_email_pattern() return self.findall(pattern, text)
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """
def generate_email_pattern(self): pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' return pattern
Generate regular expression patterns that match email addresses
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ ans = re.match(pattern, text) if ans: return True else: return False def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ return re.findall(pattern, text) def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ return re.split(pattern, text) def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ return re.sub(pattern, replacement, text) def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' return pattern def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ pattern = r'[.!?][\s]{1,2}(?=[A-Z])' return pattern def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ pattern = self.generate_split_sentences_pattern() return self.split(pattern, text) def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ pattern = self.generate_phone_number_pattern() return self.match(pattern, phone_number) def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """ pattern = self.generate_email_pattern() return self.findall(pattern, text)
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """
def generate_phone_number_pattern(self): pattern = r'\b\d{3}-\d{3}-\d{4}\b' return pattern
Generate regular expression patterns that match phone numbers
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ ans = re.match(pattern, text) if ans: return True else: return False def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ return re.findall(pattern, text) def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ return re.split(pattern, text) def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ return re.sub(pattern, replacement, text) def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' return pattern def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ pattern = r'\b\d{3}-\d{3}-\d{4}\b' return pattern def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ pattern = self.generate_split_sentences_pattern() return self.split(pattern, text) def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ pattern = self.generate_phone_number_pattern() return self.match(pattern, phone_number) def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """ pattern = self.generate_email_pattern() return self.findall(pattern, text)
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """
def generate_split_sentences_pattern(self): pattern = r'[.!?][\s]{1,2}(?=[A-Z])' return pattern
Generate regular expression patterns that match the middle characters of two sentences
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ ans = re.match(pattern, text) if ans: return True else: return False def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ return re.findall(pattern, text) def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ return re.split(pattern, text) def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ return re.sub(pattern, replacement, text) def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' return pattern def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ pattern = r'\b\d{3}-\d{3}-\d{4}\b' return pattern def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ pattern = r'[.!?][\s]{1,2}(?=[A-Z])' return pattern def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ pattern = self.generate_phone_number_pattern() return self.match(pattern, phone_number) def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """ pattern = self.generate_email_pattern() return self.findall(pattern, text)
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """
def split_sentences(self, text): pattern = self.generate_split_sentences_pattern() return self.split(pattern, text)
Split the text into a list of sentences without Punctuation except the last sentence
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ ans = re.match(pattern, text) if ans: return True else: return False def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ return re.findall(pattern, text) def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ return re.split(pattern, text) def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ return re.sub(pattern, replacement, text) def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' return pattern def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ pattern = r'\b\d{3}-\d{3}-\d{4}\b' return pattern def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ pattern = r'[.!?][\s]{1,2}(?=[A-Z])' return pattern def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ pattern = self.generate_split_sentences_pattern() return self.split(pattern, text) def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """ pattern = self.generate_email_pattern() return self.findall(pattern, text)
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """
def validate_phone_number(self, phone_number): pattern = self.generate_phone_number_pattern() return self.match(pattern, phone_number)
Verify if the phone number is valid
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ ans = re.match(pattern, text) if ans: return True else: return False def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ return re.findall(pattern, text) def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ return re.split(pattern, text) def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ return re.sub(pattern, replacement, text) def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' return pattern def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ pattern = r'\b\d{3}-\d{3}-\d{4}\b' return pattern def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ pattern = r'[.!?][\s]{1,2}(?=[A-Z])' return pattern def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ pattern = self.generate_split_sentences_pattern() return self.split(pattern, text) def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ pattern = self.generate_phone_number_pattern() return self.match(pattern, phone_number) def extract_email(self, text): pattern = self.generate_email_pattern() return self.findall(pattern, text)
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the text matches the regular expression :param pattern: string, Regular expression pattern :param text: string, Text to match :return: True or False, representing whether the text matches the regular expression or not >>> ru = RegexUtils() >>> ru.match(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890") True """ def findall(self, pattern, text): """ Find all matching substrings and return a list of all matching substrings :param pattern: string, Regular expression pattern :param text: string, Text to match :return: list of string, List of all matching substrings >>> ru = RegexUtils() >>> ru.findall(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['123-456-7890', '876-286-9876', '987-762-9767'] """ def split(self, pattern, text): """ Split text based on regular expression patterns and return a list of substrings :param pattern: string, Regular expression pattern :param text: string, Text to be split :return: list of string, List of substrings after splitting >>> ru = RegexUtils() >>> ru.split(r'\b\d{3}-\d{3}-\d{4}\b', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") ['', ' abiguygusu ', ' kjgufwycs ', ''] """ def sub(self, pattern, replacement, text): """ Replace the substring matched by a regular expression with the specified string :param pattern: string, Regular expression pattern :param replacement: Text to replace with :param text: string, Text to be replaced :return: string, Text after replacement >>> ru = RegexUtils() >>> ru.sub(r'\b\d{3}-\d{3}-\d{4}\b', 'phone num', "123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767") 'phone num abiguygusu phone num kjgufwycs phone num' """ def generate_email_pattern(self): """ Generate regular expression patterns that match email addresses :return: string, regular expression patterns that match email addresses >>> ru = RegexUtils() >>> ru.generate_email_pattern() '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' """ def generate_phone_number_pattern(self): """ Generate regular expression patterns that match phone numbers :return: string, regular expression patterns that match phone numbers >>> ru = RegexUtils() >>> ru.generate_phone_number_pattern() '\b\d{3}-\d{3}-\d{4}\b' """ def generate_split_sentences_pattern(self): """ Generate regular expression patterns that match the middle characters of two sentences :return: string, regular expression patterns that match the middle characters of two sentences >>> ru = RegexUtils() >>> ru.generate_split_sentences_pattern() '[.!?][\s]{1,2}(?=[A-Z])' """ def split_sentences(self, text): """ Split the text into a list of sentences without Punctuation except the last sentence :param text: Text to be split :return: Split Text List >>> ru = RegexUtils() >>> ru.split_sentences("Aaa. Bbbb? Ccc!") ['Aaa', 'Bbbb', 'Ccc!'] """ def validate_phone_number(self, phone_number): """ Verify if the phone number is valid :param phone_number: Phone number to be verified :return: True or False, indicating whether the phone number is valid >>> ru = RegexUtils() >>> ru.validate_phone_number("123-456-7890") True """ def extract_email(self, text): """ Extract all email addresses from the text :param text: string, input text :return: list of string, All extracted email addresses >>> ru = RegexUtils() >>> ru.extract_email("abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com") ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'] """
def extract_email(self, text): pattern = self.generate_email_pattern() return self.findall(pattern, text)
Extract all email addresses from the text
ClassEval_73_sum
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): self.name = name self.hp = hp self.attack_power = attack_power self.defense = defense self.level = level self.exp = 0 def heal(self): """ Heal the character with 10 hp and the max hp is 100. :return: int, the current health points after healing. >>> player_1 = RPGCharacter('player 1', 93, 10, 3) >>> player_1.heal() 100 """ self.hp += 10 if self.hp > 100: self.hp = 100 return self.hp def gain_exp(self, amount): """ Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level The experience that overflows should be used to calculate the next leve up untill exhausts :param amount: int, the amount of experience points to gain. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.gain_exp(1100) >>> player_1.exp 100 >>> player_1.level 5 """ while amount != 0: if self.exp + amount >= self.level * 100: amount -= (self.level * 100 - self.exp) self.level_up() else: self.exp += amount amount = 0 def level_up(self): """ Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points. max level is 100 :return: tuple[int, int, int, int], the new level, health points, attack power, and defense points after leveling up. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.level_up() (2, 120, 15, 8) """ if self.level < 100: self.level += 1 self.exp = 0 self.hp += 20 self.attack_power += 5 self.defense += 5 return self.level, self.hp, self.attack_power, self.defense def is_alive(self): """ Check if player is alive. :return: True if the hp is larger than 0, or False otherwise. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.is_alive() True """ return self.hp > 0
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): """ Initialize an RPG character object. :param name: strm, the name of the character. :param hp: int, The health points of the character. :param attack_power: int, the attack power of the character. :param defense: int, the defense points of the character. :param level: int, the level of the character. Default is 1. """ self.name = name self.hp = hp self.attack_power = attack_power self.defense = defense self.level = level self.exp = 0 def heal(self): """ Heal the character with 10 hp and the max hp is 100. :return: int, the current health points after healing. >>> player_1 = RPGCharacter('player 1', 93, 10, 3) >>> player_1.heal() 100 """ def gain_exp(self, amount): """ Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level The experience that overflows should be used to calculate the next leve up untill exhausts :param amount: int, the amount of experience points to gain. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.gain_exp(1100) >>> player_1.exp 100 >>> player_1.level 5 """ def level_up(self): """ Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points. max level is 100 :return: tuple[int, int, int, int], the new level, health points, attack power, and defense points after leveling up. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.level_up() (2, 120, 15, 8) """ def is_alive(self): """ Check if player is alive. :return: True if the hp is larger than 0, or False otherwise. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.is_alive() True """
def attack(self, other_character): damage = max(self.attack_power - other_character.defense, 1) other_character.hp -= damage
Attack another character. The damage caused needs to offset the defense value.
ClassEval_73_sum
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): self.name = name self.hp = hp self.attack_power = attack_power self.defense = defense self.level = level self.exp = 0 def attack(self, other_character): """ Attack another character. The damage caused needs to offset the defense value. :param other_character: str, The character being attacked. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_2 = RPGCharacter('player 2', 100, 7, 2) >>> player_1.attack(player_2) >>> player_2.hp 92 """ damage = max(self.attack_power - other_character.defense, 1) other_character.hp -= damage def gain_exp(self, amount): """ Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level The experience that overflows should be used to calculate the next leve up untill exhausts :param amount: int, the amount of experience points to gain. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.gain_exp(1100) >>> player_1.exp 100 >>> player_1.level 5 """ while amount != 0: if self.exp + amount >= self.level * 100: amount -= (self.level * 100 - self.exp) self.level_up() else: self.exp += amount amount = 0 def level_up(self): """ Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points. max level is 100 :return: tuple[int, int, int, int], the new level, health points, attack power, and defense points after leveling up. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.level_up() (2, 120, 15, 8) """ if self.level < 100: self.level += 1 self.exp = 0 self.hp += 20 self.attack_power += 5 self.defense += 5 return self.level, self.hp, self.attack_power, self.defense def is_alive(self): """ Check if player is alive. :return: True if the hp is larger than 0, or False otherwise. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.is_alive() True """ return self.hp > 0
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): """ Initialize an RPG character object. :param name: strm, the name of the character. :param hp: int, The health points of the character. :param attack_power: int, the attack power of the character. :param defense: int, the defense points of the character. :param level: int, the level of the character. Default is 1. """ self.name = name self.hp = hp self.attack_power = attack_power self.defense = defense self.level = level self.exp = 0 def attack(self, other_character): """ Attack another character. The damage caused needs to offset the defense value. :param other_character: str, The character being attacked. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_2 = RPGCharacter('player 2', 100, 7, 2) >>> player_1.attack(player_2) >>> player_2.hp 92 """ def gain_exp(self, amount): """ Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level The experience that overflows should be used to calculate the next leve up untill exhausts :param amount: int, the amount of experience points to gain. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.gain_exp(1100) >>> player_1.exp 100 >>> player_1.level 5 """ def level_up(self): """ Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points. max level is 100 :return: tuple[int, int, int, int], the new level, health points, attack power, and defense points after leveling up. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.level_up() (2, 120, 15, 8) """ def is_alive(self): """ Check if player is alive. :return: True if the hp is larger than 0, or False otherwise. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.is_alive() True """
def heal(self): self.hp += 10 if self.hp > 100: self.hp = 100 return self.hp
Heal the character with 10 hp and the max hp is 100.
ClassEval_73_sum
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): self.name = name self.hp = hp self.attack_power = attack_power self.defense = defense self.level = level self.exp = 0 def attack(self, other_character): """ Attack another character. The damage caused needs to offset the defense value. :param other_character: str, The character being attacked. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_2 = RPGCharacter('player 2', 100, 7, 2) >>> player_1.attack(player_2) >>> player_2.hp 92 """ damage = max(self.attack_power - other_character.defense, 1) other_character.hp -= damage def heal(self): """ Heal the character with 10 hp and the max hp is 100. :return: int, the current health points after healing. >>> player_1 = RPGCharacter('player 1', 93, 10, 3) >>> player_1.heal() 100 """ self.hp += 10 if self.hp > 100: self.hp = 100 return self.hp def level_up(self): """ Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points. max level is 100 :return: tuple[int, int, int, int], the new level, health points, attack power, and defense points after leveling up. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.level_up() (2, 120, 15, 8) """ if self.level < 100: self.level += 1 self.exp = 0 self.hp += 20 self.attack_power += 5 self.defense += 5 return self.level, self.hp, self.attack_power, self.defense def is_alive(self): """ Check if player is alive. :return: True if the hp is larger than 0, or False otherwise. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.is_alive() True """ return self.hp > 0
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): """ Initialize an RPG character object. :param name: strm, the name of the character. :param hp: int, The health points of the character. :param attack_power: int, the attack power of the character. :param defense: int, the defense points of the character. :param level: int, the level of the character. Default is 1. """ self.name = name self.hp = hp self.attack_power = attack_power self.defense = defense self.level = level self.exp = 0 def attack(self, other_character): """ Attack another character. The damage caused needs to offset the defense value. :param other_character: str, The character being attacked. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_2 = RPGCharacter('player 2', 100, 7, 2) >>> player_1.attack(player_2) >>> player_2.hp 92 """ def heal(self): """ Heal the character with 10 hp and the max hp is 100. :return: int, the current health points after healing. >>> player_1 = RPGCharacter('player 1', 93, 10, 3) >>> player_1.heal() 100 """ def level_up(self): """ Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points. max level is 100 :return: tuple[int, int, int, int], the new level, health points, attack power, and defense points after leveling up. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.level_up() (2, 120, 15, 8) """ def is_alive(self): """ Check if player is alive. :return: True if the hp is larger than 0, or False otherwise. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.is_alive() True """
def gain_exp(self, amount): while amount != 0: if self.exp + amount >= self.level * 100: amount -= (self.level * 100 - self.exp) self.level_up() else: self.exp += amount amount = 0
Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level The experience that overflows should be used to calculate the next leve up untill exhausts
ClassEval_73_sum
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): self.name = name self.hp = hp self.attack_power = attack_power self.defense = defense self.level = level self.exp = 0 def attack(self, other_character): """ Attack another character. The damage caused needs to offset the defense value. :param other_character: str, The character being attacked. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_2 = RPGCharacter('player 2', 100, 7, 2) >>> player_1.attack(player_2) >>> player_2.hp 92 """ damage = max(self.attack_power - other_character.defense, 1) other_character.hp -= damage def heal(self): """ Heal the character with 10 hp and the max hp is 100. :return: int, the current health points after healing. >>> player_1 = RPGCharacter('player 1', 93, 10, 3) >>> player_1.heal() 100 """ self.hp += 10 if self.hp > 100: self.hp = 100 return self.hp def gain_exp(self, amount): """ Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level The experience that overflows should be used to calculate the next leve up untill exhausts :param amount: int, the amount of experience points to gain. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.gain_exp(1100) >>> player_1.exp 100 >>> player_1.level 5 """ while amount != 0: if self.exp + amount >= self.level * 100: amount -= (self.level * 100 - self.exp) self.level_up() else: self.exp += amount amount = 0 def is_alive(self): """ Check if player is alive. :return: True if the hp is larger than 0, or False otherwise. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.is_alive() True """ return self.hp > 0
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): """ Initialize an RPG character object. :param name: strm, the name of the character. :param hp: int, The health points of the character. :param attack_power: int, the attack power of the character. :param defense: int, the defense points of the character. :param level: int, the level of the character. Default is 1. """ self.name = name self.hp = hp self.attack_power = attack_power self.defense = defense self.level = level self.exp = 0 def attack(self, other_character): """ Attack another character. The damage caused needs to offset the defense value. :param other_character: str, The character being attacked. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_2 = RPGCharacter('player 2', 100, 7, 2) >>> player_1.attack(player_2) >>> player_2.hp 92 """ def heal(self): """ Heal the character with 10 hp and the max hp is 100. :return: int, the current health points after healing. >>> player_1 = RPGCharacter('player 1', 93, 10, 3) >>> player_1.heal() 100 """ def gain_exp(self, amount): """ Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level The experience that overflows should be used to calculate the next leve up untill exhausts :param amount: int, the amount of experience points to gain. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.gain_exp(1100) >>> player_1.exp 100 >>> player_1.level 5 """ def is_alive(self): """ Check if player is alive. :return: True if the hp is larger than 0, or False otherwise. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.is_alive() True """
def level_up(self): if self.level < 100: self.level += 1 self.exp = 0 self.hp += 20 self.attack_power += 5 self.defense += 5 return self.level, self.hp, self.attack_power, self.defense
Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points. max level is 100
ClassEval_73_sum
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): self.name = name self.hp = hp self.attack_power = attack_power self.defense = defense self.level = level self.exp = 0 def attack(self, other_character): """ Attack another character. The damage caused needs to offset the defense value. :param other_character: str, The character being attacked. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_2 = RPGCharacter('player 2', 100, 7, 2) >>> player_1.attack(player_2) >>> player_2.hp 92 """ damage = max(self.attack_power - other_character.defense, 1) other_character.hp -= damage def heal(self): """ Heal the character with 10 hp and the max hp is 100. :return: int, the current health points after healing. >>> player_1 = RPGCharacter('player 1', 93, 10, 3) >>> player_1.heal() 100 """ self.hp += 10 if self.hp > 100: self.hp = 100 return self.hp def gain_exp(self, amount): """ Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level The experience that overflows should be used to calculate the next leve up untill exhausts :param amount: int, the amount of experience points to gain. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.gain_exp(1100) >>> player_1.exp 100 >>> player_1.level 5 """ while amount != 0: if self.exp + amount >= self.level * 100: amount -= (self.level * 100 - self.exp) self.level_up() else: self.exp += amount amount = 0 def level_up(self): """ Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points. max level is 100 :return: tuple[int, int, int, int], the new level, health points, attack power, and defense points after leveling up. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.level_up() (2, 120, 15, 8) """ if self.level < 100: self.level += 1 self.exp = 0 self.hp += 20 self.attack_power += 5 self.defense += 5 return self.level, self.hp, self.attack_power, self.defense def is_alive(self): return self.hp > 0
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): """ Initialize an RPG character object. :param name: strm, the name of the character. :param hp: int, The health points of the character. :param attack_power: int, the attack power of the character. :param defense: int, the defense points of the character. :param level: int, the level of the character. Default is 1. """ self.name = name self.hp = hp self.attack_power = attack_power self.defense = defense self.level = level self.exp = 0 def attack(self, other_character): """ Attack another character. The damage caused needs to offset the defense value. :param other_character: str, The character being attacked. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_2 = RPGCharacter('player 2', 100, 7, 2) >>> player_1.attack(player_2) >>> player_2.hp 92 """ def heal(self): """ Heal the character with 10 hp and the max hp is 100. :return: int, the current health points after healing. >>> player_1 = RPGCharacter('player 1', 93, 10, 3) >>> player_1.heal() 100 """ def gain_exp(self, amount): """ Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level The experience that overflows should be used to calculate the next leve up untill exhausts :param amount: int, the amount of experience points to gain. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.gain_exp(1100) >>> player_1.exp 100 >>> player_1.level 5 """ def level_up(self): """ Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points. max level is 100 :return: tuple[int, int, int, int], the new level, health points, attack power, and defense points after leveling up. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.level_up() (2, 120, 15, 8) """ def is_alive(self): """ Check if player is alive. :return: True if the hp is larger than 0, or False otherwise. >>> player_1 = RPGCharacter('player 1', 100, 10, 3) >>> player_1.is_alive() True """
def is_alive(self): return self.hp > 0
Check if player is alive.
ClassEval_74_sum
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): self.white_list = [] self.send_struct = {} self.receive_struct = {} def del_white_list(self, addr): """ Remove an address from the whitelist and do nothing if it does not exist :param addr: int, address to be deleted :return: new whitelist, return False if the address does not exist >>> server.add_white_list(88) >>> server.del_white_list(88) [] """ if addr not in self.white_list: return False else: self.white_list.remove(addr) return self.white_list def recv(self, info): """ Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it :param info: dict, information dictionary containing address and content :return: if successfully received, return the content of the infomation; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) abc """ if not isinstance(info, dict) or "addr" not in info or "content" not in info: return -1 addr = info["addr"] content = info["content"] if addr not in self.white_list: return False else: self.receive_struct = {"addr": addr, "content": content} return self.receive_struct["content"] def send(self, info): """ Send information containing address and content :param info: dict, information dictionary containing address and content :return: if successfully sent, return nothing; otherwise, return a string indicating an error message >>> server.send({"addr":66,"content":"ABC"}) self.send_struct = {"addr":66,"content":"ABC"} """ if not isinstance(info, dict) or "addr" not in info or "content" not in info: return "info structure is not correct" self.send_struct = {"addr": info["addr"], "content": info["content"]} def show(self, type): """ Returns struct of the specified type :param type: string, the type of struct to be returned, which can be 'send' or 'receive' :return: if type is equal to 'send' or 'receive', return the corresponding struct; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) >>> server.send({"addr":66,"content":"ABC"}) >>> server.show("send") {"addr":66,"content":"ABC"} """ if type == "send": return self.send_struct elif type == "receive": return self.receive_struct else: return False
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): """ Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary """ self.white_list = [] self.send_struct = {} self.receive_struct = {} def del_white_list(self, addr): """ Remove an address from the whitelist and do nothing if it does not exist :param addr: int, address to be deleted :return: new whitelist, return False if the address does not exist >>> server.add_white_list(88) >>> server.del_white_list(88) [] """ def recv(self, info): """ Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it :param info: dict, information dictionary containing address and content :return: if successfully received, return the content of the infomation; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) abc """ def send(self, info): """ Send information containing address and content :param info: dict, information dictionary containing address and content :return: if successfully sent, return nothing; otherwise, return a string indicating an error message >>> server.send({"addr":66,"content":"ABC"}) self.send_struct = {"addr":66,"content":"ABC"} """ def show(self, type): """ Returns struct of the specified type :param type: string, the type of struct to be returned, which can be 'send' or 'receive' :return: if type is equal to 'send' or 'receive', return the corresponding struct; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) >>> server.send({"addr":66,"content":"ABC"}) >>> server.show("send") {"addr":66,"content":"ABC"} """
def add_white_list(self, addr): if addr in self.white_list: return False else: self.white_list.append(addr) return self.white_list
Add an address to the whitelist and do nothing if it already exists
ClassEval_74_sum
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): self.white_list = [] self.send_struct = {} self.receive_struct = {} def add_white_list(self, addr): """ Add an address to the whitelist and do nothing if it already exists :param addr: int, address to be added :return: new whitelist, return False if the address already exists >>> server = Server() >>> server.add_white_list(88) [88] """ if addr in self.white_list: return False else: self.white_list.append(addr) return self.white_list def recv(self, info): """ Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it :param info: dict, information dictionary containing address and content :return: if successfully received, return the content of the infomation; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) abc """ if not isinstance(info, dict) or "addr" not in info or "content" not in info: return -1 addr = info["addr"] content = info["content"] if addr not in self.white_list: return False else: self.receive_struct = {"addr": addr, "content": content} return self.receive_struct["content"] def send(self, info): """ Send information containing address and content :param info: dict, information dictionary containing address and content :return: if successfully sent, return nothing; otherwise, return a string indicating an error message >>> server.send({"addr":66,"content":"ABC"}) self.send_struct = {"addr":66,"content":"ABC"} """ if not isinstance(info, dict) or "addr" not in info or "content" not in info: return "info structure is not correct" self.send_struct = {"addr": info["addr"], "content": info["content"]} def show(self, type): """ Returns struct of the specified type :param type: string, the type of struct to be returned, which can be 'send' or 'receive' :return: if type is equal to 'send' or 'receive', return the corresponding struct; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) >>> server.send({"addr":66,"content":"ABC"}) >>> server.show("send") {"addr":66,"content":"ABC"} """ if type == "send": return self.send_struct elif type == "receive": return self.receive_struct else: return False
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): """ Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary """ self.white_list = [] self.send_struct = {} self.receive_struct = {} def add_white_list(self, addr): """ Add an address to the whitelist and do nothing if it already exists :param addr: int, address to be added :return: new whitelist, return False if the address already exists >>> server = Server() >>> server.add_white_list(88) [88] """ def recv(self, info): """ Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it :param info: dict, information dictionary containing address and content :return: if successfully received, return the content of the infomation; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) abc """ def send(self, info): """ Send information containing address and content :param info: dict, information dictionary containing address and content :return: if successfully sent, return nothing; otherwise, return a string indicating an error message >>> server.send({"addr":66,"content":"ABC"}) self.send_struct = {"addr":66,"content":"ABC"} """ def show(self, type): """ Returns struct of the specified type :param type: string, the type of struct to be returned, which can be 'send' or 'receive' :return: if type is equal to 'send' or 'receive', return the corresponding struct; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) >>> server.send({"addr":66,"content":"ABC"}) >>> server.show("send") {"addr":66,"content":"ABC"} """
def del_white_list(self, addr): if addr not in self.white_list: return False else: self.white_list.remove(addr) return self.white_list
Remove an address from the whitelist and do nothing if it does not exist
ClassEval_74_sum
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): self.white_list = [] self.send_struct = {} self.receive_struct = {} def add_white_list(self, addr): """ Add an address to the whitelist and do nothing if it already exists :param addr: int, address to be added :return: new whitelist, return False if the address already exists >>> server = Server() >>> server.add_white_list(88) [88] """ if addr in self.white_list: return False else: self.white_list.append(addr) return self.white_list def del_white_list(self, addr): """ Remove an address from the whitelist and do nothing if it does not exist :param addr: int, address to be deleted :return: new whitelist, return False if the address does not exist >>> server.add_white_list(88) >>> server.del_white_list(88) [] """ if addr not in self.white_list: return False else: self.white_list.remove(addr) return self.white_list def send(self, info): """ Send information containing address and content :param info: dict, information dictionary containing address and content :return: if successfully sent, return nothing; otherwise, return a string indicating an error message >>> server.send({"addr":66,"content":"ABC"}) self.send_struct = {"addr":66,"content":"ABC"} """ if not isinstance(info, dict) or "addr" not in info or "content" not in info: return "info structure is not correct" self.send_struct = {"addr": info["addr"], "content": info["content"]} def show(self, type): """ Returns struct of the specified type :param type: string, the type of struct to be returned, which can be 'send' or 'receive' :return: if type is equal to 'send' or 'receive', return the corresponding struct; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) >>> server.send({"addr":66,"content":"ABC"}) >>> server.show("send") {"addr":66,"content":"ABC"} """ if type == "send": return self.send_struct elif type == "receive": return self.receive_struct else: return False
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): """ Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary """ self.white_list = [] self.send_struct = {} self.receive_struct = {} def add_white_list(self, addr): """ Add an address to the whitelist and do nothing if it already exists :param addr: int, address to be added :return: new whitelist, return False if the address already exists >>> server = Server() >>> server.add_white_list(88) [88] """ def del_white_list(self, addr): """ Remove an address from the whitelist and do nothing if it does not exist :param addr: int, address to be deleted :return: new whitelist, return False if the address does not exist >>> server.add_white_list(88) >>> server.del_white_list(88) [] """ def send(self, info): """ Send information containing address and content :param info: dict, information dictionary containing address and content :return: if successfully sent, return nothing; otherwise, return a string indicating an error message >>> server.send({"addr":66,"content":"ABC"}) self.send_struct = {"addr":66,"content":"ABC"} """ def show(self, type): """ Returns struct of the specified type :param type: string, the type of struct to be returned, which can be 'send' or 'receive' :return: if type is equal to 'send' or 'receive', return the corresponding struct; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) >>> server.send({"addr":66,"content":"ABC"}) >>> server.show("send") {"addr":66,"content":"ABC"} """
def recv(self, info): if not isinstance(info, dict) or "addr" not in info or "content" not in info: return -1 addr = info["addr"] content = info["content"] if addr not in self.white_list: return False else: self.receive_struct = {"addr": addr, "content": content} return self.receive_struct["content"]
Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it
ClassEval_74_sum
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): self.white_list = [] self.send_struct = {} self.receive_struct = {} def add_white_list(self, addr): """ Add an address to the whitelist and do nothing if it already exists :param addr: int, address to be added :return: new whitelist, return False if the address already exists >>> server = Server() >>> server.add_white_list(88) [88] """ if addr in self.white_list: return False else: self.white_list.append(addr) return self.white_list def del_white_list(self, addr): """ Remove an address from the whitelist and do nothing if it does not exist :param addr: int, address to be deleted :return: new whitelist, return False if the address does not exist >>> server.add_white_list(88) >>> server.del_white_list(88) [] """ if addr not in self.white_list: return False else: self.white_list.remove(addr) return self.white_list def recv(self, info): """ Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it :param info: dict, information dictionary containing address and content :return: if successfully received, return the content of the infomation; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) abc """ if not isinstance(info, dict) or "addr" not in info or "content" not in info: return -1 addr = info["addr"] content = info["content"] if addr not in self.white_list: return False else: self.receive_struct = {"addr": addr, "content": content} return self.receive_struct["content"] def show(self, type): """ Returns struct of the specified type :param type: string, the type of struct to be returned, which can be 'send' or 'receive' :return: if type is equal to 'send' or 'receive', return the corresponding struct; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) >>> server.send({"addr":66,"content":"ABC"}) >>> server.show("send") {"addr":66,"content":"ABC"} """ if type == "send": return self.send_struct elif type == "receive": return self.receive_struct else: return False
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): """ Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary """ self.white_list = [] self.send_struct = {} self.receive_struct = {} def add_white_list(self, addr): """ Add an address to the whitelist and do nothing if it already exists :param addr: int, address to be added :return: new whitelist, return False if the address already exists >>> server = Server() >>> server.add_white_list(88) [88] """ def del_white_list(self, addr): """ Remove an address from the whitelist and do nothing if it does not exist :param addr: int, address to be deleted :return: new whitelist, return False if the address does not exist >>> server.add_white_list(88) >>> server.del_white_list(88) [] """ def recv(self, info): """ Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it :param info: dict, information dictionary containing address and content :return: if successfully received, return the content of the infomation; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) abc """ def show(self, type): """ Returns struct of the specified type :param type: string, the type of struct to be returned, which can be 'send' or 'receive' :return: if type is equal to 'send' or 'receive', return the corresponding struct; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) >>> server.send({"addr":66,"content":"ABC"}) >>> server.show("send") {"addr":66,"content":"ABC"} """
def send(self, info): if not isinstance(info, dict) or "addr" not in info or "content" not in info: return "info structure is not correct" self.send_struct = {"addr": info["addr"], "content": info["content"]}
Send information containing address and content
ClassEval_74_sum
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): self.white_list = [] self.send_struct = {} self.receive_struct = {} def add_white_list(self, addr): """ Add an address to the whitelist and do nothing if it already exists :param addr: int, address to be added :return: new whitelist, return False if the address already exists >>> server = Server() >>> server.add_white_list(88) [88] """ if addr in self.white_list: return False else: self.white_list.append(addr) return self.white_list def del_white_list(self, addr): """ Remove an address from the whitelist and do nothing if it does not exist :param addr: int, address to be deleted :return: new whitelist, return False if the address does not exist >>> server.add_white_list(88) >>> server.del_white_list(88) [] """ if addr not in self.white_list: return False else: self.white_list.remove(addr) return self.white_list def recv(self, info): """ Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it :param info: dict, information dictionary containing address and content :return: if successfully received, return the content of the infomation; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) abc """ if not isinstance(info, dict) or "addr" not in info or "content" not in info: return -1 addr = info["addr"] content = info["content"] if addr not in self.white_list: return False else: self.receive_struct = {"addr": addr, "content": content} return self.receive_struct["content"] def send(self, info): """ Send information containing address and content :param info: dict, information dictionary containing address and content :return: if successfully sent, return nothing; otherwise, return a string indicating an error message >>> server.send({"addr":66,"content":"ABC"}) self.send_struct = {"addr":66,"content":"ABC"} """ if not isinstance(info, dict) or "addr" not in info or "content" not in info: return "info structure is not correct" self.send_struct = {"addr": info["addr"], "content": info["content"]} def show(self, type): if type == "send": return self.send_struct elif type == "receive": return self.receive_struct else: return False
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): """ Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary """ self.white_list = [] self.send_struct = {} self.receive_struct = {} def add_white_list(self, addr): """ Add an address to the whitelist and do nothing if it already exists :param addr: int, address to be added :return: new whitelist, return False if the address already exists >>> server = Server() >>> server.add_white_list(88) [88] """ def del_white_list(self, addr): """ Remove an address from the whitelist and do nothing if it does not exist :param addr: int, address to be deleted :return: new whitelist, return False if the address does not exist >>> server.add_white_list(88) >>> server.del_white_list(88) [] """ def recv(self, info): """ Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it :param info: dict, information dictionary containing address and content :return: if successfully received, return the content of the infomation; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) abc """ def send(self, info): """ Send information containing address and content :param info: dict, information dictionary containing address and content :return: if successfully sent, return nothing; otherwise, return a string indicating an error message >>> server.send({"addr":66,"content":"ABC"}) self.send_struct = {"addr":66,"content":"ABC"} """ def show(self, type): """ Returns struct of the specified type :param type: string, the type of struct to be returned, which can be 'send' or 'receive' :return: if type is equal to 'send' or 'receive', return the corresponding struct; otherwise, return False >>> server.recv({"addr":88,"content":"abc"}) >>> server.send({"addr":66,"content":"ABC"}) >>> server.show("send") {"addr":66,"content":"ABC"} """
def show(self, type): if type == "send": return self.send_struct elif type == "receive": return self.receive_struct else: return False
Returns struct of the specified type
ClassEval_75_sum
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): self.items = {} def remove_item(self, item, quantity=1): """ Subtract the specified quantity of item from the shopping list items :param item:string, Item to be subtracted in quantity :param quantity:int, Quantity to be subtracted :return:None >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.remove_item("apple", 3) self.items = {"apple":{"price":1, "quantity":2}} """ if item in self.items: self.items[item]['quantity'] -= quantity else: pass def view_items(self) -> dict: """ Return the current shopping list items :return:dict, the current shopping list items >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.remove_item("apple", 3) >>> shoppingcart.view_items() {"apple":{"price":1, "quantity":2}} """ return self.items def total_price(self) -> float: """ Calculate the total price of all items in the shopping list, which is the quantity of each item multiplied by the price :return:float, the total price of all items in the shopping list >>> shoppingcart = ShoppingCart() >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.add_item("banana", 2, 3) >>> shoppingcart.total_price() 11.0 """ return sum([item['quantity'] * item['price'] for item in self.items.values()])
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): """ Initialize the items representing the shopping list as an empty dictionary """ self.items = {} def remove_item(self, item, quantity=1): """ Subtract the specified quantity of item from the shopping list items :param item:string, Item to be subtracted in quantity :param quantity:int, Quantity to be subtracted :return:None >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.remove_item("apple", 3) self.items = {"apple":{"price":1, "quantity":2}} """ def view_items(self) -> dict: """ Return the current shopping list items :return:dict, the current shopping list items >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.remove_item("apple", 3) >>> shoppingcart.view_items() {"apple":{"price":1, "quantity":2}} """ def total_price(self) -> float: """ Calculate the total price of all items in the shopping list, which is the quantity of each item multiplied by the price :return:float, the total price of all items in the shopping list >>> shoppingcart = ShoppingCart() >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.add_item("banana", 2, 3) >>> shoppingcart.total_price() 11.0 """
def add_item(self, item, price, quantity=1): if item in self.items: self.items[item] = {'price': price, 'quantity': quantity} else: self.items[item] = {'price': price, 'quantity': quantity}
Add item information to the shopping list items, including price and quantity. The default quantity is 1
ClassEval_75_sum
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): self.items = {} def add_item(self, item, price, quantity=1): """ Add item information to the shopping list items, including price and quantity. The default quantity is 1 :param item: string, Item to be added :param price: float, The price of the item :param quantity:int, The number of items, defaults to 1 :return:None >>> shoppingcart = ShoppingCart() >>> shoppingcart.add_item("apple", 1, 5) self.items = {"apple":{"price":1, "quantity":5}} """ if item in self.items: self.items[item] = {'price': price, 'quantity': quantity} else: self.items[item] = {'price': price, 'quantity': quantity} def view_items(self) -> dict: """ Return the current shopping list items :return:dict, the current shopping list items >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.remove_item("apple", 3) >>> shoppingcart.view_items() {"apple":{"price":1, "quantity":2}} """ return self.items def total_price(self) -> float: """ Calculate the total price of all items in the shopping list, which is the quantity of each item multiplied by the price :return:float, the total price of all items in the shopping list >>> shoppingcart = ShoppingCart() >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.add_item("banana", 2, 3) >>> shoppingcart.total_price() 11.0 """ return sum([item['quantity'] * item['price'] for item in self.items.values()])
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): """ Initialize the items representing the shopping list as an empty dictionary """ self.items = {} def add_item(self, item, price, quantity=1): """ Add item information to the shopping list items, including price and quantity. The default quantity is 1 :param item: string, Item to be added :param price: float, The price of the item :param quantity:int, The number of items, defaults to 1 :return:None >>> shoppingcart = ShoppingCart() >>> shoppingcart.add_item("apple", 1, 5) self.items = {"apple":{"price":1, "quantity":5}} """ def view_items(self) -> dict: """ Return the current shopping list items :return:dict, the current shopping list items >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.remove_item("apple", 3) >>> shoppingcart.view_items() {"apple":{"price":1, "quantity":2}} """ def total_price(self) -> float: """ Calculate the total price of all items in the shopping list, which is the quantity of each item multiplied by the price :return:float, the total price of all items in the shopping list >>> shoppingcart = ShoppingCart() >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.add_item("banana", 2, 3) >>> shoppingcart.total_price() 11.0 """
def remove_item(self, item, quantity=1): if item in self.items: self.items[item]['quantity'] -= quantity else: pass
Subtract the specified quantity of item from the shopping list items
ClassEval_75_sum
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): self.items = {} def add_item(self, item, price, quantity=1): """ Add item information to the shopping list items, including price and quantity. The default quantity is 1 :param item: string, Item to be added :param price: float, The price of the item :param quantity:int, The number of items, defaults to 1 :return:None >>> shoppingcart = ShoppingCart() >>> shoppingcart.add_item("apple", 1, 5) self.items = {"apple":{"price":1, "quantity":5}} """ if item in self.items: self.items[item] = {'price': price, 'quantity': quantity} else: self.items[item] = {'price': price, 'quantity': quantity} def remove_item(self, item, quantity=1): """ Subtract the specified quantity of item from the shopping list items :param item:string, Item to be subtracted in quantity :param quantity:int, Quantity to be subtracted :return:None >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.remove_item("apple", 3) self.items = {"apple":{"price":1, "quantity":2}} """ if item in self.items: self.items[item]['quantity'] -= quantity else: pass def total_price(self) -> float: """ Calculate the total price of all items in the shopping list, which is the quantity of each item multiplied by the price :return:float, the total price of all items in the shopping list >>> shoppingcart = ShoppingCart() >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.add_item("banana", 2, 3) >>> shoppingcart.total_price() 11.0 """ return sum([item['quantity'] * item['price'] for item in self.items.values()])
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): """ Initialize the items representing the shopping list as an empty dictionary """ self.items = {} def add_item(self, item, price, quantity=1): """ Add item information to the shopping list items, including price and quantity. The default quantity is 1 :param item: string, Item to be added :param price: float, The price of the item :param quantity:int, The number of items, defaults to 1 :return:None >>> shoppingcart = ShoppingCart() >>> shoppingcart.add_item("apple", 1, 5) self.items = {"apple":{"price":1, "quantity":5}} """ def remove_item(self, item, quantity=1): """ Subtract the specified quantity of item from the shopping list items :param item:string, Item to be subtracted in quantity :param quantity:int, Quantity to be subtracted :return:None >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.remove_item("apple", 3) self.items = {"apple":{"price":1, "quantity":2}} """ def total_price(self) -> float: """ Calculate the total price of all items in the shopping list, which is the quantity of each item multiplied by the price :return:float, the total price of all items in the shopping list >>> shoppingcart = ShoppingCart() >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.add_item("banana", 2, 3) >>> shoppingcart.total_price() 11.0 """
def view_items(self) -> dict: return self.items
Return the current shopping list items
ClassEval_75_sum
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): self.items = {} def add_item(self, item, price, quantity=1): """ Add item information to the shopping list items, including price and quantity. The default quantity is 1 :param item: string, Item to be added :param price: float, The price of the item :param quantity:int, The number of items, defaults to 1 :return:None >>> shoppingcart = ShoppingCart() >>> shoppingcart.add_item("apple", 1, 5) self.items = {"apple":{"price":1, "quantity":5}} """ if item in self.items: self.items[item] = {'price': price, 'quantity': quantity} else: self.items[item] = {'price': price, 'quantity': quantity} def remove_item(self, item, quantity=1): """ Subtract the specified quantity of item from the shopping list items :param item:string, Item to be subtracted in quantity :param quantity:int, Quantity to be subtracted :return:None >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.remove_item("apple", 3) self.items = {"apple":{"price":1, "quantity":2}} """ if item in self.items: self.items[item]['quantity'] -= quantity else: pass def view_items(self) -> dict: """ Return the current shopping list items :return:dict, the current shopping list items >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.remove_item("apple", 3) >>> shoppingcart.view_items() {"apple":{"price":1, "quantity":2}} """ return self.items def total_price(self) -> float: return sum([item['quantity'] * item['price'] for item in self.items.values()])
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): """ Initialize the items representing the shopping list as an empty dictionary """ self.items = {} def add_item(self, item, price, quantity=1): """ Add item information to the shopping list items, including price and quantity. The default quantity is 1 :param item: string, Item to be added :param price: float, The price of the item :param quantity:int, The number of items, defaults to 1 :return:None >>> shoppingcart = ShoppingCart() >>> shoppingcart.add_item("apple", 1, 5) self.items = {"apple":{"price":1, "quantity":5}} """ def remove_item(self, item, quantity=1): """ Subtract the specified quantity of item from the shopping list items :param item:string, Item to be subtracted in quantity :param quantity:int, Quantity to be subtracted :return:None >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.remove_item("apple", 3) self.items = {"apple":{"price":1, "quantity":2}} """ def view_items(self) -> dict: """ Return the current shopping list items :return:dict, the current shopping list items >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.remove_item("apple", 3) >>> shoppingcart.view_items() {"apple":{"price":1, "quantity":2}} """ def total_price(self) -> float: """ Calculate the total price of all items in the shopping list, which is the quantity of each item multiplied by the price :return:float, the total price of all items in the shopping list >>> shoppingcart = ShoppingCart() >>> shoppingcart.add_item("apple", 1, 5) >>> shoppingcart.add_item("banana", 2, 3) >>> shoppingcart.total_price() 11.0 """
def total_price(self) -> float: return sum([item['quantity'] * item['price'] for item in self.items.values()])
Calculate the total price of all items in the shopping list, which is the quantity of each item multiplied by the price
ClassEval_76_sum
class SignInSystem: """ This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users. """ def __init__(self): self.users = {} def sign_in(self, username): """ Sign in a user if the user was in the self.users and change the state to True. :param username: str, the username to be signed in. :return: bool, True if the user is signed in successfully, False if the user does not exist. >>> signInSystem.sign_in("mike") True >>> signInSystem.sign_in("mik") False """ if username not in self.users: return False else: self.users[username] = True return True def check_sign_in(self, username): """ Check if a user is signed in. :param username: str, the username to be checked. :return: bool, True if the user is signed in, False if the user does not exist or is not signed in. >>> signInSystem.check_sign_in("jack") False >>> signInSystem.add_user("jack") >>> signInSystem.check_sign_in("jack") >>> signInSystem.sign_in("jack") >>> signInSystem.check_sign_in("jack") True """ if username not in self.users: return False else: if self.users[username]: return True else: return False def all_signed_in(self): """ Check if all users are signed in. :return: bool, True if all users are signed in, False otherwise. >>> signInSystem.add_user("jack") True >>> signInSystem.sign_in("jack") >>> signInSystem.all_signed_in() True """ if all(self.users.values()): return True else: return False def all_not_signed_in(self): """ Get a list of usernames that are not signed in. :return: list[str], a list of usernames that are not signed in. >>> signInSystem = SignInSystem() >>> signInSystem.add_user("a") True >>> signInSystem.add_user("b") True >>> signInSystem.all_not_signed_in() ['a', 'b'] """ not_signed_in_users = [] for username, signed_in in self.users.items(): if not signed_in: not_signed_in_users.append(username) return not_signed_in_users
class SignInSystem: """ This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users. """ def __init__(self): """ Initialize the sign-in system. """ self.users = {} def sign_in(self, username): """ Sign in a user if the user was in the self.users and change the state to True. :param username: str, the username to be signed in. :return: bool, True if the user is signed in successfully, False if the user does not exist. >>> signInSystem.sign_in("mike") True >>> signInSystem.sign_in("mik") False """ def check_sign_in(self, username): """ Check if a user is signed in. :param username: str, the username to be checked. :return: bool, True if the user is signed in, False if the user does not exist or is not signed in. >>> signInSystem.check_sign_in("jack") False >>> signInSystem.add_user("jack") >>> signInSystem.check_sign_in("jack") >>> signInSystem.sign_in("jack") >>> signInSystem.check_sign_in("jack") True """ def all_signed_in(self): """ Check if all users are signed in. :return: bool, True if all users are signed in, False otherwise. >>> signInSystem.add_user("jack") True >>> signInSystem.sign_in("jack") >>> signInSystem.all_signed_in() True """ def all_not_signed_in(self): """ Get a list of usernames that are not signed in. :return: list[str], a list of usernames that are not signed in. >>> signInSystem = SignInSystem() >>> signInSystem.add_user("a") True >>> signInSystem.add_user("b") True >>> signInSystem.all_not_signed_in() ['a', 'b'] """
def add_user(self, username): if username in self.users: return False else: self.users[username] = False return True
Add a user to the sign-in system if the user wasn't in the self.users. And the initial state is False.