diff --git a/knapsackproblem.py b/knapsackproblem.py index aed8229..f994e31 100644 --- a/knapsackproblem.py +++ b/knapsackproblem.py @@ -1,30 +1,56 @@ -items =[ -["A",24,12,"complete"], -["B",13,7,"complete"], -["C",23,11,"complete"], -["D",15,8,"complete"], -["E",16,9,"complete"], -["F",15,3,"complete"]] -sum = 0 -size = 14 -profit = 0 -new = sorted(items,key=lambda x: x[1],reverse = True) -final =[] -# new.sort(reverse = True) -for i in range(0,len(items)): - while(sumsize): - sum = size - final[len(final)-1][3]='partial' -print("\n") -for i in range(len(final)): - print(final[i]) -print("\n") -print(profit) -print("\n") - -print(sum) + +#greedyoption +#program to solve fractional +# Knapsack Problem +class ItemValue: + + """Item Value DataClass""" + def __init__(self, wt, val, ind): + self.wt = wt + self.val = val + self.ind = ind + self.cost = val // wt + + def __lt__(self, other): + return self.cost < other.cost + +# Greedy Approach +class FractionalKnapSack: + + """Time Complexity O(n log n)""" + @staticmethod + def getMaxValue(wt, val, capacity): + + """function to get maximum value """ + iVal = [] + for i in range(len(wt)): + iVal.append(ItemValue(wt[i], val[i], i)) + + # sorting items by value + 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 + +# 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) + + +