Python Fibonacci Generator

前端 未结 17 1206
别那么骄傲
别那么骄傲 2020-11-27 20:59

I need to make a program that asks for the amount of Fibonacci numbers printed and then prints them like 0, 1, 1, 2... but I can\'t get it to work. My code looks the followi

相关标签:
17条回答
  • 2020-11-27 21:28
    def fibonacci(n):
        fn = [0, 1,]
        for i in range(2, n):
            fn.append(fn[i-1] + fn[i-2])
        return fn
    
    0 讨论(0)
  • 2020-11-27 21:31

    I've build this a while ago:

    a = int(raw_input('Give amount: '))
    
    fab = [0, 1, 1]
    def fab_gen():
        while True:
            fab.append(fab[-1] + fab[-2])
            yield fab[-4]
    
    fg = fab_gen()
    for i in range(a): print(fg.next())
    

    No that fab will grow over time, so it isn't a perfect solution.

    0 讨论(0)
  • 2020-11-27 21:35

    You had the right idea and a very elegant solution, all you need to do fix is your swapping and adding statement of a and b. Your yield statement should go after your swap as well

    a, b = b, a + b #### should be a,b = a+b,a #####

    `###yield a`
    
    0 讨论(0)
  • 2020-11-27 21:38

    I would use this method:

    Python 2

    a = int(raw_input('Give amount: '))
    
    def fib(n):
        a, b = 0, 1
        for _ in xrange(n):
            yield a
            a, b = b, a + b
    
    print list(fib(a))
    

    Python 3

    a = int(input('Give amount: '))
    
    def fib(n):
        a, b = 0, 1
        for _ in range(n):
            yield a
            a, b = b, a + b
    
    print(list(fib(a)))
    
    0 讨论(0)
  • 2020-11-27 21:40

    Also you can use enumerate infinite generator:

    for i,f  in enumerate(fib()):
        print i, f
        if i>=n: break
    
    0 讨论(0)
  • 2020-11-27 21:44

    Also you can try the closed form solution (no guarantees for very large values of n due to rounding/overflow errors):

    root5 = pow(5, 0.5)
    ratio = (1 + root5)/2
    
    def fib(n):
        return int((pow(ratio, n) - pow(1 - ratio, n))/root5)
    
    0 讨论(0)
提交回复
热议问题