Skip to content

Commit 93ad7db

Browse files
Create recursive_approach_knapsack.py (TheAlgorithms#7587)
* Create recursive_approach_knapsack.py Added a new naïve recursive approach to solve the knapsack problem. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update recursive_approach_knapsack.py Updated the code * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update recursive_approach_knapsack.py Updated * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 584e743 commit 93ad7db

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# To get an insight into naive recursive way to solve the Knapsack problem
2+
3+
4+
"""
5+
A shopkeeper has bags of wheat that each have different weights and different profits.
6+
eg.
7+
no_of_items 4
8+
profit 5 4 8 6
9+
weight 1 2 4 5
10+
max_weight 5
11+
Constraints:
12+
max_weight > 0
13+
profit[i] >= 0
14+
weight[i] >= 0
15+
Calculate the maximum profit that the shopkeeper can make given maxmum weight that can
16+
be carried.
17+
"""
18+
19+
20+
def knapsack(
21+
weights: list, values: list, number_of_items: int, max_weight: int, index: int
22+
) -> int:
23+
"""
24+
Function description is as follows-
25+
:param weights: Take a list of weights
26+
:param values: Take a list of profits corresponding to the weights
27+
:param number_of_items: number of items available to pick from
28+
:param max_weight: Maximum weight that could be carried
29+
:param index: the element we are looking at
30+
:return: Maximum expected gain
31+
>>> knapsack([1, 2, 4, 5], [5, 4, 8, 6], 4, 5, 0)
32+
13
33+
>>> knapsack([3 ,4 , 5], [10, 9 , 8], 3, 25, 0)
34+
27
35+
"""
36+
if index == number_of_items:
37+
return 0
38+
ans1 = 0
39+
ans2 = 0
40+
ans1 = knapsack(weights, values, number_of_items, max_weight, index + 1)
41+
if weights[index] <= max_weight:
42+
ans2 = values[index] + knapsack(
43+
weights, values, number_of_items, max_weight - weights[index], index + 1
44+
)
45+
return max(ans1, ans2)
46+
47+
48+
if __name__ == "__main__":
49+
50+
import doctest
51+
52+
doctest.testmod()

0 commit comments

Comments
 (0)