示例#1
0
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')
示例#3
0
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('--------------------------------------------------')
示例#4
0
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}!')
示例#5
0
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)
示例#7
0
    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
示例#8
0
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)
示例#9
0
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)
示例#10
0
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)
示例#11
0
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)
示例#12
0
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
示例#13
0
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))
示例#14
0
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)
示例#15
0
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
示例#16
0
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"]
示例#17
0
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"]
示例#18
0
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
示例#20
0
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)
示例#21
0
文件: console.py 项目: sgzmd/pilights
    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))
示例#22
0
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)
示例#23
0
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"]
示例#24
0
def take_int_answer() -> int:
    """Take int answer from user."""
    return prompt.integer('Your answer: ')
示例#25
0
def test_integer():
    assert prompt.integer(empty=True) is None
示例#26
0
def test_integer(input_patch):
    input_patch.do("1")
    assert prompt.integer() == 1
示例#27
0
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))
示例#28
0
def test_integer():
    assert prompt.integer(empty=True) is None
    assert prompt.integer(default=1) is 1