我想将所有斐波那契数字打印到索引为n的数字,但是我的代码仅打印第n个斐波那契数字。请告诉我我做错了什么,应该怎么做?
n = int(input('Enter a number: '))
def fibonacci(n):
if n < 0:
print("Error(enter a positive integer)")
elif n == 1:
return 0
elif n == 2:
return 1
else:
for i in range(n):
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(n))
for i in range(n):
return fibonacci(n-1) + fibonacci(n-2)
此for循环是没有意义的,因为您是第一次迭代return
。您只应该在这里完全摆脱for循环。
这也不是您要重复的部分。相反,您要重复print()
语句:
for i in range(n):
print(fibonacci(i)) # You want the i-th fibonacci number
这将为您提供所需的结果,但这是一种非常低效的方法。对于较大的n
值,您将以指数次数计算第i个斐波那契数。
如果您很聪明并且n
大于1,您可能想以更复杂的方式使用reduce
:
from functools import reduce
def fibonacci(n):
return reduce(lambda x,y: x+[x[-1]+x[-2]], [[0,1]]+[[0]]*(n-2))
这是n=5
的工作方式:
[[0,1], [0], [0], [0]] ->
[[0,1,1], [0], [0]] ->
[[0,1,1,2], [0]] ->
[[0,1,1,2,3]] ->
stops here and returns [0,1,1,2,3]