Search code examples
pythonpython-3.xfibonacci

difference between these two fibonacci python code


What is the difference between these two python code?.i thought both are same but the output i am getting is different


    def fibonacci(num):
        a=1
        b=1
        series=[]
        series.append(a)
        series.append(b)
        for i in range(1,num-1):
            series.append(a+b)
            #a,b=b,a+b
            a=b
            b=a+b
            
            
            
        return series
    print(fibonacci(10))


    def fibonacci(num):
        a=1
        b=1
        series=[]
        series.append(a)
        series.append(b)
        for i in range(1,num-1):
            series.append(a+b)
            a,b=b,a+b
            #a=b
            #b=a+b
            
            
            
        return series
    print(fibonacci(10))


Solution

  • In the first method

    a=b
    b=a+b
    

    is an incorrect way of swapping, when you say a=b you have lost the value of a, so b=a+b is the same as b=b+b, which is not what you want.

    Another way to achieve an equivalent result to this approach, a,b = b,a+b, is by using a temporary variable to store a, as follows:

    tmp = a
    a = b
    b = tmp + b