简体   繁体   中英

infinite Fibonacci generator in python with yield error?

def fib_gen():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

print(next(fib_gen())) 
print(next(fib_gen())) 
print(next(fib_gen())) 
print(next(fib_gen()))

Output: 0 
        0 
        0 
        0

I am trying to create an infinite Fibonacci generator in python. Please help ... Where am I doing wrong ?

Each call to fib_gen() creates a new generator that is in initial state. Try assigning the return value of fib_gen() to a variable and calling next() on that same variable.

You first need to create a generator object:

def fib_gen():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b


generator = fib_gen()

print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))

The output is:

0
1
1
2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM