题目要求:数组中最大的子数组之和(如下图),然后进行单元测试和效能分析。
代码如下:
class SumMaxNum(): def function(serf,lists): max_sum = lists[0] pre_sum = 0 for i in lists: if pre_sum < 0: pre_sum = i else: pre_sum += i if pre_sum > max_sum: max_sum = pre_sum return max_sum
import unittest class MyTestCase(unittest.TestCase): def test_something(self): return self.assertEqual(True, False) def test1(self): ts = SumMaxNum() return self.assertEqual(ts.function([-2 ,6, -1, 5, 4, -7, 2, 3]),14) def test2(self): ts = SumMaxNum() return self.assertEqual(ts.function([1, 4, -5, 9, 8, 3, -6]),20) def test3(self): ts = SumMaxNum() return self.assertEqual(ts.function([-1 ,20 ,-5, 30 ,-4]),45) def test4(self): ts = SumMaxNum() return self.assertEqual(ts.function([-2 ,-3,-5 ,1 ,-9]),1) def test5(self):#这组故意设置错误的值 ts = SumMaxNum() return self.assertEqual(ts.function([-2 ,-3,-5 ,1 ,-9]),0) if __name__ == ‘__main__‘: suite = unittest.TestSuite() suite.addTest(MyTestCase(‘test1‘)) suite.addTest(MyTestCase(‘test2‘)) suite.addTest(MyTestCase(‘test3‘)) suite.addTest(MyTestCase(‘test4‘)) suite.addTest(MyTestCase(‘test5‘)) runner = unittest.TextTestRunner() runner.run(suite)
根据测试结果可以看出公测试了5组数据,其中第5组发生了错误。
注意:后面由于我的PyCharm IDE出问题了,换用了Spyder编译环境,对结果没有影响。
代码
class SumMaxNum(): def function(serf,lists): max_sum = lists[0] pre_sum = 0 for i in lists: if pre_sum < 0: pre_sum = i else: pre_sum += i if pre_sum > max_sum: max_sum = pre_sum return max_sum if __name__ == ‘__main__‘: import cProfile cProfile.run("SumMaxNum().function([-2 ,-3,-5 ,1 ,-9])")
结果:
代码:
import cProfile cProfile.run("suite.addTest(MyTestCase(‘test1‘))") cProfile.run("suite.addTest(MyTestCase(‘test2‘))") cProfile.run("suite.addTest(MyTestCase(‘test3‘))") cProfile.run("suite.addTest(MyTestCase(‘test4‘))") cProfile.run("suite.addTest(MyTestCase(‘test5‘))")
结果截图
原文:https://www.cnblogs.com/lengend/p/14532606.html