Python: 编写斐波那契协程

Python: write fibonacci coroutine

我想编写一个 fibonacci 函数,其行为类似于 python 中的 coroutine

这基本上是我想要完成的:

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

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

我尝试根据下面截取的代码编写一些逻辑,但不幸的是这不是我要找的:

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

谁能帮我找出 python 斐波那契协程的正确逻辑,我对如何正确制作它有点困惑,在此先感谢!

您可以存储一个额外的 index 来跟踪最近产生的斐波那契数的索引。然后,您可以根据 send:

提供的值计算需要将序列推进多少 steps
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