Knapsack project

Here is a simple Python implementation for computing the optimal value and solution for the Knapsack problem.

The input file is formated so that the first line specifies the pair of values n, W for the problem. Following that are n subsequent lines, each specifying the pair of values vi, wi for the ith item. As an example, here is the example we worked in class with n=7 and W=15.

7 15
8 7
3 2
5 7
4 5
9 6
1 2
2 4

The heart of the dynamic programming algorithm in this case is implemented as

def solve(n,W,val,weight):
    table = [ [0] * (W+1) ]                     # base case row is all zeroes
    for i in range(1,n+1):
        table.append( list(table[i-1])  )       # by default row i entries are based on row i-1
        for w in range(1,W+1):
            if weight[i] <= w:                  # alternate case is when using item i
                alternate = val[i] + table[i-1][w-weight[i]]
                if alternate > table[i][w]:
                    table[i][w] = alternate     

    return table

The program builds the table of values for the parameterized subproblems and then also reconstructs the actual set of items achieving the optimal solution. For the above item, it is possible to achieve a value of 20 using items 1, 2, and 5. The complete table in this case is displayed as

7 |  0  0  3  3  4  4  9  9 12 12 13 13 14 17 17 20
6 |  0  0  3  3  4  4  9  9 12 12 13 13 13 17 17 20
5 |  0  0  3  3  3  4  9  9 12 12 12 13 13 17 17 20
4 |  0  0  3  3  3  4  4  8  8 11 11 11 12 12 15 15
3 |  0  0  3  3  3  3  3  8  8 11 11 11 11 11 13 13
2 |  0  0  3  3  3  3  3  8  8 11 11 11 11 11 11 11
1 |  0  0  0  0  0  0  0  8  8  8  8  8  8  8  8  8
0 |  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
  +------------------------------------------------
     0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15


Michael Goldwasser
Last modified: Friday, 11 April 2008