diff options
-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() |