infinite Fibonacci generator in python with yield error?

Multi tool use
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 ?





Possible duplicate of Python Fibonacci Generator
– Blincer
Jul 1 at 5:37





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.

hj VWFqAl qjDgHXNEoNs31hf2m6a Lz0FZ30d OX8sVavdQ73uR,HT
L1xPC4EMgt3jKm4SSjR6nQLFdxhNhLGTM M86VBT0rn 8f

Popular posts from this blog

PySpark - SparkContext: Error initializing SparkContext File does not exist

django NoReverseMatch Exception

List of Kim Possible characters