Skip to content

Commit 85b9c59

Browse files
function for the knapsack problem which returns one of the optimal subsets
1 parent f2994cf commit 85b9c59

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

dynamic_programming/knapsack.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
"""
22
Given 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+
4+
Note that only the integer weights 0-1 knapsack problem is solvable using dynamic programming.
35
"""
6+
from __future__ import print_function, division, absolute_import
7+
48

5-
def MF_knapsack(i, wt, val, j):
9+
def MF_knapsack(i,wt,val,j):
610
'''
711
This code involves the concept of memory functions. Here we solve the subproblems which are needed
812
unlike the below example
@@ -13,8 +17,7 @@ def MF_knapsack(i, wt, val, j):
1317
if j < wt[i - 1]:
1418
val = MF_knapsack(i - 1,wt,val,j)
1519
else:
16-
val = max(MF_knapsack(i - 1, wt, val, j),
17-
MF_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1])
20+
val = max(MF_knapsack(i - 1,wt,val,j),MF_knapsack(i - 1,wt,val,j - wt[i - 1]) + val[i - 1])
1821
F[i][j] = val
1922
return F[i][j]
2023

@@ -123,8 +126,7 @@ def _construct_solution(dp, wt, i, j, optimal_set):
123126
wt = [4, 3, 2, 3]
124127
n = 4
125128
w = 6
126-
F = [[0]*(w + 1)] + [[0] + [-1 for i in range(w + 1)] for j in range(n + 1)]
127-
129+
F = [[0] * (w + 1)] + [[0] + [-1 for i in range(w + 1)] for j in range(n + 1)]
128130
optimal_solution, _ = knapsack(w,wt,val, n)
129131
print(optimal_solution)
130132
print(MF_knapsack(n,wt,val,w)) # switched the n and w

0 commit comments

Comments
 (0)