在单行上打印Fibonacci序列

时间:2018-06-07 15:01:32

标签: python python-3.x

n = int(input('How many terms you want to Generate: '))

i = 1
j = 1
k = 0
print(i,j)
while k < n:
    j += i
    print(j, end=" ")
    i = j-i
    k += 1

前两行打印在第一行,其他所有打印在第二行。我试图在一个列表中附加所有内容,但它给了我错误。

1 个答案:

答案 0 :(得分:1)

您在循环中正确地将参数end=" "提供给print,但在循环之前忘记了print

n = int(input('How many terms you want to Generate: '))

i = 1
j = 1
k = 0
print(i, j, end=" ")
while k < n:
    j += i
    print(j, end=" ")
    i = j-i
    k += 1

输出:

How many terms you want to Generate: 5
1 1 2 3 5 8 13

尽管如此,请注意您的解决方案仍然无法打印正确数量的元素。

改进

使用生成器存在更多的elegants解决方案,它们非常适合表示无限序列。

import itertools

def fib():
    a, b = 1, 1
    while True:
        yield a
        a, b = b, a + b

n = int(input('How many terms you want to Generate: '))
print(*itertools.islice(fib(), n))

输出:

How many terms you want to Generate: 5
1 1 2 3 5