Py学习  »  Python

在python中返回最多n项的斐波那契数列[重复]

Sumit Dwivedi • 4 年前 • 2220 次点击  

我很难理解其中的逻辑,比如如何创建一个python函数,该函数以n为参数,n是从0开始的斐波那契数列中获取的元素总数,然后返回一个斐波那契数列列表,直到这些元素数为止。

E.g. Input = 3 then Output = [0,1,2]
Input=6 then Output = [0,1,1,2,3,5]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133114
文章 [ 3 ]  |  最新文章 4 年前
lucascavalcante
Reply   •   1 楼
lucascavalcante    4 年前

你需要一个 发电机 为此。

  • 需要存储两个状态。
  • 用序列的大小建立一个列表。
  • 遍历该列表,在每个位置放置前面元素的总和。
  • 在下一次迭代中,累积的总和将存储在当前位置。
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

print(list(fib(5)))
>>> [0, 1, 1, 2, 3]
prafful manwani
Reply   •   2 楼
prafful manwani    4 年前
n = int(input())
ls = [0,1]
for x in range(n):
    if len(ls) < n:
        ls.append(ls[-1] + ls[-2])
print(ls)
Ibrahim
Reply   •   3 楼
Ibrahim    4 年前

这个 rth 斐波那契的术语是 r-1th 术语+ r-2th 术语,其中r>0 所以你可以从一个初始列表开始 [0,1] 然后使用for循环遍历具有最大限制的自然数 n 和最小极限 1 然后使用列表中的索引来获取 r-1th 术语和 r-2 然后附加 rth 在名单上。我会这样做的。

intialise the list with elements 0,1
use a for loop here to loop through the natural numbers
get the r-1th from the list
get the r-2th from the list
add both
append the result you got, in the list you initialised