From 59202db8f1607eb4983c0f2d811128b27db0d2b5 Mon Sep 17 00:00:00 2001 From: Sourabh Rana Date: Tue, 13 Oct 2020 23:20:27 +0530 Subject: [PATCH] fractional knapsack problem --- Fractionalknapsack.py | 53 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Fractionalknapsack.py diff --git a/Fractionalknapsack.py b/Fractionalknapsack.py new file mode 100644 index 0000000..a939f46 --- /dev/null +++ b/Fractionalknapsack.py @@ -0,0 +1,53 @@ +#fractional Knapsack +class ItemValue: + + + def __init__(self, wt, val, ind): + self.wt = wt + self.val = val + self.ind = ind + self.cost = val // wt + + + def __gt__(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)) + + # sorting items by value + iVal.sort(reverse = True) + # sort in decreasing order + 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 + +# Driver Code +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) + +