Question: import itertools def knapsack ( C , W , V ) : # Generate all possible combinations of items combinations = list ( itertools .

import itertools
def knapsack(C, W, V):
# Generate all possible combinations of items
combinations = list(itertools.product([0,1], repeat=len(W)))
# Calculate the value and weight of each combination
values =[]
weights =[]
for comb in combinations:
value = sum([V[i] for i in range(len(W)) if comb[i]==1])
weight = sum([W[i] for i in range(len(W)) if comb[i]==1])
values.append(value)
weights.append(weight)
# Find the combination with maximum value and weight under the knapsack capacity
max_value =0
max_weight =0
max_combination = None
for i in range(len(combinations)):
if weights[i]<= C and values[i]> max_value:
max_value = values[i]
max_weight = weights[i]
max_combination = combinations[i]
# Create the list of picked items
P =[int(b) for b in max_combination]
return P, max_value, max_weight
# Test the function
C =15
W =[11,2,1,4,1]
V =[4,2,1,10,2]
P, total_value, total_weight = knapsack(C, W, V)
print("Items Picked P =", P)
print("Total value of picked items =", total_value)
print("Total weight of picked items =", total_weight)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!