create a function that sokves the knapsack problem in python

Here's an implementation of the dynamic programming approach to solve the knapsack problem in Python:

main.py
def knapsack(W, wt, val, n):
    # initialize memoization table with zeros
    K = [[0 for x in range(W+1)] for x in range(n+1)]

    # build memoization table in bottom-up manner
    for i in range(n+1):
        for w in range(W+1):
            if i==0 or w==0:
                K[i][w] = 0
            elif wt[i-1] <= w:
                K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]],  K[i-1][w])
            else:
                K[i][w] = K[i-1][w]

    # return maximum value
    return K[n][W]
495 chars
17 lines

This function takes four inputs:

  • W: the capacity of the knapsack
  • wt: a list of the weights of the items
  • val: a list of the values of the items
  • n: the number of items

It returns the maximum value that can be obtained by filling the knapsack to its capacity without exceeding the capacity. The function implements the dynamic programming approach where a memoization table is first initialized with zeros and then built in a bottom-up manner to obtain the maximum value using the recurrence relation:

main.py
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]],  K[i-1][w])
56 chars
2 lines

The recurrence relation computes the maximum value for each combination of i (items) and w (knapsack capacity). Once the entire memoization table is built, the maximum value is returned in the cell K[n][W].

Note that this implementation assumes that the input lists wt and val are of length n. If they are not, you may need to modify the code accordingly.

gistlibby LogSnag