An iterative algorithm for Fibonacci numbers

后端 未结 13 1152
野性不改
野性不改 2020-11-28 10:37

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 prob

13条回答
  •  情话喂你
    2020-11-28 11:13

    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
    

提交回复
热议问题