How to write the Fibonacci Sequence?

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

    Using for loop and print just the result

    def fib(n:'upto n number')->int:
        if n==0:
            return 0
        elif n==1:
            return 1
        a=0
        b=1
        for i in range(0,n-1):
            b=a+b
            a=b-a
        return b
    

    Result

    >>>fib(50)
    12586269025
    >>>>
    >>> fib(100)
    354224848179261915075
    >>> 
    

    Print the list containing all the numbers

    def fib(n:'upto n number')->int:
        l=[0,1]
        if n==0:
            return l[0]
        elif n==1:
            return l
        a=0
        b=1
        for i in range(0,n-1):
            b=a+b
            a=b-a
            l.append(b)
        return l
    

    Result

    >>> fib(10)
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
    

提交回复
热议问题