Fibonacci系列在python中使用生成器

时间:2018-02-05 10:33:07

标签: python python-3.x generator fibonacci

如何在python中使用生成器生成斐波纳契数组。

2 个答案:

答案 0 :(得分:0)

def fib_gen():
    a = 0
    b = 1
    c = 0
    yield a
    yield b

    while True:
        c = a + b
        yield c
        a = b
        b = c


fs = fib_gen()

print(next(fs))
print(next(fs))
print(next(fs))
print(next(fs))
print(next(fs))
print(next(fs))

答案 1 :(得分:0)

以下是斐波那契发生器的示例。此处的关键是使用yield语句。

def fib(n):
    a = b = 1
    yield a
    yield b
    while n > 2:
        n -= 1
        a, b = b, a + b
        yield b