What is the difference between `a, b = b, a+b` and `a = b; b = a+b` for fibonacci [duplicate]

不打扰是莪最后的温柔 提交于 2019-11-30 06:02:54

问题


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))

回答1:


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)



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!