+ 5
Where is the error here?
I was testing around with generators and coded this: def fib(): a = 1 b = 1 yield a yield b while True: a, b = b, a + b yield b Its supposed to yield the fibonacci numbers, but using print(next(fib())) always prints 1...
6 Respostas
+ 10
It produces an infinite generator expression. If you change while True to while b != 55, it will break when 55 is reached. Then, if you print(list(fib())), it will print the list. You can iterate on it using next().
+ 6
def fib():
a = 1
b = 1
yield a
yield b
while True:
a, b = b, a + b
yield b
genfib5 = fib()
for i in range(5):
print(next(genfib5))
print()
# or ( this way will produce infinite loop with your fib() version:
def fib2(n):
a = 1
b = 1
yield a
if n > 1:
yield b
c = 2
while c < n:
a, b = b, a + b
yield b
c += 1
genfib5 = fib2(5)
for i in genfib5:
print(i)
print()
# or shortener ( without assigning the generator object to a variable ):
for i in fib2(42):
print(i)
+ 5
Yes, you must assign a variable with a generator object instance in the case of the 'next()' function use ( else 'print(next(fib())' will always print the first item of a new generator at each iteration -- and you will get only 1 at output ^^ )
Anyway, infinte loops aren't user friendly, and would may be avoided :P ( your infinite output loop will display result infinitly and too much quickly for be readable during the output scroll wich will never terminate by any other way than brutally interrupt it -- software shutdown in better cases, hardware in worst )
+ 2
def fib():
a = 1
b = 1
yield a
yield b
while True:
a, b = b, a + b
yield b
# you could keep also keep your original
# code and use zip with a specified range
# to extract that many values rather than
# using explicit next calls
handel = fib()
print([x for _,x in zip(range(9),handel)])
+ 2
I found a different way. Yes I wanted to do infinite loop
the definition of fib() stays the same
f = fib()
while True:
print(next(f))
I didnt know I had to assign the generator to a variable (f)
+ 2
@visph I know, thats what I wanted, after all it was just a test...
I also added a sleep() to the loop