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

File tree

4 files changed

+131
-0
lines changed

4 files changed

+131
-0
lines changed

knapsack/README.md

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# A naive recursive implementation of 0-1 Knapsack Problem
2+
3+
This overview is taken from:
4+
5+
https://en.wikipedia.org/wiki/Knapsack_problem
6+
7+
---
8+
9+
## Overview
10+
11+
The knapsack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most valuable items. The problem often arises in resource allocation where the decision makers have to choose from a set of non-divisible projects or tasks under a fixed budget or time constraint, respectively.
12+
13+
The knapsack problem has been studied for more than a century, with early works dating as far back as 1897 The name "knapsack problem" dates back to the early works of mathematician Tobias Dantzig (1884–1956), and refers to the commonplace problem of packing the most valuable or useful items without overloading the luggage.
14+
15+
---
16+
17+
## Documentation
18+
19+
This module uses docstrings to enable the use of Python's in-built `help(...)` function.
20+
For instance, try `help(Vector)`, `help(unitBasisVector)`, and `help(CLASSNAME.METHODNAME)`.
21+
22+
---
23+
24+
## Usage
25+
26+
Import the module `knapsack.py` from the **.** directory into your project.
27+
28+
---
29+
30+
## Tests
31+
32+
`.` contains Python unit tests which can be run with `python3 -m unittest -v`.

knapsack/__init__.py

Whitespace-only changes.

knapsack/knapsack.py

+47
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

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
Created on Fri Oct 16 09:31:07 2020
3+
4+
@author: Dr. Tobias Schröder
5+
@license: MIT-license
6+
7+
This file contains the test-suite for the knapsack problem.
8+
"""
9+
import unittest
10+
11+
from knapsack import knapsack as k
12+
13+
14+
class Test(unittest.TestCase):
15+
def test_base_case(self):
16+
"""
17+
test for the base case
18+
"""
19+
cap = 0
20+
val = [0]
21+
w = [0]
22+
c = len(val)
23+
self.assertEqual(k.knapsack(cap, w, val, c), 0)
24+
25+
val = [60]
26+
w = [10]
27+
c = len(val)
28+
self.assertEqual(k.knapsack(cap, w, val, c), 0)
29+
30+
def test_easy_case(self):
31+
"""
32+
test for the base case
33+
"""
34+
cap = 3
35+
val = [1, 2, 3]
36+
w = [3, 2, 1]
37+
c = len(val)
38+
self.assertEqual(k.knapsack(cap, w, val, c), 5)
39+
40+
def test_knapsack(self):
41+
"""
42+
test for the knapsack
43+
"""
44+
cap = 50
45+
val = [60, 100, 120]
46+
w = [10, 20, 30]
47+
c = len(val)
48+
self.assertEqual(k.knapsack(cap, w, val, c), 220)
49+
50+
51+
if __name__ == "__main__":
52+
unittest.main()

0 commit comments

Comments
 (0)