|
| 1 | +# https://en.wikipedia.org/wiki/Continuous_knapsack_problem |
| 2 | +# https://www.guru99.com/fractional-knapsack-problem-greedy.html |
| 3 | +# https://medium.com/walkinthecode/greedy-algorithm-fractional-knapsack-problem-9aba1daecc93 |
| 4 | + |
| 5 | +from typing import List, Tuple |
| 6 | + |
| 7 | + |
| 8 | +def fractional_knapsack( |
| 9 | + value: List[int], weight: List[int], capacity: int |
| 10 | +) -> Tuple[int, List[int]]: |
| 11 | + """ |
| 12 | + >>> value = [1, 3, 5, 7, 9] |
| 13 | + >>> weight = [0.9, 0.7, 0.5, 0.3, 0.1] |
| 14 | + >>> fractional_knapsack(value, weight, 5) |
| 15 | + (25, [1, 1, 1, 1, 1]) |
| 16 | + >>> fractional_knapsack(value, weight, 15) |
| 17 | + (25, [1, 1, 1, 1, 1]) |
| 18 | + >>> fractional_knapsack(value, weight, 25) |
| 19 | + (25, [1, 1, 1, 1, 1]) |
| 20 | + >>> fractional_knapsack(value, weight, 26) |
| 21 | + (25, [1, 1, 1, 1, 1]) |
| 22 | + >>> fractional_knapsack(value, weight, -1) |
| 23 | + (-90.0, [0, 0, 0, 0, -10.0]) |
| 24 | + >>> fractional_knapsack([1, 3, 5, 7], weight, 30) |
| 25 | + (16, [1, 1, 1, 1]) |
| 26 | + >>> fractional_knapsack(value, [0.9, 0.7, 0.5, 0.3, 0.1], 30) |
| 27 | + (25, [1, 1, 1, 1, 1]) |
| 28 | + >>> fractional_knapsack([], [], 30) |
| 29 | + (0, []) |
| 30 | + """ |
| 31 | + index = list(range(len(value))) |
| 32 | + ratio = [v / w for v, w in zip(value, weight)] |
| 33 | + index.sort(key=lambda i: ratio[i], reverse=True) |
| 34 | + |
| 35 | + max_value = 0 |
| 36 | + fractions = [0] * len(value) |
| 37 | + for i in index: |
| 38 | + if weight[i] <= capacity: |
| 39 | + fractions[i] = 1 |
| 40 | + max_value += value[i] |
| 41 | + capacity -= weight[i] |
| 42 | + else: |
| 43 | + fractions[i] = capacity / weight[i] |
| 44 | + max_value += value[i] * capacity / weight[i] |
| 45 | + break |
| 46 | + |
| 47 | + return max_value, fractions |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + n = int(input("Enter number of items: ")) |
| 52 | + value = input(f"Enter the values of the {n} item(s) in order: ").split() |
| 53 | + value = [int(v) for v in value] |
| 54 | + weight = input(f"Enter the positive weights of the {n} item(s) in order: ".split()) |
| 55 | + weight = [int(w) for w in weight] |
| 56 | + capacity = int(input("Enter maximum weight: ")) |
| 57 | + |
| 58 | + max_value, fractions = fractional_knapsack(value, weight, capacity) |
| 59 | + print("The maximum value of items that can be carried:", max_value) |
| 60 | + print("The fractions in which the items should be taken:", fractions) |
0 commit comments