斐波那契数的迭代算法 [英] An iterative algorithm for Fibonacci numbers
问题描述
我对斐波那契数的迭代算法感兴趣,因此我在Wiki上找到了公式...它看起来很直接,所以我在Python中尝试了它...编译没有问题,公式看起来也不错。 ..不确定为什么会给出错误的输出...我执行不正确吗?
I am interested in an iterative algorithm for Fibonacci numbers, so I found the formula on wiki...it looks straight forward so I tried it in Python...it doesn't have a problem compiling and formula looks right...not sure why its giving the wrong output...did I not implement it right ?
def fib (n):
if( n == 0):
return 0
else:
x = 0
y = 1
for i in range(1,n):
z = (x + y)
x = y
y = z
return y
for i in range(10):
print (fib(i))
输出
0
无
1
1
1
1
1
1
0
None
1
1
1
1
1
1
推荐答案
问题是您的返回y
在您的功能循环。因此,在第一次迭代之后,它将已经停止并返回第一个值:1.除非 n
为0时,否则函数将返回 0
本身,并且在 n
为1的情况下,for循环甚至不会迭代一次,并且没有 return
正在执行(因此 None
返回值)。
The problem is that your return y
is within the loop of your function. So after the first iteration, it will already stop and return the first value: 1. Except when n
is 0, in which case the function is made to return 0
itself, and in case n
is 1, when the for loop will not iterate even once, and no return
is being execute (hence the None
return value).
要解决此问题,只需将返回y
移出循环即可。
To fix this, just move the return y
outside of the loop.
以KebertX的示例为例,这是我亲自在Python中制作的解决方案。当然,如果要处理许多斐波那契值,您甚至可能希望将这两种解决方案结合起来并为数字创建缓存。
Following KebertX’s example, here is a solution I would personally make in Python. Of course, if you were to process many Fibonacci values, you might even want to combine those two solutions and create a cache for the numbers.
def f(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a + b
return a
这篇关于斐波那契数的迭代算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!