Home > Software engineering >  difference between these two fibonacci python code
difference between these two fibonacci python code

Time:09-10

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

CodePudding user response:

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 

CodePudding user response:

The issue here is about storing the values you are calculating, on the first snippet you are saying a b only on the second snippet you are saying b =a b. The value of b is changing when you say b = a b.

Hope my explanation is understandable.You are re-assigning the value of b o the first snippet (b=a b)

  • Related