Returns the maximum value that can be put in a knapsack of a capacity cap, whereby each weight w has a specific value val with option to allow repetitive selection of items >>> cap = 50 >>> val = [60, 100, 120] >>> w = [10, 20, 30] >>> c = len(val) >>> knapsack(cap,
(
capacity: int,
weights: list[int],
values: list[int],
counter: int,
allow_repetition=False,
)
| 8 | |
| 9 | |
| 10 | def knapsack( |
| 11 | capacity: int, |
| 12 | weights: list[int], |
| 13 | values: list[int], |
| 14 | counter: int, |
| 15 | allow_repetition=False, |
| 16 | ) -> int: |
| 17 | """ |
| 18 | Returns the maximum value that can be put in a knapsack of a capacity cap, |
| 19 | whereby each weight w has a specific value val |
| 20 | with option to allow repetitive selection of items |
| 21 | |
| 22 | >>> cap = 50 |
| 23 | >>> val = [60, 100, 120] |
| 24 | >>> w = [10, 20, 30] |
| 25 | >>> c = len(val) |
| 26 | >>> knapsack(cap, w, val, c) |
| 27 | 220 |
| 28 | |
| 29 | Given the repetition is NOT allowed, |
| 30 | the result is 220 cause the values of 100 and 120 got the weight of 50 |
| 31 | which is the limit of the capacity. |
| 32 | >>> knapsack(cap, w, val, c, True) |
| 33 | 300 |
| 34 | |
| 35 | Given the repetition is allowed, |
| 36 | the result is 300 cause the values of 60*5 (pick 5 times) |
| 37 | got the weight of 10*5 which is the limit of the capacity. |
| 38 | """ |
| 39 | |
| 40 | @lru_cache |
| 41 | def knapsack_recur(capacity: int, counter: int) -> int: |
| 42 | # Base Case |
| 43 | if counter == 0 or capacity == 0: |
| 44 | return 0 |
| 45 | |
| 46 | # If weight of the nth item is more than Knapsack of capacity, |
| 47 | # then this item cannot be included in the optimal solution, |
| 48 | # else return the maximum of two cases: |
| 49 | # (1) nth item included only once (0-1), if allow_repetition is False |
| 50 | # nth item included one or more times (0-N), if allow_repetition is True |
| 51 | # (2) not included |
| 52 | if weights[counter - 1] > capacity: |
| 53 | return knapsack_recur(capacity, counter - 1) |
| 54 | else: |
| 55 | left_capacity = capacity - weights[counter - 1] |
| 56 | new_value_included = values[counter - 1] + knapsack_recur( |
| 57 | left_capacity, counter - 1 if not allow_repetition else counter |
| 58 | ) |
| 59 | without_new_value = knapsack_recur(capacity, counter - 1) |
| 60 | return max(new_value_included, without_new_value) |
| 61 | |
| 62 | return knapsack_recur(capacity, counter) |
| 63 | |
| 64 | |
| 65 | if __name__ == "__main__": |
nothing calls this directly
no test coverage detected