From 86ec958a1005f3f5b3ec43259688f6d4505cd01b Mon Sep 17 00:00:00 2001 From: JatinR05 <71865805+JatinR05@users.noreply.github.com> Date: Sun, 23 Oct 2022 23:33:40 +0530 Subject: [PATCH 1/2] Update __init__.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added a naïve approach to solve 0/1 knapsack using recursion --- knapsack/__init__.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/knapsack/__init__.py b/knapsack/__init__.py index e69de29bb2d1..c5b7a17eb038 100644 --- a/knapsack/__init__.py +++ b/knapsack/__init__.py @@ -0,0 +1,27 @@ +def knapsack(weights, values, n, maxWeight,i) : + if i == len(weights): + return 0 + ans1 = 0 + ans2 = 0 + ans1 = knapsack(weights,values,n,maxWeight,i+1) + if weights[i] <= maxWeight: + ans2 = values[i] + knapsack(weights,values,n,maxWeight-weights[i],i+1) + return max(ans1,ans2) + +def takeInput() : + n = int(input()) + + if n == 0 : + return list(), list(), n, 0 + + weights = list(map(int, input().split(" "))) + values = list(map(int, input().split(" "))) + maxWeight = int(input()) + + return weights, values, n, maxWeight + + +#main +weights, values, n, maxWeight = takeInput() + +print(knapsack(weights, values, n, maxWeight,0)) From 06583b05be020c99d0e0c9db652e676cf4441a0d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 23 Oct 2022 18:09:44 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- knapsack/__init__.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/knapsack/__init__.py b/knapsack/__init__.py index c5b7a17eb038..4d7d49e5e4a9 100644 --- a/knapsack/__init__.py +++ b/knapsack/__init__.py @@ -1,17 +1,18 @@ -def knapsack(weights, values, n, maxWeight,i) : +def knapsack(weights, values, n, maxWeight, i): if i == len(weights): return 0 ans1 = 0 ans2 = 0 - ans1 = knapsack(weights,values,n,maxWeight,i+1) + ans1 = knapsack(weights, values, n, maxWeight, i + 1) if weights[i] <= maxWeight: - ans2 = values[i] + knapsack(weights,values,n,maxWeight-weights[i],i+1) - return max(ans1,ans2) + ans2 = values[i] + knapsack(weights, values, n, maxWeight - weights[i], i + 1) + return max(ans1, ans2) -def takeInput() : + +def takeInput(): n = int(input()) - if n == 0 : + if n == 0: return list(), list(), n, 0 weights = list(map(int, input().split(" "))) @@ -21,7 +22,7 @@ def takeInput() : return weights, values, n, maxWeight -#main +# main weights, values, n, maxWeight = takeInput() -print(knapsack(weights, values, n, maxWeight,0)) +print(knapsack(weights, values, n, maxWeight, 0))