difference between these two fibonacci python code

Question:

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

Asked By: Zeusthunder1

||

Answers:

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 
Answered By: Mohammed Alkhrashi

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)

Answered By: Bhugs Hardy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.