MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / mf_knapsack

Function mf_knapsack

dynamic_programming/knapsack.py:10–26  ·  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 ``-1`` s filled up

(i, wt, val, j)

Source from the content-addressed store, hash-verified

8
9
10def mf_knapsack(i, wt, val, j):
11 """
12 This code involves the concept of memory functions. Here we solve the subproblems
13 which are needed unlike the below example
14 F is a 2D array with ``-1`` s filled up
15 """
16 global f # a global dp table for knapsack
17 if f[i][j] < 0:
18 if j < wt[i - 1]:
19 val = mf_knapsack(i - 1, wt, val, j)
20 else:
21 val = max(
22 mf_knapsack(i - 1, wt, val, j),
23 mf_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1],
24 )
25 f[i][j] = val
26 return f[i][j]
27
28
29def knapsack(w, wt, val, n):

Callers 1

knapsack.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected