Here's an implementation of the dynamic programming approach to solve the knapsack problem in Python:
main.py495 chars17 lines
This function takes four inputs:
W
: the capacity of the knapsackwt
: a list of the weights of the itemsval
: a list of the values of the itemsn
: the number of itemsIt 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.py56 chars2 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