Increment in (a, b = b, a + b) while using a Generator Function

时间:2019-04-17 01:49:15

标签: python fibonacci

Can someone explain how the increment of a or value of a occurs within the for loop to generate the Fib sequence? I have an understanding of (a, b = b, a + b). However, I am unable to figure how the increment occurs in the for loop when next() is called.

 def fib(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b
x = fib(4)
print(x.__next__())
print(x.__next__())
print(x.__next__())
print(x.__next__())

0 1 1 2

1 个答案:

答案 0 :(得分:1)

To begin with, you can go to the next element of the generator by next(x).

Just using a print statement in your code will help you understand as well.

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, b)
        yield a
        a, b = b, a + b

x = fib(4)
print(next(x))
print(next(x))
print(next(x))
print(next(x))
0 1
0
1 1
1
1 2
1
2 3
2

Here the next function lazily evaluates and prints out the value of a, until you call next again. So in the first next, it prints out 0.
Then when you call next again, a = 1 and b = 1, and you get a = 1.
Then when you call next again, a = 1 and b = 2, and you get a = 1.
Then when you call next again, a = 2 and b = 3, and you get a = 2.
After that, since you are done with your for loop, you cannot call next anymore