summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHaidong Ji2018-12-26 18:15:59 -0600
committerHaidong Ji2018-12-26 18:15:59 -0600
commita8bdf7580ae3c6b55554b965810aeb48517d7af1 (patch)
treea594fa7535b24b4c0d7a5de81a49829e9a395772
parent61ffe2a9e5fd066dae82a32185bbfe821696bd8a (diff)
Knapsack maximize gold done!
-rw-r--r--AlgoDesignAndTechniqueEdxPython/sources/knapsack.py22
-rw-r--r--AlgoDesignAndTechniqueEdxPython/tests/knapsackTest.py21
2 files changed, 43 insertions, 0 deletions
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()