Moises Pineda
Moises Pineda

Reputation: 21

Fibonacci with Generators

I am trying to make the Fibonacci Succession with Generators but my code return 2**a...

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a = b
        b = a + b
n = int(input("How long? "))
fib = fibonacci()

for i in range(n):
    print(next(fib))

Upvotes: 0

Views: 150

Answers (1)

Nick
Nick

Reputation: 147166

Your issue is that when you assign b = a + b, you've already updated the value of a to be the old value of b. Thus you are effectively assigning b = b + b or 2*b, which is why you get 0, 1, 2, 4, 8, ... as a result. You can work around that by assigning a and b at the same time:

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib=fibonacci()

for i in range(10):
    print(next(fib))

Output:

0
1
1
2
3
5
8
13
21
34

Upvotes: 5

Related Questions