Question

Hello I am currently getting an index out of range error from the following code: (I will post the code first and then the error)

Main File:

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

Class File (Only the greedy function):

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

The test File (for greedy function):

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

The Error:

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
Was it helpful?

Solution

knap_array = []

for i in range(1, len(v)): #The index out of range error occurs here:
    knap_array.append([v[i],w[i]])

you can't create list element by referencing them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top