EXPERIMENT -8
Aim: WAP to implement Knapsack Problem using greedy algorithm.
Theory:
Weights and values of n items, we need to put these items in a knapsack of capacity W to get
the maximum total value in the knapsack.
In the 0-1 knapsack problem, we are not allowed to break items. We either take the whole item
or don’t take it.
An efficient solution is to use Greedy approach. The basic idea of the greedy approach is to
calculate the ratio value/weight for each item and sort the item on basis of this ratio. Then take
the item with the highest ratio and add them until we can’t add the next item as a whole and at
the end add the next item as much as we can. Which will always be the optimal solution to this
problem.
A simple code with our own comparison function can be written as follows, please see sort
function more closely, the third argument to sort function is our comparison function which
sorts the item according to value/weight ratio in non-decreasing order.
After sorting we need to loop over these items and add them in our knapsack satisfying above-
mentioned criteria.
CODING:
class ItemValue:
def __init__(self, wt, val, ind):
self.wt = wt
self.val = val
self.ind = ind
self.cost = val
def __lt__(self, other):
return self.cost < other.cost
class FractionalKnapSack:
@staticmethod
def getMaxValue(wt, val, capacity):
iVal = []
for i in range(len(wt)):
iVal.append(ItemValue(wt[i], val[i], i))
iVal.sort(reverse=True)
totalValue = 0
for i in iVal:
curWt = int(i.wt)
curVal = int(i.val)
if capacity - curWt >= 0:
capacity -= curWt
totalValue += curVal
else:
fraction = capacity / curWt
totalValue += curVal * fraction
capacity = int(capacity - (curWt * fraction))
break
return totalValue
if __name__ == "__main__":
wt = [10, 40, 20, 30]
val = [60, 40, 100, 120]
capacity = 50
maxValue = FractionalKnapSack.getMaxValue(wt, val, capacity)
print("Maximum value in Knapsack =", maxValue)
OUTPUT:
RESULT:
The program is successfully done and compiled in python.