如何在python中使用生成器生成斐波纳契数组。
答案 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