Python docs:
>>> def fib(n):
a,b=0,1
while a<n:
print a,
a,b=b,a+b
>>> fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
My reimplementation:
>>> def fib2(n):
a=0
b=1
while a<n:
print a
a=b
b=a+b
>>> fib2(2000)
0
1
2
4
8
16
32
64
128
256
512
1024
Advertisement
Answer
The difference between
a,b=b,a+b
and
a=b b=a+b
is that in the second one, a is assigned value of b, and then b is assigned the sum of a and b, which means it is twice its original value.
Consider:
a = 1 b = 2 a,b = b,a+b
This gives
a==2 (old value of b) b==3 (sum of 1 and 2)
Contrarily:
a = 1 b = 2 a = b b = a + b
which gives:
a==2 (old value of b) b==a+b==2+2==4 (twice the old value of b)