0

I am implementing the 0/1 Knapsack problem using Dynamic Programming. However, when the number of items or the sack capacity is too large, my algorithm fails to complete, giving rise to an exception. It is a simple DP algorithm which creates a 2D-matrix for item no. vs capacity. Here is my code snippet:

def solve_it(input_data):
    # Modify this code to run your optimization algorithm
    
    # parse the input
    lines = input_data.split('\n')

    firstLine = lines[0].split()
    item_count = int(firstLine[0])
    capacity = int(firstLine[1])

    
    vals=[]
    weights=[]

    for i in range(1, item_count+1):
        line = lines[i] 
        parts = line.split() 
        #items.append(Item(i-1, int(parts[0]), int(parts[1]))) 
        vals.append(int(parts[0])) 
        weights.append(int(parts[1])) 
    taken=[0 for i in range(len(weights))]    
    list=[[0 for j in range(capacity + 1)] for i in range(len(weights) + 1)]
    for item in range(len(weights)+1):             
        for wt in range(capacity + 1): 
            if item==0 or wt==0:
                list[item][wt]=0  
            elif weights[item-1]<=wt: 
                if (vals[item-1]+list[item-1][wt-weights[item-1]])>=list[item-1][wt]:  
                    list[item][wt]=vals[item-1]+list[item-1][wt-weights[item-1]] 
                else:  
                    list[item][wt]=list[item-1][wt] 
            else: 
                list[item][wt]=list[item-1][wt] 
    n=item_count
    w=capacity 
    while n>0: 
          if list[n][w]!=list[n-1][w]:
              taken[n-1]=1
              w=w-weights[n-1]
          n-=1    
                
    value=list[item_count][capacity]
    if capacity> sum(weights[:]):
        opt=0
    else:
        opt=1
        
    
    # prepare the solution in the specified output format
    output_data = str(value) + ' ' + str(opt) + '\n'
    output_data += ' '.join(map(str, taken))
    return output_data 

Any ideas to improve the execution time ?

  • The knapsack problem is a combinatorial problem that is NP-hard (https://en.wikipedia.org/wiki/Knapsack_problem). Generally, that means it is extremely hard to solve the problem as the number of variables increase. There seems to be a polynomial time approach to solving the knapsack problem, so you may want to have a look at that (https://en.wikipedia.org/wiki/Pseudo-polynomial_time). That said even in linear time at some point you'd hit a wall. – k88 Jul 15 '20 at 05:53
  • Does anyone have an idea how we can add the A* heuristic along with this? It was mentioned somewhere that this would work. – Divyayan Dey Jul 15 '20 at 05:56
  • I don't think it is straightforward to use the A* heuristic with the knapsack problem. The A* heuristic is a graph traversal algorithm, so if you know how to model the knapsack as a graph it won't be straightforward. I would suggest looking into an optimization algorithm as tabu search, genetic algorithms, linear programming etc. – k88 Jul 15 '20 at 06:03

0 Answers0