@@ -9,10 +9,10 @@ def frac_knapsack(values: list[int], weights: list[int], capacity: int, max_item
9
9
This function implements fractional knapsack problem.
10
10
11
11
Args:
12
- vl : List of values of items.
13
- wt : List of weights of items.
14
- w : Capacity of the knapsack.
15
- n : Number of items.
12
+ values : List of values of items.
13
+ weights : List of weights of items.
14
+ capacity : Capacity of the knapsack.
15
+ max_items : Number of items.
16
16
17
17
Returns:
18
18
Maximum value of items that can be put into the knapsack.
@@ -46,17 +46,19 @@ def frac_knapsack(values: list[int], weights: list[int], capacity: int, max_item
46
46
"""
47
47
48
48
# sort in descending order of value/weight ratio
49
- r = sorted (zip (vl , wt ), key = lambda x : x [0 ] / x [1 ], reverse = True , strict = True )
49
+ r = sorted (zip (values , weights ),
50
+ key = lambda x : x [0 ] / x [1 ], reverse = True )
50
51
51
- vl , wt = [i [0 ] for i in r ], [i [1 ] for i in r ] # unzip the list
52
- acc = list (accumulate (wt )) # cumulative sum of weights
53
- k = bisect (acc , w ) # find the index of the weight just greater than w
52
+ values , weights = [i [0 ] for i in r ], [i [1 ] for i in r ] # unzip the list
53
+ acc = list (accumulate (weights )) # cumulative sum of weights
54
+ # find the index of the weight just greater than capacity
55
+ k = bisect (acc , capacity )
54
56
55
57
if k == 0 : # no item can be put into the knapsack
56
58
return 0
57
- elif k != n : # fractional part of the kth item can be put into the knapsack
58
- return sum (vl [:k ]) + (w - acc [k - 1 ]) * (vl [k ]) / (wt [k ])
59
- return sum (vl [:k ]) # all items can be put into the knapsack
59
+ elif k != max_items : # fractional part of the kth item can be put into the knapsack
60
+ return sum (values [:k ]) + (capacity - acc [k - 1 ]) * (values [k ]) / (weights [k ])
61
+ return sum (values [:k ]) # all items can be put into the knapsack
60
62
61
63
62
64
if __name__ == "__main__" :
0 commit comments