summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-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()