如何解决在while循环内返回斐波那契数列中的数字
我正在尝试构建一个函数,该函数将在斐波那契数列中采用n并返回第n个整数。例如,斐波那契数列:
1,1,2,3,5,8,13,21,..... 如果函数是Fibonacci,则它将返回:Fibonacci(8)= 21
现在,我正在编写如下函数:
def Fibonacci2(a):
ls = []
ls = [1,1]
n=0
i=0
while i<a:
ls.append(ls[i-1]+ls[i-2])
n=ls[-1]
i=i+1
return n
Fibonacci2(8)
哪个显示值:8
这是不正确的。
解决方法
您可以通过以下方式完成它:
def Fibonacci2(num):
a = 0
b = 1
n = 2 #iteration counter
while n < num:
c = b #store the current value of the last element of the series
b = b + a #derive the next element of the series by adding the last two elements
a = c
n += 1
return b
打印(Fibonacci2(8))
结果
13
,
您可以尝试这样的事情,
def Fibonacci(n):
a,b = 0,1
arr = [b]
while (len(arr) - 1 < n) :
a,b = b,a + b
arr.append(b)
return arr[n - 1]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。