How to write the Fibonacci Sequence?

前端 未结 30 2323
醉酒成梦
醉酒成梦 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:12

    there is a very easy method to realize that!

    you can run this code online freely by using http://www.learnpython.org/

    # Set the variable brian on line 3!
    
    def fib(n):
    """This is documentation string for function. It'll be available by fib.__doc__()
    Return a list containing the Fibonacci series up to n."""
    result = []
    a = 0
    b = 1
    while a < n:
        result.append(a)  # 0 1 1 2 3 5  8  (13) break
        tmp_var = b       # 1 1 2 3 5 8  13
        b = a + b         # 1 2 3 5 8 13 21
        a = tmp_var       # 1 1 2 3 5 8  13
        # print(a)
    return result
    
    print(fib(10))
    # result should be this: [0, 1, 1, 2, 3, 5, 8]
    

提交回复
热议问题