Skip to content

Commit f647070

Browse files
committed
Renamed the variables
1 parent b0a5d6d commit f647070

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

Diff for: greedy_methods/fractional_knapsack.py

+13-11
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@ def frac_knapsack(values: list[int], weights: list[int], capacity: int, max_item
99
This function implements fractional knapsack problem.
1010
1111
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.
1616
1717
Returns:
1818
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
4646
"""
4747

4848
# 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)
5051

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)
5456

5557
if k == 0: # no item can be put into the knapsack
5658
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
6062

6163

6264
if __name__ == "__main__":

0 commit comments

Comments
 (0)