infinite Fibonacci generator in python with yield error?

Multi tool use
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 ?
Thanks but No @insaner.. In infinite series I get this code from web everywhere.. but it is resetting the value of a every-time it is called.
– Sameer Pradhan
Jul 1 at 5:39
2 Answers
2
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.
fib_gen()
fib_gen()
next()
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
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Possible duplicate of Python Fibonacci Generator
– Blincer
Jul 1 at 5:37