user1142285
user1142285

Reputation: 119

fibonacci and non-fibonacci coding

I apologize since this might be a common question, but I think I am looking for a quite specific answer that wouldn't be found in other topics. Basically, I am quite confused about the flow of adding numbers. Here are two similar codes that compute numbers differently. Is there any simple explanation for this?

>>> a = 0
>>> b = 1
>>> while b <1000:
    print b
        a, b = b, a+b


1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987

>>> a =0
>>> b=1
>>> while b<1000:
       print b
       a = b
       b = a+b


1,2,4,8,16,32,64,128,256,512

Upvotes: 1

Views: 224

Answers (3)

zzz
zzz

Reputation: 1

The assignments happen at the same time in the 1st code example, and serially in the 2nd, leading to a different answer.

Upvotes: 0

Tony
Tony

Reputation: 11

There is a precedence difference in the swap. In the first example you are assigning: a = 1 b = 1

In the second example you are assigning: a = 1 b = 2

In order to achieve the same order of operations as the first example you'll have to use a temp var.

Upvotes: 1

Jordan
Jordan

Reputation: 2758

The difference lies in what the values are WHEN swapped

a, b = b, a+b

sets a to b and sets a to a+b but the swaps are done relatively at the same time so it's not in order, ie the change in b doesn't respect that a was changed first.

In the second example

a = b

b = a+b

the values are changed and the 2nd statement respects the change of the first

Upvotes: 1

Related Questions