Moo
Moo

Reputation: 81

Why do these two python functions return different results?

1-

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

2-

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

On execution:

fib1(10) I got the wrong answer: 0 1 2 4 8

fib2(10) I got the right answer: 0 1 1 2 3 5 8

Upvotes: 3

Views: 123

Answers (3)

C Panda
C Panda

Reputation: 3405

fib1 contains a classic bug. It is in the same realm as that of swapping values of two variables. Think about how you would have done that in C or C++.

int a = 3;
int b = 5;
int temp;
temp = a; /* 3 */
a = b; /* 5 */
b = temp; /* 3, hence swapped */

There is a way to do without temp, although there are intermediate calculations involved. Now in Python, if you are not going to exploit the tuple unpacking feature, you have to involve a temp variable.

a = 3
b = 5
temp = a
a = b
b = temp

OR

a = 3
b = 5
a_ = (a+b)/2 - (a-b)/2 # 5.0
b_ = (a+b)/2 + (a-b)/2 # 3.0

Better use the tuple unpacking as in fib2.

Upvotes: 0

jtitusj
jtitusj

Reputation: 3086

here's a quick answer:

the basic difference is the way the values of a and b are reassigned. In fib1(), you have

a = b
b = a + b

while in fib2(), you have

a, b = b, b + a

Now, these two looks equal statements but they are not. Here's why:

In fib2(), you assign the values of the tuple (b, b + a) to the tuple (a, b). Hence, reassignment of values are simultaneous.

However, with fib1(), you first assign value of b to a using a = b and then assign the value a + b to b. Since you have already changed value of a, you are in effect doing

b = a + b = b + b = 2b

In other words, you are doing a, b = b, 2b and that is why you are getting multiples of 2 rather than the fibonacci sequence.

Upvotes: 0

dustinroepsch
dustinroepsch

Reputation: 1160

In fib 1 a = b overwrites the value of a,

which means a is no longer the right value for the statement

b = a+b

However, in your second example both those things happen at the same time on the line a,b = a, b+a which means a is the right value still.

Upvotes: 8

Related Questions