Why divide this operation into two causes change in result?

2

I made a simple algorithm that solved Fibonacci in 2 logical operations inside the loop. I decided to look for a better way and found a version that does in only 1 calculation in of the loop. It worked perfectly, but when I went to understand the logic appeared a problem.

The code that generates the correct sequence is as follows:

N = int(input())
x, b, a = 0, 1, 0

while x < N:
    print('{}'.format(a), end=' ')
    a, b = b, a + b
    x += 1

So I tried to decompose the logic a, b = b, a + b and the results began to give problems.

For example: Both

a = b
b = a + b

as

b = a + b
a = b

outputs a completely out of order sequence.

I ask: What is the error in changing the logic in these cases since I kept the same logical operations although in different lines? Is there any difference in being on the same line or in separate lines?

    
asked by anonymous 20.02.2018 / 03:01

2 answers

5

It has a difference. When on the same row, both values will be updated concomitantly, while on different lines no. As a starts at zero and b at one, when you do a, b = b, a+b , a will receive the value of b , 1, and b will receive the value of a+b , 0 + 1 = 1. Note that the value of a is still 0 in this line, since it will be 1 only after the entire row is executed. In separate lines, b would receive 1 + 1 = 2, breaking the sequence.

On the same line:

a = 0
b = 1

print('Antes:')
print('a', a)  # a 0
print('b', b)  # b 1

a, b = b, a+b

print('Depois:')
print('a', a)  # a 1
print('b', b)  # b 1

See working at Repl.it | Ideone

On separate lines:

a = 0
b = 1

print('Antes:')
print('a', a)  # a 0
print('b', b)  # b 1

a = b 
b = a+b

print('Depois:')
print('a', a)  # a 1
print('b', b)  # b 2

See working at Repl.it | Ideone

    
20.02.2018 / 03:12
1

What happens is that in the expression a, b = b, a + b , the value of a + b is calculated before the value of a is changed (to b ).

Example:

a = 3
b = 5
a, b = b, a + b
a
=> 5
b
=> 8

When you do one at a time, the values that will be used in a + b change before time.

Example:

a = 3
b = 5
a = b
a
=> 5
b = a + b
b
=> 10   
    
20.02.2018 / 03:11