What am I doing wrong with this fibonacci code snippet in the python docs or my implementation?

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 reappraisal:

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

      

+3


source to share


4 answers


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)

      

+2


source


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.

+1


source


def fib2(n):
a=0
b=1
while a<n:
    print a
    a=b
    b=a+b

      

Here when you do a = b

and then b=a+b

This equals b = b+b

This is not what you want

Now this is what you want:

def fib2(n):
a=0
b=1
while a<n:
    print a
    tmp = b
    b = a+b
    a = tmp

      

But a,b=b,a+b

this is much more pythonic

0


source


I believe this is a comma syntax detail. Try:

c=b
b=b+a
a=c

      

0


source







All Articles