How to write the Fibonacci Sequence?

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

    def fib(x, y, n):
        if n < 1: 
            return x, y, n
        else: 
            return fib(y, x + y, n - 1)
    
    print fib(0, 1, 4)
    (3, 5, 0)
    
    #
    def fib(x, y, n):
        if n > 1:
            for item in fib(y, x + y, n - 1):
                yield item
        yield x, y, n
    
    f = fib(0, 1, 12)
    f.next()
    (89, 144, 1)
    f.next()[0]
    55
    

提交回复
热议问题