Tuesday, May 7, 2019

Knapsack with Python3

class ItemValue:
    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:
    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
  
# Driver Code
if __name__ == "__main__":
    wt = [15, 20, 25]
    val = [10, 15, 18]
    capacity = 20
  
    maxValue = FractionalKnapSack.getMaxValue(wt, val, capacity)
    print("Maximum value in Knapsack = ", maxValue)

No comments:

Post a Comment