Skip to content

Commit 962d71c

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent eaf87c6 commit 962d71c

2 files changed

Lines changed: 16 additions & 3 deletions

File tree

knapsack/knapsack.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,13 @@
55
from 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

knapsack/tests/test_knapsack.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,5 +57,6 @@ def test_knapsack_repetition(self):
5757
c = len(val)
5858
self.assertEqual(k.knapsack(cap, w, val, c, True), 300)
5959

60+
6061
if __name__ == "__main__":
6162
unittest.main()

0 commit comments

Comments
 (0)