What am I doing wrong with this fibonacci code snippet in the python docs or my implementation?
Difference between
a,b=b,a+b
and
a=b
b=a+b
is that in the second, the a
value is assigned b
and then the b
sum a
and is assigned b
, which means that 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)
Opposite:
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)
source to share
The difference is that when you do:
a,b=b,a+b
# ^
a
which I have denoted is the original value a
, not the updated value. This is because Python always evaluates what's to the right of the sign =
before it evaluates what's to the left.
If you do,
a=b
b=a+b
the a
on the second line is the new value a
that was assigned on the line above. This will disable your computation.
For more information, here's a link to assignment statements in Python.
To get the same behavior as a function in the Python docs, you need a temporary variable to keep the original value a
:
tmp=a
a=b
b=tmp+b
Below is a demo:
>>> def fib2(n):
... a=0
... b=1
... while a<n:
... print a, # The comma causes everything to be printed on one line
... tmp=a
... a=b
... b=tmp+b
...
>>> fib2(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
>>>
Of course it's simple:
a,b=b,a+b
much more pythonic. Although I would recommend that you put in multiple spaces:
a, b = b, a+b
Readability is everything in Python.
source to share