Fibonacci与Python:indexer:list索引超出范围
我试图编写一个程序,用Python计算斐波那契数:Fibonacci与Python:indexer:list索引超出范围,python,fibonacci,Python,Fibonacci,我试图编写一个程序,用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后,弹出以下消息: T
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
过程中出了什么问题?提前感谢。您需要用Fibonacci序列的前两个数字填充列表:
a = [0, 1]
您需要使用Fibonacci序列的前两个数字填充列表:
a = [0, 1]
-如果在使用之前未在列表中设置2和-1索引,则它们不可用
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))
-如果在使用之前未在列表中设置2和-1索引,则它们不可用
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))
在代码中进行这些更改
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)
调用此函数来计算任何斐波那契数列
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)
索引器错误:列出索引超出范围您的e从空数组开始并尝试访问其上的索引。索引器错误:列出索引超出范围您的e从空数组开始并尝试访问其上的索引。