Last answered:

06 Oct 2021

Posted on:

27 Sept 2021

1

Resolved: question about problem 2 in the excercise

Hi,
for problem 2, this is the provided answer:
n = 12
a = 0
b = 1
d = dict()
for i in range(1,n+1):
    d[i] = a
    a,b = b,a+b
print(d)

when I replace a,b = b,a+b by
a=b
b=a+b
the output changes. why is that?

1 answers ( 1 marked as helpful)
Instructor
Posted on:

06 Oct 2021

2

Hello Abdulmalik,

Thank you for your question - that is exactly what is expected from you, to play with the code, to meddle with it and to try and break it. That is a very good form of  practice. Now, in the original code you have a,b = b,a+b, so that is a simultaneous assignment. After performing a,b = b,a+b,the variables 'a' and 'b' get changed according to the following pattern:
-> the new value of 'a' is the old value of 'b'
-> the new value of 'b' is the old value of 'a' + the old value of 'b'
--------------------
Let's see what happens when we change the code toa = b and afterwards b=a+b. The first line means that the new value of 'a' is the value of 'b'. The second line is crucial now - the new value of 'b' is the current (!) value of 'a' (which is now the old 'b') + the value of 'b'. This means that we just double the value of 'b' on every iteration.
--------------------
Consider a practical example - let initially a = 5 and b = 8. One iteration of the original code a,b = b, a+b means that 'a' becomes 8 and 'b' becomes 5+8, so finally you have a = 8 and b = 13. One iteration of the changed code a=b and b = a+b means that 'a' first becomes 8; then 'b' becomes 8 + 8, because we have changed the value of 'a' in the previous line. This is the reason why the code snippet produces a different result.

Hopefully this explains it all!

Best,
A. The 365 Team

Submit an answer