您好我目前从以下代码中获取索引超出范围错误:(我将首先发布代码然后发布错误)
import Knapsack_Test
size = 10
W = 2*size
knapsack = Knapsack_Test.Knapsack_Test()
for i in range(1, 10):
knapsack.greedy_knapsack_test(size, W)
size = size + 10*i
W = 2*size
def greedy_knap(self, v, w, W):
knap_array = []
for i in range(1, len(v)):
#The index out of range error occurs here:
knap_array[i] = [v[i],w[i]]
sort_order = self.sort.merge_sort(knap_array)
weight = 0
value = 0
knap_sac= []
n = len(knap_array)
j = 0
profit = 0
while weight < W and j < n:
if weight + knap_array[i][1] <= W:
knap_sac.append(knap_array[i])
weight = weight + knap_array[i][1]
profit = profit + knap_array[i][0]
j = j + 1
return profit
def greedy_knapsack_test(self, size, W):
v = []
w = []
for i in range(1,size):
v.append(random.randint(1,1000))
for i in range(1,size):
w.append(random.randint(1,1000))
start = time.time()
self.knapsack.greedy_knap(v, w, W)
end = time.time() - start
return end
Traceback (most recent call last):
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\Knapsack_Main.py", line 10, in <module>
knapsack.greedy_knapsack_test(size, W)
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\Knapsack_Test.py", line 31, in greedy_knapsack_test
self.knapsack.greedy_knap(v, w, W)
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\KnapsackClass.py", line 30, in greedy_knap
knap_array[i] = [v[i],w[i]]
IndexError: list assignment index out of range
答案 0 :(得分:2)
knap_array = []
for i in range(1, len(v)): #The index out of range error occurs here:
knap_array.append([v[i],w[i]])
您无法通过引用它们来创建列表元素。