Python:创建前n个斐波纳契数的列表 [英] Python: Creating a List of the First n Fibonacci Numbers
本文介绍了Python:创建前n个斐波纳契数的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Python和这些论坛的新手.
I am new to Python and to these forums.
我的问题是:如何在Python中创建n
斐波那契数字的列表?
My question is: How can I create a list of n
Fibonacci numbers in Python?
到目前为止,我有一个给出 nth
斐波那契数的函数,但是我想获得第一个n
Fib的列表.未来工作的编号.
So far, I have a function that gives the nth
Fibonacci number, but I want to have a list of the first n
Fib. numbers for future work.
例如:
fib(8) -> [0,1,1,2,3,5,8,13]
推荐答案
尝试一下,这是一种递归实现,它通过首先计算先前值的列表来返回数字列表:
Try this, a recursive implementation that returns a list of numbers by first calculating the list of previous values:
def fib(n):
if n == 0:
return [0]
elif n == 1:
return [0, 1]
else:
lst = fib(n-1)
lst.append(lst[-1] + lst[-2])
return lst
它按预期工作:
fib(8)
=> [0, 1, 1, 2, 3, 5, 8, 13, 21]
这篇关于Python:创建前n个斐波纳契数的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文