This question already has an answer here:
I'm new to python so I want to ask you a question..
Previously while I was writing a fibonacci function I tryed to replace
a, b = b, a+b
with
a = b
b = a + b
Believing that it was the same thing but I noted that the output is different (and wrong) Shouldn't these two codes do the same thing? Here it is the full code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def main(args):
fibonacci(1000)
return 0
def fibonacci(n):
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b # if I comment this and decomment the two line below it shows me a different output
# a = b
# b = a + b
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
when you do:
a, b = b, a+b
a will hold the previous value of b and b will hold a+b based on previous value.
But when you do:
a = b
b = a + b
Value of a is updated to b during a=b and hence a+b will have different result as a is now updated.
For example, see simple code to swap two values. It is possible because of the on the fly change in values:
>>> a , b = 5, 10
>>> a, b = b, a
>>> a, b
(10, 5)
b, a+b is the same as (b, a+b) (a tuple). When you do a, b = b, a+b you implicilty assign the first element to the variable on the left and the second value to the variable on the right.
In your replacement, you changed a's value before calculating b, which didn't happen before.
So, if we assume a = 1 and b = 2, we have:
a, b = (2, 1+2)
>> print(a)
>> 2
>> print(b)
>> 3
In your latter example, we'd have:
a = 2
b = 2 + 2
>> print(a)
>> 2
>> print(b)
>> 4
来源:https://stackoverflow.com/questions/40747003/what-is-the-difference-between-a-b-b-ab-and-a-b-b-ab-for-fibonacc