From e2a83b3bc66630cb2667375fba9de5c5baac3aca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nadirhan=20=C5=9Eahin?= Date: Sun, 23 Oct 2022 22:28:11 +0300 Subject: [PATCH] Update knapsack.py (#7271) * Update knapsack.py * Update dynamic_programming/knapsack.py Co-authored-by: Christian Clauss * Update knapsack.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: Christian Clauss Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- dynamic_programming/knapsack.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/dynamic_programming/knapsack.py b/dynamic_programming/knapsack.py index 093e15f49..b12d30313 100644 --- a/dynamic_programming/knapsack.py +++ b/dynamic_programming/knapsack.py @@ -1,9 +1,9 @@ """ Given weights and values of n items, put these items in a knapsack of - capacity W to get the maximum total value in the knapsack. +capacity W to get the maximum total value in the knapsack. Note that only the integer weights 0-1 knapsack problem is solvable - using dynamic programming. +using dynamic programming. """ @@ -27,7 +27,7 @@ def mf_knapsack(i, wt, val, j): def knapsack(w, wt, val, n): - dp = [[0 for i in range(w + 1)] for j in range(n + 1)] + dp = [[0] * (w + 1) for _ in range(n + 1)] for i in range(1, n + 1): for w_ in range(1, w + 1): @@ -108,7 +108,7 @@ def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set): dp: list of list, the table of a solved integer weight dynamic programming problem wt: list or tuple, the vector of weights of the items - i: int, the index of the item under consideration + i: int, the index of the item under consideration j: int, the current possible maximum weight optimal_set: set, the optimal subset so far. This gets modified by the function. @@ -136,7 +136,7 @@ if __name__ == "__main__": wt = [4, 3, 2, 3] n = 4 w = 6 - f = [[0] * (w + 1)] + [[0] + [-1 for i in range(w + 1)] for j in range(n + 1)] + f = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] optimal_solution, _ = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w