Reputation: 53
This is what they have:
def fib(n):
a, b = 0, 1
while a < n:
print a,
a, b = b, a+b
This is what I have:
def fib(n):
a = 0
b = 1
while a < n:
print a
a = b
b = b+a
The first returns the correct sequence when employed, whereas mine proceeds 0, 1, 2, 4, 8, 16, 32...
I am currently learning programming (no prior computer science education), and it's clear that the problem is how I've defined my variables. What is the difference between separating the variables by commas and separating variables by a new line (assuming that is the issue)?
Upvotes: 5
Views: 334
Reputation: 304147
This is a tuple assignment:
a, b = 0, 1
You can also think of it as
(a, b) = (0, 1)
A temporary tuple is created with the values 0
, and 1
and then unpacked onto the variable a
and b
This is also a tuple assignment
a, b = b, a+b
Again, you can think of it as
(a, b) = (b, a+b)
The temporary tuple is created from the values of b
and a+b
before either of them is updated. The assignment only happens after the temporary tuple is created.
By breaking it out to separate steps, you are changing the meaning of the code.
Lets see what happens here
a, b = 0, 1 # a=0 , b=1
a, b = b, a+b # a=1 , b=1
Compare with
a = 0 # a=0
b = 1 # a=0 , b=1
a = b # a=1 , b=1
b = b+a # a=1 , b=2
Upvotes: 8
Reputation: 213233
There is only one difference:
In the first one, the assignment b = b+a
is done before the modification of a
. This is because, both the expression in RHS is evaluated first, before any assignment is done.
Whereas in the 2nd one, the 2nd assignment is done after the modification of a
. That is why you are seeing wrong result.
So, in your code:
b = b + a
is actually:
b = b + b
because a
has already been assigned the value of b
.
Upvotes: 5