Skip to content

Commit 171481e

Browse files
committed
Address review feedback for knapsack_with_count
1 parent bc25a22 commit 171481e

2 files changed

Lines changed: 11 additions & 5 deletions

File tree

knapsack/knapsack.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def knapsack(
3737
got the weight of 10*5 which is the limit of the capacity.
3838
"""
3939

40-
@lru_cache
40+
@lru_cache(maxsize=None)
4141
def knapsack_recur(capacity: int, counter: int) -> int:
4242
# Base Case
4343
if counter == 0 or capacity == 0:
@@ -70,10 +70,14 @@ def knapsack_with_count(
7070
allow_repetition: bool = False,
7171
) -> tuple[int, int]:
7272
"""
73-
Return both the maximum knapsack value and the number of optimal subsets.
73+
Return both the maximum knapsack value and number of optimal selections.
7474
75-
The return value is ``(max_value, number_of_optimal_subsets)``.
75+
The return value is ``(max_value, number_of_optimal_selections)``.
7676
If multiple choices produce the same maximum value, their counts are added.
77+
Distinct selections are order-insensitive:
78+
- with ``allow_repetition=False`` these are distinct subsets by item index;
79+
- with ``allow_repetition=True`` these are distinct multisets by item index
80+
multiplicity.
7781
7882
>>> cap = 50
7983
>>> val = [60, 100, 120]
@@ -89,7 +93,7 @@ def knapsack_with_count(
8993
(2, 2)
9094
"""
9195

92-
@lru_cache
96+
@lru_cache(maxsize=None)
9397
def knapsack_recur(remaining_capacity: int, item_count: int) -> tuple[int, int]:
9498
# Base Case: one empty subset yields value 0.
9599
if item_count == 0 or remaining_capacity == 0:

knapsack/tests/test_knapsack.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,14 +60,16 @@ def test_knapsack_repetition(self):
6060

6161
def test_knapsack_with_count(self):
6262
"""
63-
test for maximum value and number of optimal subsets
63+
test for maximum value and number of optimal selections
6464
"""
6565
cap = 50
6666
val = [60, 100, 120]
6767
w = [10, 20, 30]
6868
c = len(val)
6969
assert k.knapsack_with_count(cap, w, val, c) == (220, 1)
7070
assert k.knapsack_with_count(cap, w, val, c, True) == (300, 1)
71+
assert k.knapsack_with_count(0, w, val, c) == (0, 1)
72+
assert k.knapsack_with_count(50, w, val, 0) == (0, 1)
7173

7274
def test_knapsack_with_count_ties(self):
7375
"""

0 commit comments

Comments
 (0)