Python Fibonacci Generator

前端 未结 17 1190
别那么骄傲
别那么骄傲 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:44
    a = 3 #raw_input
    
    def fib_gen():
        a, b = 0, 1
        while 1:
            yield a
            a, b = b, a + b
    
    fs = fib_gen()
    next(fs)
    for i in range(a):
        print (next(fs))
    
    0 讨论(0)
  • 2020-11-27 21:45

    Since you are writing a generator, why not use two yields, to save doing the extra shuffle?

    import itertools as it
    
    num_iterations = int(raw_input('How many? '))
    def fib():
        a,b = 0,1
        while True:
            yield a
            b = a+b
            yield b
            a = a+b
    
    for x in it.islice(fib(), num_iterations):
        print x
    

    .....

    0 讨论(0)
  • 2020-11-27 21:45
    def genFibanocciSeries():
    
        a=0
        b=1
        for x in range(1,10):
            yield a
            a,b = b, a+b
    
    for fib_series in genFibanocciSeries():
        print(fib_series)
    
    0 讨论(0)
  • 2020-11-27 21:46

    Your a is a global name so-to-say.

    a = int(raw_input('Give amount: '))
    

    Whenever Python sees an a, it thinks you are talking about the above one. Calling it something else (elsewhere or here) should help.

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

    It looks like you are using the a twice. Try changing that to a different variable name.

    The following seems to be working great for me.

    def fib():
        a, b = 0, 1
        while True:
            yield a
            a, b = b, a+b
    
    f = fib()
    for x in range(100):
        print(f.next())
    
    0 讨论(0)
  • 2020-11-27 21:49

    i like this version:

    array = [0,1]
    
    for i in range(20):
       x = array[0]+array[1]   
       print(x)
       array[0] = array[1]
       array[1] = x
    
    0 讨论(0)
提交回复
热议问题