How to write the Fibonacci Sequence?

前端 未结 30 2335
醉酒成梦
醉酒成梦 2020-11-22 00:32

I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1

30条回答
  •  礼貌的吻别
    2020-11-22 01:25

    Fibonacci sequence is: 1, 1, 2, 3, 5, 8, ....

    That is f(1) = 1, f(2) = 1, f(3) = 2, ..., f(n) = f(n-1) + f(n-2).

    My favorite implementation (simplest and yet achieves a light speed in compare to other implementations) is this:

    def fibonacci(n):
        a, b = 0, 1
        for _ in range(1, n):
            a, b = b, a + b
        return b
    

    Test

    >>> [fibonacci(i) for i in range(1, 10)]
    [1, 1, 2, 3, 5, 8, 13, 21, 34]
    

    Timing

    >>> %%time
    >>> fibonacci(100**3)
    CPU times: user 9.65 s, sys: 9.44 ms, total: 9.66 s
    Wall time: 9.66 s
    

    Edit: an example visualization for this implementations.

提交回复
热议问题