22 https://en.wikipedia.org/wiki/Knapsack_problem
33"""
44from __future__ import annotations
5+
56from functools import lru_cache
67
78
8- def knapsack (capacity : int , weights : list [int ], values : list [int ], counter : int , allow_repetition = False ) -> int :
9+ def knapsack (
10+ capacity : int ,
11+ weights : list [int ],
12+ values : list [int ],
13+ counter : int ,
14+ allow_repetition = False ,
15+ ) -> int :
916 """
1017 Returns the maximum value that can be put in a knapsack of a capacity cap,
11- whereby each weight w has a specific value val with option to allow repetitive selection of items
18+ whereby each weight w has a specific value val
19+ with option to allow repetitive selection of items
1220
1321 >>> cap = 50
1422 >>> val = [60, 100, 120]
@@ -24,10 +32,11 @@ def knapsack(capacity: int, weights: list[int], values: list[int], counter: int,
2432 300
2533
2634 Given the repetition is allowed,
27- tthe result is 300 cause the values of 60*5 (pick 5 times)
35+ the result is 300 cause the values of 60*5 (pick 5 times)
2836 which is the limit of the capacity.
2937 """
30- @lru_cache ()
38+
39+ @lru_cache
3140 def knapsack_recur (cap : int , c : int ) -> int :
3241 # Base Case
3342 if c == 0 or cap == 0 :
@@ -44,10 +53,15 @@ def knapsack_recur(cap: int, c: int) -> int:
4453 else :
4554 without_new_value = knapsack_recur (cap , c - 1 )
4655 if allow_repetition :
47- new_value_included = values [c - 1 ] + knapsack_recur (cap - weights [c - 1 ], c )
56+ new_value_included = values [c - 1 ] + knapsack_recur (
57+ cap - weights [c - 1 ], c
58+ )
4859 else :
49- new_value_included = values [c - 1 ] + knapsack_recur (cap - weights [c - 1 ], c - 1 )
60+ new_value_included = values [c - 1 ] + knapsack_recur (
61+ cap - weights [c - 1 ], c - 1
62+ )
5063 return max (new_value_included , without_new_value )
64+
5165 return knapsack_recur (capacity , counter )
5266
5367
0 commit comments