【发布时间】:2020-06-27 20:58:14
【问题描述】:
免责声明:我完全没有使用 Sage/Python 的经验,所以这可能是一个非常简单的错误
我已经定义了一个名为“权重”的列表
weights = [[0,24,16,4,1],[24,0,5,1,6],[16,5,0,15,7],[4,1,15,0,2],[1,6,7,2,0]]
给出特定路径的成本或权重。所以第一个列表将从第“零”个节点开始,下一个列表将从第一个节点开始,等等。
我想创建一个函数getCost,它从0 to 4 中获取整数列表,并将路径总和的所有成本相加。
def getCost(list):
cost = weights[0][list[0]]
for i in range(1,len(list)+1):
if list[i] > 4 or list[i] < 0:
print "Elements in list cannot be greater than 4."
break
else:
cost += weights[list[i-1]][list[i]]
return "The total cost of this path is " + cost
getCost([1,4,3,2])
但这给了我以下错误信息:
Traceback (most recent call last):
File "/cocalc/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 1234, in execute
flags=compile_flags), namespace, locals)
File "", line 1, in <module>
File "", line 4, in getCost
IndexError: list index out of range
其中哪一部分导致索引超出范围?我想如果我将 for 循环的范围从 i=1 开始,我就不会遇到下限问题。
【问题讨论】:
-
你转到
+1,这超出了list[i]的范围 -
list是python中的保留关键字,我建议你使用其他变量名 -
另外,您可以简单地使用类似以下的内容:
for i in your_list而不是for i in range(1, len(list)+1)。目前,您将列表的第一个元素分配给cost,这可能违反您指定的条件,因为没有检查。