def report_airports_with_highest_cancellation_rate(): """List airports with highest cancellation rates""" context = ReportContext() context.year = prompt.integer("Year: ") context.limit = prompt.integer("Limit: ") print("IATA\tAirport Name\t\t\t\tCancelled %") print("-" * 60) impl().report_airports_with_highest_cancellation_rate(context)
def is_power_of_three(): number = prompt.integer('Input number to define') power_req = prompt.integer('Input required power') counter = 1 while counter < number: counter *= power_req if counter == number: print('Number is power') else: print('Number is not power')
def play_HQ(source='test', save=False): n_question = 0 n_correct_answer = 0 if save: saveFile(time.strftime("%a %d %b %Y %H:%M:%S")) play = prompt.integer('\nNew question : ') while (play): s = "" n_question += 1 list_req = getRequest(source) if len(list_req): print('\nQ', n_question, '.', list_req[0]['q'], '?\n') s += 'Q' + str(n_question) + '. ' + list_req[0]['q'] + ' ?' # change all structure # change list_req into (question, list_answer #getResults_Wikipedia(list_req) stats = getStats_Google(list_req) answer = list_req[max(stats.items(), key=operator.itemgetter(1))[0] - 1]['a'] for n, req in enumerate(list_req): print(n + 1, '. ', req['a'], '->', stats[n + 1]) s += '\n' + str(n + 1) + '. ' + str(req['a']) + ' -> ' + str( stats[n + 1]) print('\nAnswer :', answer) s += '\n\nAnswer : ' + answer correct_answer = prompt.integer('The correct answer is : ') if correct_answer < 1 or correct_answer > 3: correct_answer = 1 correct_answer = list_req[correct_answer - 1]['a'] s += '\nThe correct answer is : ' + correct_answer if answer == correct_answer: n_correct_answer += 1 if save: saveFile(s) play = prompt.integer('\nNew question : ') if save: saveFile('Accuracy : ' + str(n_correct_answer) + ' / ' + str(n_question)) saveFile('--------------------------------------------------')
def start(game): greeting = 'Welcome to the Brain Games!' print(greeting) print(game.DESCRIPTION) print('') name = get_user_name() counter = 0 while counter < 3: question, correct_answer = game.start_round() if type(correct_answer) == int: answer = integer(question) else: answer = string(question) if answer != correct_answer: print(f'Your answer: {answer}') print(f"'{answer}' is wrong answer ;(." f" Correct answer was '{correct_answer}'") print(f"Let's try again, {name}!") break print(f'Your answer: {answer}') print('Correct!') counter += 1 if counter == 3: print(f'Congratulations, {name}!')
def run(name=None, right_answer=None, question=None): print(f"Hello,{name}!") def wrong(): return print("You are wrong!") def invalid(): return print("Invalid") def correct(): return print("Correct!") times_played = 0 user_right_answer = 0 num = 0 while times_played < 3: print("Question:{}".format(question[num])) if type(right_answer[0]) == int: user_answer = prompt.integer("Your answer: ") else: user_answer = prompt.string("Your answer: ") if right_answer[num] == user_answer: correct() user_right_answer += 1 times_played += 1 num += 1 elif right_answer[num] != user_answer: wrong() times_played += 1 num += 1 else: invalid() if user_right_answer == 3: print(f"Congratulations, {name}!")
def game(): """ Runs single game episode. Returns: tuple """ start = random.choice(range(1, 51)) step = random.choice(range(1, 11)) progression = [i for i in range(start, start + step * 11, step)] missing_num = random.choice(progression) question = "" for i in progression: if i == missing_num: question += ".." else: question += str(i) if i != progression[-1]: question += " " print('What number is missing in progression?') print(f'Question: {question}') user_answer = prompt.integer('Your answer: ') if user_answer == missing_num: return (True, user_answer, missing_num) else: return (False, user_answer, missing_num)
def try_parse(self, host, uris, anime, searching=True): host = self.host parse = self.beautifulSoup_page(host + uris[0] + anime) # simple_msg('{}{}{}'.format(host, uris[0], anime), tab=True) if (self.parse_name(parse)).strip() in [ u'A página não foi encontrada', 'Animes' ]: if len(uris[1::]) > 0: return self.try_parse(host, uris[1::], anime) else: error_msg('Page < {} > not found!'.format(anime), True) if searching: info_msg('Trying to find the anime < {} > '.format(anime), True) from .findAnime import FindAnime animes_names = names_to_try(anime) for anime_name in animes_names: search = FindAnime(anime_name).parse_search() if search: # info_msg(str(search), True) if search.get(slugify(anime), False): anime_name = search.get(slugify(anime), anime) else: import prompt i = 0 print("") for search_keys, search_options in search.items( ): simple_msg('\t[ {} ]:'.format(i), 'green', '{}'.format(search_keys), tab=True) i += 1 simple_msg('\tAny another number:', 'yellow', 'Cancel choice', True) choice = prompt.integer( prompt="\t\tPlease enter a number: ") keys_in_list = list(search.keys()) if choice >= len(search): return False anime_name = search[keys_in_list[choice]] return self.try_parse(host, [''], anime_name, False) return False else: return parse
def get_question_answer(): num1 = randint(1, 99) num2 = randint(1, 99) print('Question: {} {}'.format(str(num1), str(num2))) answer = prompt.integer('Your answer: ') correct_answer = get_nod(num1, num2) return (answer == correct_answer, answer, correct_answer)
def main(): path_to_file = prompt.string('Введите путь к файлу .wav-формата: ') phone = prompt.integer('Введите номер телефона: ') record_to_db = prompt.string('Записать результат в базу данных? yes/no: ') while record_to_db not in ('yes', 'no'): record_to_db = prompt.string( 'Записать результат в базу данных? yes/no:') stage = prompt.integer( 'Введите этап распознавания\n' '1 - автоответчик/человек, 2 - положительный/отрицательный ответ человека: ' ) while stage not in (1, 2): stage = prompt.integer( 'Введите этап распознавания\n' '1 - автоответчик/человек, 2 - положительный/отрицательный ответ человека: ' ) analyze_response(path_to_file, phone, record_to_db, stage)
def report_airport_metrics(): """List metrics for all airports""" context = ReportContext() context.year = prompt.integer("Year: ") print("IATA\tAirport Name\t\t\t\t Total\tCancelled %\tDiverted %") print("-" * 91) impl().report_airport_metrics(context)
def report_airports_near_location(): """List airports near specified geolocation""" context = ReportContext() context.location = (prompt.real("Latitude: "), prompt.real("Longitude: ")) context.distance = prompt.integer("Distance (in miles): ") print("IATA\tAirport Name\t\t\t\t\tState\tCity\t\t\t\tDistance") print("-" * 105) impl().report_airports_near_location(context)
def choose_game(games=None): if games is None: return print("Choose a game: ") for game_index, game in enumerate(games): print(f"{game_index}. {game.TITLE}") choice = None while choice is None or choice > len(games) - 1 or choice < 0: choice = prompt.integer(prompt="Your choice: ") game = games[choice] return game
def get_question_answer(): num1 = int(random() * 100) num2 = int(random() * 100) operator = choice(('+', '-', '*')) print('Question: {} {} {}'.format(str(num1), operator, str(num2))) answer = prompt.integer('Your answer: ') if operator == '+': return (((num1 + num2) == answer), answer, (num1 + num2)) if operator == '-': return (((num1 - num2) == answer), answer, (num1 - num2)) if operator == '*': return (((num1 * num2) == answer), answer, (num1 * num2))
def get_question_answer(): progression_length = randint(5, 10) progression_start = randint(0, 100) progression_step = randint(1, 5) missing_element = randint(0, (progression_length - 1)) progression = [progression_start] for i in range(1, progression_length): progression.append(progression[i - 1] + progression_step) correct_answer = progression[missing_element] progression[missing_element] = '..' print('Question: ', end='') print(*progression) answer = prompt.integer('Your answer: ') return (answer == correct_answer, answer, correct_answer)
def main(): print('Find the greatest common divisor of given numbers.') a = random.randint(0, 100) b = random.randint(0, 100) print(f'Question: {a} {b}') answer = prompt.integer('Your answer: ') gcd = find_gcd(a, b) if answer == gcd: print('Correct!') return 0 else: print("'{}' is wrong answer ;(. Correct answer was '{}'.\n" "".format(answer, gcd)) return 1
def progression_game(): prepare = common.prepare() games_counter = prepare["games_counter"] name = prepare["name"] right_answers = prepare["right_answers"] print("What number is missing in the progression?") while games_counter: progression = [i for i in range(0, 50, random.randint(2, 10))] index = random.randint(0, len(progression) - 1) right_answer = progression[index] progression[index] = ".." print("Question: ", *progression) gamer_answer = prompt.integer("Your answer: ") result = common.result(gamer_answer, right_answer, games_counter, right_answers, name) games_counter = result["games_counter"] right_answers = result["right_answers"]
def gcd_game(): prepare = common.prepare() games_counter = prepare["games_counter"] name = prepare["name"] right_answers = prepare["right_answers"] print("Find the greatest common divisor of given numbers.") while games_counter: first_operand = random.randint(0, 100) second_operand = random.randint(0, 100) question = f"{first_operand} {second_operand}" right_answer = common.gcd(first_operand, second_operand) print(f"Question: {question}") gamer_answer = prompt.integer("Your answer: ") result = common.result(gamer_answer, right_answer, games_counter, right_answers, name) games_counter = result["games_counter"] right_answers = result["right_answers"]
def main(): print('What is the result of the expression?') a = random.randint(0, 100) b = random.randint(0, 100) action = random.choice(['-', '+', '*']) if action == '-': correct_answer = a - b elif action == '+': correct_answer = a + b else: correct_answer = a * b print(f'Question: {a} {action} {b}') answer = prompt.integer('Your answer: ') if answer == correct_answer: print('Correct!') return 0 else: print("'{}' is wrong answer ;(. Correct answer was '{}'.\n" "".format(answer, correct_answer)) return 1
def main(): first_element = random.randint(0, 100) progression_length = random.randint(5, 10) hidden_elem_index = random.randint(0, progression_length - 1) increment = random.randint(1, 10) progression = [first_element] for i in range(1, progression_length): progression.append(first_element + increment * i) print('What number is missing in the progression?') print('Question: ', end='') for element in progression: if progression.index(element) != hidden_elem_index: print(element, end=' ') else: print('..', end=' ') answer = prompt.integer('\nYour answer: ') if answer == progression[hidden_elem_index]: print('Correct!') return 0 else: print("'{}' is wrong answer ;(. Correct answer was '{}'.\n" "".format(answer, progression[hidden_elem_index])) return 1
def game(): """ Runs single game episode. Returns: tuple """ num_1 = random.choice(range(1, 101)) num_2 = random.choice(range(1, 101)) print('Find the greatest common divisor of given numbers.') print(f'Question: {num_1} {num_2}') while num_1 != 0 and num_2 != 0: if num_1 > num_2: num_1 = num_1 % num_2 else: num_2 = num_2 % num_1 gcd = num_1 + num_2 user_answer = prompt.integer('Your answer: ') if user_answer == gcd: return (True, user_answer, gcd) else: return (False, user_answer, gcd)
def run(self) -> None: while True: command = prompt.string("Enter command (stop/delay/algo): ") if command == 'stop': logging.info("Stopping the program") self._q.put_nowait( ControlMessage(ControlMessage.MessageType.STOP)) return elif command == 'algo': algo_names = ", ".join(algos.algo_by_name.keys()) new_algo_name = prompt.string( f"Select new algorithm, one of {algo_names}: ") logging.info("Requesting algorithm change to %s", new_algo_name) self._q.put_nowait( ControlMessage(ControlMessage.MessageType.CHANGE_ALGO, new_algo_name)) elif command == 'delay': new_delay = prompt.integer("Enter new delay, ms: ") self._q.put_nowait( ControlMessage(ControlMessage.MessageType.CHANGE_DELAY, new_delay))
def game(): """ Runs a single episode of a game. Returns: tuple """ num_1 = random.choice(range(0, 101)) num_2 = random.choice(range(0, 101)) operator = random.choice(['*', '+', '-']) print('What is the result of the expression?') print(f'Question: {num_1} {operator} {num_2}') user_answer = prompt.integer('Your answer: ') if operator == '+': correct_answer = num_1 + num_2 elif operator == '-': correct_answer = num_1 - num_2 else: correct_answer = num_1 * num_2 if user_answer == correct_answer: return (True, user_answer, correct_answer) else: return (False, user_answer, correct_answer)
def calc_game(): prepare = common.prepare() games_counter = prepare["games_counter"] name = prepare["name"] right_answers = prepare["right_answers"] print("What is the result of the expression?") operator_seq = "+-*" while games_counter: operator_str = random.choice(operator_seq) first_operand = random.randint(0, 100) second_operand = random.randint(0, 100) question = f"{first_operand} {operator_str} {second_operand}" if operator_str == "+": right_answer = first_operand + second_operand if operator_str == "-": right_answer = first_operand - second_operand if operator_str == "*": right_answer = first_operand * second_operand print(f"Question: {question}") gamer_answer = prompt.integer("Your answer: ") result = common.result(gamer_answer, right_answer, games_counter, right_answers, name) games_counter = result["games_counter"] right_answers = result["right_answers"]
def take_int_answer() -> int: """Take int answer from user.""" return prompt.integer('Your answer: ')
def test_integer(): assert prompt.integer(empty=True) is None
def test_integer(input_patch): input_patch.do("1") assert prompt.integer() == 1
import prompt def t(num): response = ('Fizz' if num % 3 == 0 else '') + ('Buzz' if num % 5 == 0 else '') return str(num) if not response else response def fizz_buzz(start, stop): return ' '.join(map(t, range(start, stop + 1))) start = prompt.integer('enter start: ') stop = prompt.integer('enter stop: ') print(fizz_buzz(start, stop))
def test_integer(): assert prompt.integer(empty=True) is None assert prompt.integer(default=1) is 1