MCPcopy Create free account
hub / github.com/subbarayudu-j/TheAlgorithms-Python / MF_knapsack

Function MF_knapsack

dynamic_programming/knapsack.py:4–17  ·  view source on GitHub ↗

This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with -1s filled up

(i,wt,val,j)

Source from the content-addressed store, hash-verified

2Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack.
3"""
4def MF_knapsack(i,wt,val,j):
5 '''
6 This code involves the concept of memory functions. Here we solve the subproblems which are needed
7 unlike the below example
8 F is a 2D array with -1s filled up
9 '''
10 global F # a global dp table for knapsack
11 if F[i][j] < 0:
12 if j < wt[i - 1]:
13 val = MF_knapsack(i - 1,wt,val,j)
14 else:
15 val = max(MF_knapsack(i - 1,wt,val,j),MF_knapsack(i - 1,wt,val,j - wt[i - 1]) + val[i - 1])
16 F[i][j] = val
17 return F[i][j]
18
19def knapsack(W, wt, val, n):
20 dp = [[0 for i in range(W+1)]for j in range(n+1)]

Callers 1

knapsack.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected