MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / knapsack_recur

Function knapsack_recur

knapsack/knapsack.py:41–60  ·  view source on GitHub ↗
(capacity: int, counter: int)

Source from the content-addressed store, hash-verified

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

Callers 1

knapsackFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected