【问题标题】:Python: write fibonacci coroutinePython:编写斐波那契协程
【发布时间】:2020-04-27 10:57:34
【问题描述】:

我想写一个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 fibonacci协程的正确逻辑,我对如何正确地制作它有点困惑,提前谢谢!

【问题讨论】:

    标签: python fibonacci coroutine


    【解决方案1】:

    您可以存储一个额外的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
    

    【讨论】:

      猜你喜欢
      • 2019-07-11
      • 2010-09-22
      • 2014-05-23
      • 2019-01-18
      • 2015-03-26
      • 2013-08-03
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多