diff options
-rw-r--r-- | AlgoDesignAndTechniqueEdxPython/sources/different_summands.py | 31 | ||||
-rw-r--r-- | AlgoDesignAndTechniqueEdxPython/tests/different_summandsTest.py | 35 |
2 files changed, 66 insertions, 0 deletions
diff --git a/AlgoDesignAndTechniqueEdxPython/sources/different_summands.py b/AlgoDesignAndTechniqueEdxPython/sources/different_summands.py new file mode 100644 index 0000000..48af063 --- /dev/null +++ b/AlgoDesignAndTechniqueEdxPython/sources/different_summands.py @@ -0,0 +1,31 @@ +# Uses python3 +import sys + + +def getOptimalSummands(n): + summands = [] + if n < 3: + summands.append(n) + return summands + runningSum = 0 + + for i in range(1, n + 1): + runningSum = runningSum + i + summands.append(i) + if runningSum == n: + break + if runningSum > n: + del summands[-1] + summands[-1] = summands[-1] + n - runningSum + i + break + return summands + +if __name__ == '__main__': + input = sys.stdin.read() + n = int(input) + summands = getOptimalSummands(n) + print(len(summands)) + for x in summands: + print(x, end=' ') + + diff --git a/AlgoDesignAndTechniqueEdxPython/tests/different_summandsTest.py b/AlgoDesignAndTechniqueEdxPython/tests/different_summandsTest.py new file mode 100644 index 0000000..cfb178d --- /dev/null +++ b/AlgoDesignAndTechniqueEdxPython/tests/different_summandsTest.py @@ -0,0 +1,35 @@ +''' +Created on Sep 28, 2018 + +@author: haidong +''' +import unittest + +from sources.different_summands import getOptimalSummands + +class Test(unittest.TestCase): + + + def testName(self): + n = 6 + self.assertEqual(len(getOptimalSummands(n)), 3) + + def testName1(self): + n = 8 + self.assertEqual(len(getOptimalSummands(n)), 3) + + def testName2(self): + n = 2 + self.assertEqual(len(getOptimalSummands(n)), 1) + + def testName3(self): + n = 4 + self.assertEqual(len(getOptimalSummands(n)), 2) + + def testName4(self): + n = 4 + self.assertEqual(getOptimalSummands(n)[1], 3) + +if __name__ == "__main__": + #import sys;sys.argv = ['', 'Test.testName'] + unittest.main()
\ No newline at end of file |