Sa, Jsanxka
Sa, Jsanxka
Lab report
There are n items with price vi and weight wi. A robber has a bag with capacity w. We have to
create an algorithm to completely fill his bag after collecting the items in appropriate ratio such that
we get maximum profit.
Algorithm description
The input is path of the file containing number of items, capacity, item price and item weight. The
function starts by reading the file and separating n and w, and calculating the price of a single unit
of each item using formula vi/wi, and appending the value to a list. Then it sorts the list in
descending order wrt their ratio. Then it uses greedy method to get maximum amount from the most
precious item, followed by second. Then it calculates profit by multiplying amount collected to their
respective ratio. While adding if current capacity is less than item amount, it takes the item amount
equal to the current capacity. Else we add entire item amount to the capacity, till either the item
amount gets to 0 or the capacity is full. If it’s the first case, then we move on to next item, if it’s the
later then we exit the loop and return profit, round to 4 decimals.
Program
def knapsack(file_path):
l1 = file.read().split('\n')
d1 = []
l2 = l2[1:]
for i in range(n):
d1.append( ((int(l2[i][0]) / int(l2[i][1])), int(l2[i][0]), int(l2[i][1])))
d1.sort(reverse=True)
profit = 0
i=0
else:
cap -= d1[i][2]
profit += d1[i][1]
return round(profit, 4)
Sample runs
Acknowledgements
I would love to solve more problems like this and get your feedback for improvement.
Thank You