一个迭代算法Fibonacci数 [英] a iterative algorithm for fibonacci numbers

查看:236
本文介绍了一个迭代算法Fibonacci数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感兴趣的一个迭代算法Fibonacci数,所以我发现维基公式...它看起来直截了当,所以我想它在Python ......它没有一个问题,编译和公式是正确的。 ..not知道为什么它给了错误的输出......我才没有实现它的权利?

 高清FIB(N):
    如果(N == 0):
        返回0
    其他:
        X = 0
        Y = 1
        因为我在范围内(1,N):
            Z =(X + Y)
            X = Y
            Y = Z
            返回是

对于i在范围(10):
    打印(FIB(I))
 

输出

  0
无
1
1
1
1
1
1
1
1
1
1
 

解决方案

现在的问题是,你的返回是是函数的循环中。因此在第一次迭代之后,将已经停止,并返回所述第一值:1.除非 N 为0,在这种情况下,功能是由以返回 0 本身,如果 N 1,当循环不会重复,甚至一次也没有返回正在被执行(因此返回值)。

要解决这个问题,只要移动返回是的循环之外。

替代实施

随着KebertX的例子,这里是一个解决方案,我会亲自做在Python。当然,如果你要处理许多斐波纳契值,你甚至可能要合并这两个解决方案,并为数字的高速缓存。

 高清F(N):
    的a,b = 0,1
    对于i在范围(0,n)的:
        的a,b = B,A + B
    返回
 

I am interested in a 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))

output

0
None
1
1
1
1
1
1
1
1
1
1

解决方案

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).

To fix this, just move the return y outside of the loop.

Alternative implementation

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

这篇关于一个迭代算法Fibonacci数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆