1

可能重复:
Python Fibonacci Generator

我正在尝试构建一个可以将值附加到空列表的函数

n1 = 1

n2 = 2

fn = []

我想将 n1 和 n2 加在一起,然后将该值发送给 fn。

然后我想将 n1 和 n2 重新分配给序列的最后两个值。

然后我希望能够在一定数量的迭代后停止它。

我基本上是在尝试构建一个斐波那契序列生成器而不使用该函数

#s(n) = (1.618^n-(1-1.618)^n)/(5^.5)`

例子:

 fn = []




 def fibb(n1,n2,f_iter):
 # n1 would be the first number of the sequence
 # n2 would be the second number of the sequence
 # f_iter would be how many iterations it would do until finished

因此,如果输入是:

 def fibb(1,2,10):  
    return fn

 fn = [1,2,3,5,8,13,21,34,55,89,144,233]

#f_iter(0:1+2=3,1:2+3=5,2:3+5=8,3:5+8=13, . . . 10:89+144=233)
4

1 回答 1

1

你可以用这个

def fib():
    first, second = 0, 1
    while 1:
        yield first
        first, second = second, first + second
于 2012-12-02T06:20:15.970 回答