+ 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...

4th May 2017, 9:01 PM
Supersebi3
Supersebi3 - avatar
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().
4th May 2017, 9:26 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 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)
4th May 2017, 9:39 PM
visph
visph - avatar
+ 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 )
5th May 2017, 5:32 AM
visph
visph - avatar
+ 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)])
4th May 2017, 10:06 PM
richard
+ 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)
5th May 2017, 5:25 AM
Supersebi3
Supersebi3 - avatar
+ 2
@visph I know, thats what I wanted, after all it was just a test... I also added a sleep() to the loop
5th May 2017, 5:36 AM
Supersebi3
Supersebi3 - avatar