Add a naive recursive implementation of 0-1 Knapsack Problem (#2743) · zinating/algorithms-python@802ac83 · GitHub
Skip to content

Commit 802ac83

Browse files
authored
Add a naive recursive implementation of 0-1 Knapsack Problem (TheAlgorithms#2743)
* Add naive recursive implementation of 0-1 Knapsack problem * Fix shadowing * Add doctest * Fix type hints * Add link to wiki * Blacked the file * Fix isort * Move knapsack / add readme and more tests * Add missed main in tests
1 parent 79d5755 commit 802ac83

4 files changed

Lines changed: 131 additions & 0 deletions

File tree

knapsack/README.md

Lines changed: 32 additions & 0 deletions

knapsack/__init__.py

Whitespace-only changes.

knapsack/knapsack.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from typing import List
2+
3+
""" A naive recursive implementation of 0-1 Knapsack Problem
4+
https://en.wikipedia.org/wiki/Knapsack_problem
5+
"""
6+
7+
8+
def knapsack(capacity: int, weights: List[int], values: List[int], counter: int) -> int:
9+
"""
10+
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.
12+
13+
>>> cap = 50
14+
>>> val = [60, 100, 120]
15+
>>> w = [10, 20, 30]
16+
>>> c = len(val)
17+
>>> knapsack(cap, w, val, c)
18+
220
19+
20+
The result is 220 cause the values of 100 and 120 got the weight of 50
21+
which is the limit of the capacity.
22+
"""
23+
24+
# Base Case
25+
if counter == 0 or capacity == 0:
26+
return 0
27+
28+
# If weight of the nth item is more than Knapsack of capacity,
29+
# then this item cannot be included in the optimal solution,
30+
# else return the maximum of two cases:
31+
# (1) nth item included
32+
# (2) not included
33+
if weights[counter - 1] > capacity:
34+
return knapsack(capacity, weights, values, counter - 1)
35+
else:
36+
left_capacity = capacity - weights[counter - 1]
37+
new_value_included = values[counter - 1] + knapsack(
38+
left_capacity, weights, values, counter - 1
39+
)
40+
without_new_value = knapsack(capacity, weights, values, counter - 1)
41+
return max(new_value_included, without_new_value)
42+
43+
44+
if __name__ == "__main__":
45+
import doctest
46+
47+
doctest.testmod()

knapsack/test_knapsack.py

Lines changed: 52 additions & 0 deletions

0 commit comments

Comments
 (0)