218k views
2 votes
Suppose you are an art thief (not a good start) who has broken into an art gallery. All you have to haul out your stolen art is your briefcase, which holds only W pounds of art and, for every piece of art, you know its weight and its value. Dataset is as follows: Items 1, 2, 3, 4, and 5 have weights 1, 2, 5, 6, 7 and value 1, 6, 18, 22, and 28, respectively.Let W = 11.

Required:
Builds a solution for Dataset 2 using W = 11 as the weight limit.

1 Answer

2 votes

Answer:

We have to use general knapsack problem algorithm.

I have used that and written a function to write the output to a csv file where we can see the value that can be gained for a given item and given knapsack size (briefcase size in pounds).

Python Code :-

def writeResultsToFile(K): ## displaying the output result better

f=open("result.csv","w")

item=0

f.write(",");

for i in range(len(K[0])):

f.write("BRIEFCASE SIZE = "+str(i)+" POUNDS ,")

f.write("\\")

for i in K:

f.write("ITEM "+str(item)+",")

item+=1

for j in i:

f.write(str(j)+',')

f.write('\\')

def knapSack(W, wt, val, n): ## general knapsack algorithm

K = [[0 for x in range(W+1)] for x in range(n+1)]

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]

writeResultsToFile(K) ## pass the knapsack array to function to analyse better

return K[n][W]

val = [1, 6, 18, 22, 28]

wt = [1, 2, 5, 6, 7]

W = 11

n = len(val)

print(knapSack(W, wt, val, n))

User Kevdliu
by
3.6k points