Reputation: 15
I am new in python programming, and I am trying writing fib based on the generator. And I tried this:
def fib(n):
a = 0
b = 1
for _ in range(n):
yield a
print(a)
a, b = b, a + b
print((a,b))
and This one:
def fib(n):
a = 0
b = 1
for _ in range(n):
yield a
a = b
b = a + b
print(list(fib(a)))
the results are different, why would that happen?
Upvotes: 0
Views: 173
Reputation: 7900
Python doesn't break this
a, b = b, a + b
into this:
a = b
b = a + b
Instead, Python compiler evaluates right hand of an expression first by converting this:
a = 0
b = 1
a, b = b, a + b
into this:
a = 0
b = 1
a, b = 1, 1
then assigns it in proper order.
So a
and b
becomes 1.
Upvotes: 1
Reputation: 54223
Step through and find out!
a = 0
b = 1
# loop starts: # loop starts
yield a # yields 0, a=0, b=1 yield a # yields 0, a=0, b=1
a = b # a=1, b=1 a, b = b, b+a # a=1, b=1
b = a + b # a=1, b=2
# loop
yield a # yields 1, a=1, b=2 yield a # yields 1, a=1, b=1
a = b # a=2, b=2 a, b = b, b+a # a=1, b=2
b = a + b # a=2, b=4
# loop
yield a # yields 2 a=2, b=4 yield a # yields 1, a=1, b=2
a = b # a=4, b=4 a, b = b, b+a # a=2, b=3
b = a + b # a=4, b=8
# etc...
Upvotes: 0