-2

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

1
  • Your indentation is clearly wrong, but what's less clear is how it ought to be indented. Don't make us guess; please edit to fix it. On the desktop version of this site, you can get code marked up for you by pasting your code, selecting the pasted block, and typing ctrl-K. Commented Dec 4, 2023 at 6:12

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

1 Comment

i is in two different scopes, it wouldn't cause any issues, albeit the indenting in the question is messed up.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.