From a8bdf7580ae3c6b55554b965810aeb48517d7af1 Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Wed, 26 Dec 2018 18:15:59 -0600 Subject: Knapsack maximize gold done! --- .../sources/knapsack.py | 22 ++++++++++++++++++++++ .../tests/knapsackTest.py | 21 +++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 AlgoDesignAndTechniqueEdxPython/sources/knapsack.py create mode 100644 AlgoDesignAndTechniqueEdxPython/tests/knapsackTest.py diff --git a/AlgoDesignAndTechniqueEdxPython/sources/knapsack.py b/AlgoDesignAndTechniqueEdxPython/sources/knapsack.py new file mode 100644 index 0000000..24e5e92 --- /dev/null +++ b/AlgoDesignAndTechniqueEdxPython/sources/knapsack.py @@ -0,0 +1,22 @@ +# Uses python3 +import sys + + +def optimalWeight(W, w2): + j = len(w2) + value = [[0 for _ in range(j + 1)] for _ in range(W + 1)] + + for i in range(1, j + 1): + for w in range(1, W + 1): + value[w][i] = value[w][i - 1] + if w2[i - 1] <= w: + val = value[w - w2[i - 1]][i - 1] + w2[i - 1] + if value[w][i] < val: + value[w][i] = val + return value[W][j] + + +if __name__ == '__main__': + input = sys.stdin.read() + W, n, *w = list(map(int, input.split())) + print(optimalWeight(W, w)) diff --git a/AlgoDesignAndTechniqueEdxPython/tests/knapsackTest.py b/AlgoDesignAndTechniqueEdxPython/tests/knapsackTest.py new file mode 100644 index 0000000..d01a44a --- /dev/null +++ b/AlgoDesignAndTechniqueEdxPython/tests/knapsackTest.py @@ -0,0 +1,21 @@ +''' +Created on Dec 26, 2018 + +@author: haidong +''' +import unittest + +from sources.knapsack import optimalWeight + + +class Test(unittest.TestCase): + + def testName(self): + w = [1, 4, 8] + W = 10 + self.assertEqual(9, optimalWeight(W, w)) + + +if __name__ == "__main__": + # import sys;sys.argv = ['', 'Test.testName'] + unittest.main() -- cgit v1.2.3