Fibonacci with Python: IndexError: list index out of range
Fibonacci with Python: IndexError: list index out of range
我正在尝试编写一个程序来使用 Python 计算斐波那契数:
n = int(input())
def fib(n):
a = []
if (n <=1):
return n
else:
for i in range(2, n):
a.append(a[-1] + a[-2])
return a[i]
print (fib(n))
但是,我无法打印出预期的结果。例如,我输入数字 8 后,弹出以下消息:
Traceback (most recent call last):
File "fibonacci.py", line 11, in <module>
print (fib(n))
File "fibonacci.py", line 9, in fib
a.append(a[-1] + a[-2])
IndexError: list index out of range
过程中出了什么问题?提前致谢。
您需要用斐波那契数列的前 2 个数字填充您的列表:
a = [0, 1]
-2 和-1 索引如果在使用前未在"a" 列表中设置它们则不可用。
n = int(input())
def fib(n):
a = [0, 1]
if n <=1:
return n
else:
for i in range(2, n):
a.append(a[-1] + a[-2])
return a[i]
print (fib(n))
在您的代码中进行这些更改
n = int(input())
def fib(n):
a = [0,1] # add these values to your array to intialize
if (n <=1):
return n
else:
for i in range(2, n):
a.append(a[-1] + a[-2])
return a # change this also so that you can get all the values returned at the same time
print (fib(n))
调用此函数计算任意斐波那契数列
def Fibonacci(n):
if n<0:
print("Incorrect input")
# First Fibonacci number is 0
elif n==0:
return 0
# Second Fibonacci number is 1
elif n==1:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
或者您可以使用此公式作为斐波那契数列中第 n 项的公式。
Fn = {[(√5 + 1)/2] ^ n} / √5
我正在尝试编写一个程序来使用 Python 计算斐波那契数:
n = int(input())
def fib(n):
a = []
if (n <=1):
return n
else:
for i in range(2, n):
a.append(a[-1] + a[-2])
return a[i]
print (fib(n))
但是,我无法打印出预期的结果。例如,我输入数字 8 后,弹出以下消息:
Traceback (most recent call last):
File "fibonacci.py", line 11, in <module>
print (fib(n))
File "fibonacci.py", line 9, in fib
a.append(a[-1] + a[-2])
IndexError: list index out of range
过程中出了什么问题?提前致谢。
您需要用斐波那契数列的前 2 个数字填充您的列表:
a = [0, 1]
-2 和-1 索引如果在使用前未在"a" 列表中设置它们则不可用。
n = int(input())
def fib(n):
a = [0, 1]
if n <=1:
return n
else:
for i in range(2, n):
a.append(a[-1] + a[-2])
return a[i]
print (fib(n))
在您的代码中进行这些更改
n = int(input())
def fib(n):
a = [0,1] # add these values to your array to intialize
if (n <=1):
return n
else:
for i in range(2, n):
a.append(a[-1] + a[-2])
return a # change this also so that you can get all the values returned at the same time
print (fib(n))
调用此函数计算任意斐波那契数列
def Fibonacci(n):
if n<0:
print("Incorrect input")
# First Fibonacci number is 0
elif n==0:
return 0
# Second Fibonacci number is 1
elif n==1:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
或者您可以使用此公式作为斐波那契数列中第 n 项的公式。
Fn = {[(√5 + 1)/2] ^ n} / √5