0% found this document useful (0 votes)
40 views

Knapsack Algo

This document defines a knapsack problem as a list of items each with a weight and value. It initializes a table to track solutions and fills it using dynamic programming to find the maximum value for a knapsack of capacity 10. It then traces back through the table to find which items were included for the optimal solution.

Uploaded by

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

Knapsack Algo

This document defines a knapsack problem as a list of items each with a weight and value. It initializes a table to track solutions and fills it using dynamic programming to find the maximum value for a knapsack of capacity 10. It then traces back through the table to find which items were included for the optimal solution.

Uploaded by

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

# Define the items as a list of tuples (weight, value)

items = [(2, 6), (3, 5), (4, 8), (5, 9)]

# Define the capacity of the knapsack


capacity = 10

# Initialize the table with zeros


table = [[0 for j in range(capacity + 1)] for i in range(len(items) + 1)]

# Fill in the table using dynamic programming


for i in range(1, len(items) + 1):
for j in range(1, capacity + 1):
weight, value = items[i-1]
if weight <= j:
table[i][j] = max(table[i-1][j], table[i-1][j-weight] + value)
else:
table[i][j] = table[i-1][j]

# Find the items that were included in the solution


i = len(items)
j = capacity
included_items = []
while i > 0 and j > 0:
weight, value = items[i-1]
if table[i][j] != table[i-1][j]:
included_items.append(i-1)
j -= weight
i -= 1

# Reverse the list of included items


included_items = included_items[::-1]

# Print the table and the solution


print("Table:")
for row in table:
print(row)
print("Maximum value:", table[-1][-1])
print("Included items:", included_items)

You might also like