amir_rj
amir_rj

Reputation: 1

get the element of a list in knapsack 0-1

I have this python code solving knapsack problem using dynamic programming. this function returns the total cost of best subset but I want it to return the elements of best subset . can anybody help me with this?

def knapSack(W, wt, val, n):
    K = [[0 for x in range(W + 1)] for x in range(n + 1)]

    # Build table K[][] 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 K[n][W]


val = [40, 100, 120,140]
wt = [1, 2, 3,4]
W = 4
n = len(val)
print(knapSack(W, wt, val, n))

Upvotes: 0

Views: 1851

Answers (2)

Todd Burus
Todd Burus

Reputation: 983

You can add this code to the end of your function to work your way back through the items added:

res = K[n][W]
print(res)

w = W
for i in range(n, 0, -1):
    if res <= 0:
        break

    if res == K[i - 1][w]:
        continue
    else:
        print(wt[i - 1])

        res = res - val[i - 1]
        w = w - wt[i - 1]

Upvotes: 0

Arka Pal
Arka Pal

Reputation: 275

What you can do is instead of returning only K[n][W], return K Then iterate K as :

elements=list()
dp=K
w = W
i = n
while (i> 0):
  if dp[w][i] - dp[w - wt(i)][i-1] == val(i):
     #the element 'i' is in the knapsack
     element.append(i)
     i = i-1 //only in 0-1 knapsack
     w -=wt(i)
  else: 
     i = i-1 

The idea is you reverse iterate the K matrix to determine which elements' values were added to get to the optimum K[W][n] value.

Upvotes: 2

Related Questions