Why this python code is giving two different outputs for the same code or both are different codes?

61 Views Asked by At

This is Python code to print Fibonacci series using generator function. Code 1:

def test_fib(n):
    a = 0
    b = 1
    for i in range(n):
        yield a
        a = b
        b = a+b
     #end of function
        
for t in test_fib(10):
    print(t)

Output of code1:- 0 1 2 4 8 16 32 64 128 256 Code 2:-

def test_fib(n):
    a, b = 0, 1
    for i in range(n):
        yield a
        a, b = b, a+b
    #end of function
        
for i in test_fib(10):
    print(i)

Output of code2:- 0 1 1 2 3 5 8 13 21 34

3

There are 3 best solutions below

0
Ali Salesi On

the first code just doubles the b since we set a to b first. the second code uses tuple unpacking so the assignment is done using previous values so it actually gives us the Fibonacci series.

0
Bigbob556677 On

I actually enjoyed this question. Essentially what is happening when you run the Tuple unpacking in exapmle 2 is that Python doesn't "re check" the variables a and b before performing the addition.

Meaning that when a+b occurs, a!=b yet.

Here's a minimal example of this effect.

a=1
a,b = a+1, a+1
print(a, b) # >>> 2 2 

or in plain math here's whats happening

a,b = 1+1, 1+1

With your first example you are adding 1 to a and then adding the sum of that to b, with the second function the two assignments happens at the same time persay.

1
CodeApy25 On

I agree with the others on the idea of Tuple unpacking, but also, for the second one, you used (for 'i') twice.

Possibly could be some problem with the i-value as you never reset that variable.