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!

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.