0

I want to write a fibonacci function that behaves as a coroutine in python.

Here is basically what I want to accomplish:

def fibonacci(limit: int) -> int:
    ...

fib = fibonacci(limit=100_000_000)
next(fib)
fib.send(10)  # -> 55
next(fib)  # -> 89
fib.send(15) # -> 610
...

I tried to write some logic based on code snipped below, but unfortunately it's not what I'm looking for:

def fibonacci(limit: int) -> int:
    a, b = 0, 1
    while limit:
        c: int = (yield b)
        if c is not None:
            a, b = b, a + b + c
        else:
            a, b = b, a + b
        limit -= 1

Could anyone please help me to figure out the right logic for python fibonacci coroutine, I'm kind of confused on how to make it properly, thanks in advance!

Vladimir Yahello
  • 243
  • 1
  • 2
  • 10

1 Answers1

2

You can store an additional index that keeps track of the index of the most recently yielded Fibonacci number. Then you can compute by how many steps you need to advance the sequence based on the value provided by send:

def fibonacci(limit):
    a, b = 0, 1
    index = 1  # the index of the fibonacci number 'b'
    while index < limit:
        goto = (yield b)
        if goto is None:
            goto = index + 1
        if goto > limit:
            break
        steps = goto - index
        if steps >= 0:
            for __ in range(steps):
                a, b = b, a + b
        else:
            for __ in range(-steps):
                a, b = b - a, a
        index = goto
a_guest
  • 34,165
  • 12
  • 64
  • 118