为什么我得到"索引错误:列出索引超出范围"



我得到这个错误:

IndexError: list index out of range

这是我的功能

def power(x, y, bound):
list, exp = [], []
z = -1
for i in range (1, bound):
for j in range (1, bound):
if x**i + y**j in range (bound):
if x**i + y**j in list:
break
else:
list.append(x**i + y**j)
z += 1
if z == 0:
exp.append(str(x**i + y**j)+" = " + str(x) + "^" + str(i) + " + " + str(y) + "^" + str(j))
break
if list[z] == max(list):
exp.append(str(x**i + y**j)+" = " + str(x) + "^" + str(i) + " + " + str(y) + "^" + str(j))
else:
for n in range(len(list)):
if (list[z] < list[n+1]) and (list[z] > list[n]):
exp.insert(n, str(x**i + y**j) + " = " + str(x) + "^" + str(i) + " + " + str(y) + "^" + str(j))
else:
break
print("nThe list of values:", sorted(list))
print("nExplaination:n"+"n".join(exp))

Call my function:

print("Input: Two positive integers x and y and the boundnOutput: A list of values x^i + y^j bounded by boundn(i and j are positive integers)n")
x = int(input("Input x: "))
y = int(input("Input y: "))
bound = int(input("Input the bound: "))
power(x, y, bound)

我该如何解决这个问题?

好吧,看看函数中的代码,很明显i超过了list的大小:

def power(x, y, bound):
list, exp = [], []

list(不要使用list作为变量名-它是内置的,您已经在这里覆盖了它)以空列表开始。

i = -1

这一行是无用的,因为i在下一行

中被覆盖
for i in range (1, bound):

所以i现在是1

list.append(x**i + y**j)

现在你似乎已经将第一个值附加到list-现在它的大小为1

i += 1

现在你增加了i,所以必须是2

if list[i] == max(list):

但是现在你试图索引到list,这会引发一个IndexError

好的,现在你已经改变了你的代码,我之前的答案已经无效了。

现在你的问题在这里:

if (list[z] < list[n+1]) and (list[z] > list[n]):

n+1,因为n来自for n in range(len(list)):,最终n+1会落在list的末端。

你得问问自己:if (list[z] < list[n+1]) and (list[z] > list[n]):到底是什么意思。

解决困难的一种方法是捕获异常并打印相关值。考虑:

$ python3 <<EOF
a = []
try:
i = 3
a[i] = 0
except IndexError as oops:
print( "%s: array is %d and index is %d" % (str(oops), len(a), i) )
EOF
list assignment index out of range: array is 0 and index is 3

最新更新