0% found this document useful (0 votes)
9 views3 pages

ADA p5 103

Uploaded by

soyik35468
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)
9 views3 pages

ADA p5 103

Uploaded by

soyik35468
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/ 3

PEN : 220840131103

Practical :- 5
Aim :- Implementation of a knapsack problem using dynamic
programming.
Tool :- Google Colab, Python

The Knapsack problem is a combinatorial optimization problem that involves


selecting items with given weights and values to maximize the total value while
staying within a specific weight limit. It is a classic problem in computer science
and operations research, with many applications such as resource allocation,
finance, and logistics. The dynamic programming approach to the knapsack
problem is particularly useful because it breaks the problem down into smaller
subproblems, solving each subproblem only once and storing its solution for
future reference. This reduces the time complexity significantly compared to a
brute-force approach.

In the dynamic programming solution, a table is constructed where each entry


represents the maximum value that can be achieved with a certain weight limit
using a subset of the available items. The algorithm iterates over the items and
weight capacities, updating the table based on whether including an item leads to
a higher value without exceeding the weight limit. By filling out this table, the
solution to the original problem is found in a bottom-up manner, providing an
efficient way to solve the knapsack problem with a time complexity of O(nW),
where n is the number of items and W is the maximum weight capacity of the
knapsack.

|Page
PEN : 220840131103

Code :-
import random as rd

def knapsack(values, weights, W):


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

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


for w in range(1, W + 1):
if weights[i - 1] <= w:
V[i][w] = max(V[i - 1][w], V[i - 1][w - weights[i - 1]] + values[i - 1])
else:
V[i][w] = V[i - 1][w]

col_width = max(len(str(V[i][w])) for i in range(n + 1) for w in range(W + 1)) + 2

print("Value Table:\n")

header = "Weight limit: " + "".join(f"{i:>{col_width}}" for i in range(W + 1))


separator = "-" * 20 + "----" * (W + 1)
print(header)
print(separator)

for i in range(n):
row = f"W{i+1} = {weights[i]:<{col_width - 2}}, V{i+1} = {values[i]:<{col_width -
2}} :" + "".join(f"{V[i + 1][w]:>{col_width}}" for w in range(W + 1))
print(row)

included_items = []
item_weights = []
w=W
for i in range(n, 0, -1):
if V[i][w] != V[i - 1][w]:
included_items.append(i)
item_weights.append(weights[i - 1])
w -= weights[i - 1]

total_value = V[n][W]
included_items.reverse()
item_weights.reverse()

print("\nAnswer:")
print(f"Total Value: {total_value}")
print(f"Total Weight: {W}")
print(f"Used Weight: {sum(item_weights)}")
print(f"Objects Included in Knapsack: {{ {', '.join(map(str, included_items))} }}")

|Page
PEN : 220840131103

print("Weights of Included Objects:")


for i, weight in zip(included_items, item_weights):
print(f"Object {i}: Weight {weight}")

rd.seed(4)
values = rd.sample(range(1, 50), 5)
weights = rd.sample(range(1, 20), 5)
W = rd.randint(10, 30)

knapsack(values, weights, W)

OUTPUT :-

|Page

You might also like