0% found this document useful (0 votes)
5 views2 pages

Aoa5 Jency

The document presents a Python implementation of the 0/1 Knapsack Algorithm using dynamic programming. It includes functions to calculate the maximum profit and trace the selected items based on their weights and profits. The example provided uses modified profit and weight values to demonstrate the algorithm's functionality.

Uploaded by

Aniket Ugale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Aoa5 Jency

The document presents a Python implementation of the 0/1 Knapsack Algorithm using dynamic programming. It includes functions to calculate the maximum profit and trace the selected items based on their weights and profits. The example provided uses modified profit and weight values to demonstrate the algorithm's functionality.

Uploaded by

Aniket Ugale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Name: Jency Dabre Roll No: 61

Class: SE-CMPN-C3 Subject: AOAL


Program to implement 0/1 Knapsack Algorithm:

CODE:
def knapSack(W, val, wt):

n = len(val)

V = [[0] * (W + 1) for _ in range(n + 1)]

# Fill V table using dynamic programming

for i in range(1, n + 1):

for j in range(W + 1):

if wt[i - 1] <= j:

V[i][j] = max(V[i - 1][j], val[i - 1] + V[i - 1][j - wt[i - 1]])

else:

V[i][j] = V[i - 1][j]

return {

"maxProfit": V[n][W],

"selectedItems": traceKnapsack(wt, val, V, W)

def traceKnapsack(wt, val, V, W):

n = len(val)

selectedWeights = []

selectedProfits = []

i, j = n, W

while i > 0 and j > 0:

if V[i][j] != V[i - 1][j]:

selectedWeights.append(wt[i - 1])

selectedProfits.append(val[i - 1])

j -= wt[i - 1]

i -= 1
return {"selectedWeights": selectedWeights, "selectedProfits": selectedProfits}

# Modified Profits and Weights

profit = [45, 55, 95, 130, 85, 35, 25] # Slightly adjusted profit values

weight = [3, 4, 6, 2, 2, 4, 5] # Slightly adjusted weight values

W = 20

# Run the knapsack algorithm

result = knapSack(W, profit, weight)

# Print results

print("Maximum Profit:", result["maxProfit"])

print("Selected Weights:", result["selectedItems"]["selectedWeights"])

print("Selected Profits:", result["selectedItems"]["selectedProfits"])

OUTPUT:

You might also like