Python: Usage Of Variables And Their Difference ("a, B = 0, 1" Vs "a = 0", "b = 1")
I was looking at the Python Manual and found this snippet for a Fibonacci-Number generator: def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n:
Solution 1:
Doing:
a, b = b, a+b
is equivalent to:
temp = a
a = b
b += temp
It lets you simultaneously do two calculations without the need of an intermediate/temporary variable.
The difference is that in your second piece of code, when you do the second line b = a+b
, you have already modifed a
in the previous line which is not the same as the first piece of code.
Examples
>>>a = 2>>>b = 3>>>a,b
2 3
>>>a,b = b,a>>>a,b
3 2
On the other hand, if you use the second approach shown in your question:
>>>a = 2>>>b = 3>>>a,b
2 3
>>>a = b>>>b = a>>>a,b
3 3
Solution 2:
In
a, b = b, a+b
the right-hand expressions are evaluated first, and their results are assigned to a
and b
. This is similar to the following:
_new_a = b
_new_b = a+b
a = _new_a
b = _new_b
On the other hand, in
a = b
b = a+b
you are modifying a
before adding it to b
. This is equivalent to
a, b = b, b+b
which explains where the powers of two are coming from.
Post a Comment for "Python: Usage Of Variables And Their Difference ("a, B = 0, 1" Vs "a = 0", "b = 1")"