diff options
author | Haidong Ji | 2018-12-27 10:20:17 -0600 |
---|---|---|
committer | Haidong Ji | 2018-12-27 10:20:17 -0600 |
commit | f32e2e8777d12869ce9e82aee1e3b9cc9e87f0f6 (patch) | |
tree | ec325a84f8fe351a265e8ebb9a6a6c11fd6b6903 | |
parent | a8bdf7580ae3c6b55554b965810aeb48517d7af1 (diff) |
Kanpsack partition3 done!
Not sure how scientific this comparison is, but I've got Max time used:
0.03/10.00, max memory used: 10264576/536870912.), and bytwigorlimerick
got Max time used: 0.04/10.00, max memory used: 10260480/536870912.).
https://courses.edx.org/courses/course-v1:UCSanDiegoX+ALGS200x+2T2017/discussion/forum/course/threads/5a4290cc44a15008b5000768
Looks like we are using different approaches.
Funny that my approach is a bit faster than
-rw-r--r-- | AlgoDesignAndTechniqueEdxPython/sources/partition3.py | 43 | ||||
-rw-r--r-- | AlgoDesignAndTechniqueEdxPython/tests/partition3Test.py | 28 |
2 files changed, 71 insertions, 0 deletions
diff --git a/AlgoDesignAndTechniqueEdxPython/sources/partition3.py b/AlgoDesignAndTechniqueEdxPython/sources/partition3.py new file mode 100644 index 0000000..9a711f1 --- /dev/null +++ b/AlgoDesignAndTechniqueEdxPython/sources/partition3.py @@ -0,0 +1,43 @@ +# Uses python3 +import sys + + +def getPartition3(a): + if len(a) < 3: + return 0 + sum = 0 + for i in a: + sum = sum + i; + if sum % 3 != 0: + return 0 + W = int(sum / 3) + values = optimalWeight2DArray(W, a) + count = 0 + for i in range(1, len(a) + 1): + for w in range(1, W + 1): + if values[w][i] == W: + count = count + 1 + if count >= 3: + return 1 + else: + return 0 + + +def optimalWeight2DArray(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 + + +if __name__ == '__main__': + input = sys.stdin.read() + n, *A = list(map(int, input.split())) + print(getPartition3(A)) diff --git a/AlgoDesignAndTechniqueEdxPython/tests/partition3Test.py b/AlgoDesignAndTechniqueEdxPython/tests/partition3Test.py new file mode 100644 index 0000000..a5aea66 --- /dev/null +++ b/AlgoDesignAndTechniqueEdxPython/tests/partition3Test.py @@ -0,0 +1,28 @@ +''' +Created on Dec 27, 2018 + +@author: haidong +''' +import unittest + +from sources.partition3 import getPartition3 + + +class Test(unittest.TestCase): + + def testName(self): + a = [3, 3, 3, 3] + self.assertEqual(0, getPartition3(a)) + + def testName1(self): + a = [30] + self.assertEqual(0, getPartition3(a)) + + def testName2(self): + a = [1, 2, 3, 4, 5, 5, 7, 7, 8, 10, 12, 19, 25] + self.assertEqual(1, getPartition3(a)) + + +if __name__ == "__main__": + # import sys;sys.argv = ['', 'Test.testName'] + unittest.main() |