4

I am writing Fibonacci code in python. The below solution is mine.

enter image description here

While the other below solution is from python.org.

enter image description here

Can anyone tell me why it yields a different answer even though the logic of assigning the variables is the same?

1
  • 1
    It would be best if you added your code as formatted text instead of screenshots to keep it searchable and readable, and avoid issues in the future with link rot. Commented Jun 26, 2017 at 18:48

4 Answers 4

7

Those two programs are not equivalent. The right hand side of the equals (=) is evaluated all together. Doing:

a=b
b=a+b

Is different from:

a,b = b,a+b

This is in reality the same as:

c = a
a = b
b = b + c

Your example is actually covered on the Python documentation:

The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

Sign up to request clarification or add additional context in comments.

Comments

7

The lines

a = b # Assigns the value of 'b' to 'a'
b = a + b # Adds the new value of 'a' to 'b'

whereas,

a, b = b, a+b Assigns the value of b to a. Adds the existing value of a to b.

Comments

5

The reason it works in the second example is becasue the a=b doesn't evaluate until both are done. So when it gets to the b=a+b part, a is still its previous value. In your first example you are overwriting a before using it. In python when you declare variables in this way you are actually using them as tuples. This means that until the whole line is completed they retain their original values. Once the tuple is unpacked they are overwritten.

Comments

2

I see extra tabs in your solution and also logic of your program is wrong. As far as I understood by writing fib(5) you want 5th fibonacci in the series (which is 5) not a number which is less than 5 (which is 3).

a=b
b=a+b

and

a,b = b,a+b

are not equal.

Look at the code below.

def fibonacci(num):
    a,b=0,1;
    counter = 2;
    while(a<=):
        a,b = b,a+b
        counter += 1
    return b

print fibonacci(5)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.