How to write the Fibonacci Sequence?

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

    These all look a bit more complicated than they need to be. My code is very simple and fast:

    def fibonacci(x):
    
        List = []
        f = 1
        List.append(f)
        List.append(f) #because the fibonacci sequence has two 1's at first
        while f<=x:
            f = List[-1] + List[-2]   #says that f = the sum of the last two f's in the series
            List.append(f)
        else:
            List.remove(List[-1])  #because the code lists the fibonacci number one past x. Not necessary, but defines the code better
            for i in range(0, len(List)):
            print List[i]  #prints it in series form instead of list form. Also not necessary
    

提交回复
热议问题