Variable assignment difference

66 views Asked by At

I'm currently on an exercise to produce the position of a given Fibonacci number.

My initial code was :

n = int(input())
a = 0
b = 1
new_list = []

for i in range(n+1):
    new_list.append(a)
    a = b 
    b = a + b 

print(new_list)

However, The right way to execute the code is :

n = int(input())
a = 0
b = 1
new_list = []

for i in range(n+1):
    new_list.append(a)
    a, b = b, a + b

print(max(new_list))

What's the difference between a,b = b, a + b and a = b, b += a written in separate lines?

I asked for help from ChatGPT, but I don't quite understand the difference between my code and the corrected code, given that my code returns the wrong answer and ChatGPT is correct.

3

There are 3 answers

0
Mureinik On BEST ANSWER

The right-hand side is fully evaluated before performing the assignment. In the second second snippet, you'd first add a+b, and then assign a=b and b=a+b, where the value of a is taken before it's overridden with b.

In the first snippet, a is overriden with b, and then b is assigned a+b, which just doubles its value.

If you wanted to separate the assignments for better readability, you could use a temporary variable:

tmp = a + b
a = b
b = tmp
2
Vinayak On

The very important difference i am seeing here is the "print(max(new_list))". Here it is requestng for the max number in the list which will provide you the only number you need.

0
Vijay On

The difference between

a=b b=a+b

and

a,b=b,a+b

is that when you do in the first method the value of 'a' will changed(updated with value 'b') so that in the next line "b=a+b" since the value of 'a' is updated with value 'b' it will be calculated as 'b+b' which is '2b'. But in the second method both 'a' and 'b' will be updated to 'b' and 'a+b' simultaneously. So the values will not be changed.