简单的 fizzbuzz 问题

Simple fizzbuzz issue

我正在做一些 CodeEval 挑战,并且正在做 fizzbuzz 挑战。现在我确定这是一个非常简单的问题,我只是在看它,但我在 python 中这样做,我对它还很陌生,只是在学习。

Players generally sit in a circle. The first player says the number “1”, and each player says next number in turn. However, any number divisible by X (for example, three) is replaced by the word fizz, and any divisible by Y (for example, five) by the word buzz. Numbers divisible by both become fizz buzz. A player who hesitates, or makes a mistake is eliminated from the game.

Write a program that prints out the final series of numbers where those divisible by X, Y and both are replaced by “F” for fizz, “B” for buzz and “FB” for fizz buzz.

Input sample:

Your program should accept a file as its first argument. The file contains multiple separated lines; each line contains 3 numbers that are space delimited. The first number is the first divider (X), the second number is the second divider (Y), and the third number is how far you should count (N). You may assume that the input file is formatted correctly and the numbers are valid positive integers.

For example:

3 5 10

2 7 15

Output sample:

1 2 F 4 B F 7 8 F B

1 F 3 F 5 F B F 9 F 11 F 13 FB 15

Print out the series 1 through N replacing numbers divisible by X with “F”, numbers divisible by Y with “B” and numbers divisible by both with “FB”. Since the input file contains multiple sets of values, your output should print out one line per set. Ensure that there are no trailing empty spaces in each line you print.

Constraints:

The number of test cases ≤ 20

"X" is in range [1, 20]

"Y" is in range [1, 20]

"N" is in range [21, 100]

当我 运行 我的程序时,我从文件中得到以下输出:

1
1

我的程序没有运行正确地通过文件,我做错了什么?

def fizzbuzz(num_range, div_low=3, div_high=5):
    for x in num_range:
        if x % div_low == 0:
            return "F"
        elif x % div_high == 0:
            return "B"
        elif x % div_low == 0 and x % div_high == 0:
            return "FB"
        else:
            return x

if __name__ == '__main__':
    with open("numbers.txt", "r") as nums:
        for i in nums.readlines():
            high = int(i.rstrip().split(" ")[1])
            low = int(i.rstrip().split(" ")[0])
            nums = range(1, int(i.rstrip().split(" ")[2]))
            print(fizzbuzz(nums, low, high))

您的函数 returns 在 x 的第一个值上。您需要在循环中建立一串响应,然后 return 该字符串仅 完成循环后。

另请注意,您的逻辑永远不会 return "FB",因为 "F" 和 [=] 都在 else 子句中25=].

series = ""
for x in num_range:
    if x % div_low == 0 and x % div_high == 0:
        series += "FB"
    elif x % div_low == 0:
        series += "F"
    elif x % div_high == 0:
        series += "B"
    else:
        series += str(x)

return series

由于您 return 是一个字符串,因此您必须先转换数字,然后再附加它。我还没有为你解决所有问题,但这应该会让你动起来。