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协程的正确逻辑,我对如何正确地制作它有点困惑,在此先感谢!


MMMHUHU
浏览 122回答 1
1回答

慕标琳琳

您可以存储一个附加index的跟踪最近产生的斐波那契数的索引。然后,您可以steps根据提供的值计算您需要推进序列的数量send:def fibonacci(limit):&nbsp; &nbsp; a, b = 0, 1&nbsp; &nbsp; index = 1&nbsp; # the index of the fibonacci number 'b'&nbsp; &nbsp; while index < limit:&nbsp; &nbsp; &nbsp; &nbsp; goto = (yield b)&nbsp; &nbsp; &nbsp; &nbsp; if goto is None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; goto = index + 1&nbsp; &nbsp; &nbsp; &nbsp; if goto > limit:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; steps = goto - index&nbsp; &nbsp; &nbsp; &nbsp; if steps >= 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for __ in range(steps):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a, b = b, a + b&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for __ in range(-steps):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a, b = b - a, a&nbsp; &nbsp; &nbsp; &nbsp; index = goto
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python