55from functools import lru_cache
66
77
8- def knapsack (capacity : int , weights : list [int ], values : list [int ], counter : int , allow_repetition = False ) -> int :
8+ def knapsack (
9+ capacity : int ,
10+ weights : list [int ],
11+ values : list [int ],
12+ counter : int ,
13+ allow_repetition = False ,
14+ ) -> int :
915 """
1016 Returns the maximum value that can be put in a knapsack of a capacity cap,
1117 whereby each weight w has a specific value val with option to allow repetitive selection of items
@@ -27,6 +33,7 @@ def knapsack(capacity: int, weights: list[int], values: list[int], counter: int,
2733 tthe result is 300 cause the values of 60*5 (pick 5 times)
2834 which is the limit of the capacity.
2935 """
36+
3037 @lru_cache ()
3138 def knapsack_recur (cap : int , c : int ) -> int :
3239 # Base Case
@@ -44,10 +51,15 @@ def knapsack_recur(cap: int, c: int) -> int:
4451 else :
4552 without_new_value = knapsack_recur (cap , c - 1 )
4653 if allow_repetition :
47- new_value_included = values [c - 1 ] + knapsack_recur (cap - weights [c - 1 ], c )
54+ new_value_included = values [c - 1 ] + knapsack_recur (
55+ cap - weights [c - 1 ], c
56+ )
4857 else :
49- new_value_included = values [c - 1 ] + knapsack_recur (cap - weights [c - 1 ], c - 1 )
58+ new_value_included = values [c - 1 ] + knapsack_recur (
59+ cap - weights [c - 1 ], c - 1
60+ )
5061 return max (new_value_included , without_new_value )
62+
5163 return knapsack_recur (capacity , counter )
5264
5365
0 commit comments