如何使用没有停止数的生成器编写斐波那契数列

How to write Fibonacci with generator without stop number

我经历了Beginning Python fibonacci generator

如何写出我们要停止的停止编号。

我的 FIbnocci 代码如下

def Fibonnaci(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    else:
        return (Fibonnaci(n-1)+ Fibonnaci(n-2))

n = int(input())
print(Fibonnaci(n))

我写的是 yield 语句,但它是无限循环 运行

def fib(n):
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib(7)

求出> 13

yield语句用于迭代一些数据,一次产生一个值。

所以:迭代

f = fib()
fibs = [next(f) for _ in range(7)]
fib_7 = fibs[-1]

注意 当您从 yield a 开始时,您会得到一个 0 作为第一个数字。所以转移到 yield b 这将按预期工作

你不想无限循环;你需要记录你执行了多少次操作。

在生成元素时在循环中保持计数器的状态。继续前进,直到 count >= n

def fib(n):
     count = 0
     a, b = 0, 1
     while count < n:
             yield a
             a, b = b, a + b
             count += 1

然后,如果您愿意,您可以在列表推导中利用它来获取所有等于该斐波那契数的值。

[i for i in fib(10)]
n = int(input())
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b  #swap the values, sum

def firstn(g, n):
    for i in range(n):
        yield g.__next__() # take  the next value for the generator


t =  (list(firstn(fibonacci(), n+1))) # Put in a list
print (t[-1])   #take the last element