From 93ad7db97fa211b6e9f77025513a45df83400f88 Mon Sep 17 00:00:00 2001 From: JatinR05 <71865805+JatinR05@users.noreply.github.com> Date: Sat, 29 Oct 2022 18:58:12 +0530 Subject: [PATCH] Create recursive_approach_knapsack.py (#7587) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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> --- knapsack/recursive_approach_knapsack.py | 52 +++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 knapsack/recursive_approach_knapsack.py diff --git a/knapsack/recursive_approach_knapsack.py b/knapsack/recursive_approach_knapsack.py new file mode 100644 index 000000000..d813981cb --- /dev/null +++ b/knapsack/recursive_approach_knapsack.py @@ -0,0 +1,52 @@ +# To get an insight into naive recursive way to solve the Knapsack problem + + +""" +A shopkeeper has bags of wheat that each have different weights and different profits. +eg. +no_of_items 4 +profit 5 4 8 6 +weight 1 2 4 5 +max_weight 5 +Constraints: +max_weight > 0 +profit[i] >= 0 +weight[i] >= 0 +Calculate the maximum profit that the shopkeeper can make given maxmum weight that can +be carried. +""" + + +def knapsack( + weights: list, values: list, number_of_items: int, max_weight: int, index: int +) -> int: + """ + Function description is as follows- + :param weights: Take a list of weights + :param values: Take a list of profits corresponding to the weights + :param number_of_items: number of items available to pick from + :param max_weight: Maximum weight that could be carried + :param index: the element we are looking at + :return: Maximum expected gain + >>> knapsack([1, 2, 4, 5], [5, 4, 8, 6], 4, 5, 0) + 13 + >>> knapsack([3 ,4 , 5], [10, 9 , 8], 3, 25, 0) + 27 + """ + if index == number_of_items: + return 0 + ans1 = 0 + ans2 = 0 + ans1 = knapsack(weights, values, number_of_items, max_weight, index + 1) + if weights[index] <= max_weight: + ans2 = values[index] + knapsack( + weights, values, number_of_items, max_weight - weights[index], index + 1 + ) + return max(ans1, ans2) + + +if __name__ == "__main__": + + import doctest + + doctest.testmod()