Difference between writing something on one line and on several lines

后端 未结 6 1516
我寻月下人不归
我寻月下人不归 2021-01-13 03:16

Where is the difference when I write something on one line, seperated by a , and on two lines. Apparently I do not understand the difference, because I though t

6条回答
  •  有刺的猬
    2021-01-13 03:41

    To find a replacement for

    a, b = b, a + b
    

    you must become aware that this assignment is performed "step by step".

    So its equivalent is

    old_a = a
    a = b
    b = old_a + b # note the old_a here, as a has been replaced in the meanwhile.
    

    Demo:

    def fibi(n):
        a, b = 0, 1
        for i in range(n):
            a, b = b, a + b
        return a
    
    def fibi2(n):
       a, b = 0, 1
       for i in range(n):
        old_a = a
        a = b
        b = old_a + b
       return a
    
    >>> fibi(0)
    0
    >>> fibi(1)
    1
    >>> fibi(2)
    1
    >>> fibi(3)
    2
    >>> fibi(4)
    3
    >>> fibi(5)
    5
    >>> fibi(6)
    8
    >>> fibi(7)
    13
    >>>
    >>>
    >>>
    >>> fibi2(0)
    0
    >>> fibi2(1)
    1
    >>> fibi2(2)
    1
    >>> fibi2(3)
    2
    >>> fibi2(4)
    3
    >>> fibi2(5)
    5
    >>> fibi2(6)
    8
    >>> fibi2(7)
    

提交回复
热议问题