用于创建斐波那契数列生成器的 Python 脚本

标签 python function iterator sequence fibonacci

Possible Duplicate:
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)

最佳答案

你可以使用这个

def fib():
    first, second = 0, 1
    while 1:
        yield first
        first, second = second, first + second

关于用于创建斐波那契数列生成器的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13665815/

相关文章:

python - sqlite python sqlite3.OperationalError : database is locked

python - 如何在没有警告的情况下在 Pandas 中进行分配?

function - 将函数的返回值分配给 unix shell 脚本中的变量

c++ - 引用变量的默认值

python - django - 导入错误

python - 如何使用 fetchmany 将 mysql 表转储到 csv 中

json - 使用 Node.js 将 URL/路径转换为 ​​Json

c++ - 迭代器的值

c++ - 为动态矩阵类实现自定义迭代器

iterator - 如何自动实现 FromIterator?