user1476793
user1476793

Reputation: 9

Logic on printing Fibonacci numbers in Python

This is been killing me. When using the following code to print the Fib number, it gives the right output:

a = 0
n = 1
while n < 55:
    print(n)
    a,n = n,a+n

but when I change to this:

a = 0
n = 1
while n < 55:
    print(n)
    a = n
    n = a+n

The output is totally different. I've even run it thru pythontutor.com to watch stepping.

What are I missing.

Upvotes: 0

Views: 75

Answers (3)

Jay
Jay

Reputation: 24895

There is a difference in the way variable values are interpreted and assigned between the two code snippets.

In case of the first snippet, while assigning the value to "n", the new value of a is not used, rather the value of a from the previous iteration is used.

But, in case of the second snippet, the value of "a" is first updated and then used for the second statement.

Let's take an example:

For the first iteration where n is 1,

First Code Snippet: At the end of the iteration, the value of a will be 1 and value of n also will be 1. (For n = a+n, value of a is considered 0)

Second Code Snippet: At the end of the iteration, the value of a will be 1 and value of n will be 2. (For n = a+n, value of a is considered 1)

The key point to be noted about the Python Comma Operator is that, all the expressions to the right of the assignment operator are evaluated first before the assignments are actually made and this causes the difference in output between the two.

Upvotes: 1

Roberto Trani
Roberto Trani

Reputation: 1227

Let's call a_i and n_i the values of a and n at the i-th iteration. In the first code you are assigning to n_i+1 the value a_i + n_i, instead in the second code you are assignign to n_i+1 the value a_i+n_i+n_i. This happen because you are assigning a before n in the second code, while this happen simultaneously in the first one. To solve this issue save in a temporary variable the old value of n or a.

Alternatively, with just a bit of math, you can do the following without saving any temporary variable:

a = 0
n = 1
while n < 55:
    print(n)
    n = a+n
    a = n-a

which is equivalent to: a_i+1 = n_i+1 - a_i = a_i + n_i - a_i = n_i.

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186678

Well, the initial assignment

 a,n = n,a+n

means

 old_a = a
 a = n
 n = old_a + n # saved a value (old_a) used 

Please, notice that n = old_a + n, not a + n == 2 * n

Upvotes: 0

Related Questions