Skip to content

Commit c542f2b

Browse files
Jiang15Jiang15
authored andcommitted
wei/refactor code
1 parent eaf87c6 commit c542f2b

2 files changed

Lines changed: 21 additions & 6 deletions

File tree

knapsack/knapsack.py

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,21 @@
22
https://en.wikipedia.org/wiki/Knapsack_problem
33
"""
44
from __future__ import annotations
5+
56
from 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

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)