首页 > 解决方案 > Python:编写斐波那契协程

问题描述

我想编写一个在 pythonfibonacci中表现得像 a 的函数。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 fibonacci协程的正确逻辑,我对如何正确地制作它有点困惑,在此先感谢!

标签: pythonfibonaccicoroutine

解决方案


您可以存储一个附加index的跟踪最近产生的斐波那契数的索引。然后,您可以steps根据提供的值计算您需要推进序列的数量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

推荐阅读