File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #fractional Knapsack
2+ class ItemValue :
3+
4+
5+ def __init__ (self , wt , val , ind ):
6+ self .wt = wt
7+ self .val = val
8+ self .ind = ind
9+ self .cost = val // wt
10+
11+
12+ def __gt__ (self , other ):
13+ return self .cost > other .cost
14+
15+
16+ class FractionalKnapSack :
17+
18+ @staticmethod
19+ def getMaxValue (wt , val , capacity ):
20+
21+
22+ iVal = []
23+ for i in range (len (wt )):
24+ iVal .append (ItemValue (wt [i ], val [i ], i ))
25+
26+ # sorting items by value
27+ iVal .sort (reverse = True )
28+ # sort in decreasing order
29+ totalValue = 0
30+
31+ for i in iVal :
32+ curWt = int (i .wt )
33+ curVal = int (i .val )
34+ if capacity - curWt >= 0 :
35+ capacity -= curWt
36+ totalValue += curVal
37+ else :
38+ fraction = capacity / curWt
39+ totalValue += curVal * fraction
40+ capacity = int (capacity - (curWt * fraction ))
41+ break
42+ return totalValue
43+
44+ # Driver Code
45+ if __name__ == "__main__" :
46+ wt = [10 , 40 , 20 , 30 ]
47+ val = [60 , 40 , 100 , 120 ]
48+ capacity = 50
49+
50+ maxValue = FractionalKnapSack .getMaxValue (wt , val , capacity )
51+ print ("Maximum value in Knapsack =" , maxValue )
52+
53+
You can’t perform that action at this time.
0 commit comments