[英]Program passes all other test cases except the last one. How to fix last test case?
I need to find the maximum recurrence in a number and I seem to have figured out all other test cases besides testcase on line 31 in test_sweep.我需要找到一个数字中的最大重复次数,并且我似乎已经在 test_sweep 中的第 31 行找出了除 testcase 之外的所有其他测试用例。
I have tried to rewrite this but I am fairly certain my code should work.我试图重写这个,但我相当确定我的代码应该可以工作。
def max_run(l: list) -> list:
if len(l) <= 0:
return 0
if len(l) == 1:
return 1
bal = 0
maxbal = 0
compare_item = l[0]
for item in l:
if item == compare_item:
bal = bal + 1
else:
compare_item = item
if bal >= maxbal:
maxbal = bal
bal = 1
return maxbal
class TestMaxRun(unittest.TestCase):
def test_run(self):
before = [1, 1, 3, 3, 3, 5]
saved = before.copy()
self.assertEqual(sweep.max_run(before), 3)
self.assertEqual(before, saved)
self.assertEqual(sweep.max_run([]), 0)
self.assertEqual(sweep.max_run([42]), 1)
self.assertEqual(sweep.max_run([1, 2, 3]), 1)
self.assertEqual(sweep.max_run([3, 3, 3, 2, 3]), 3)
self.assertEqual(sweep.max_run([1, 2, 2, 3]), 2)
self.assertEqual(sweep.max_run([3, 4, 5, 5, 5]), 3)
Should pass all errors.应该通过所有错误。 max_run fails on line 31. max_run 在第 31 行失败。
Your issue is that you don't properly handle a long sequence at the end of the input.您的问题是您没有正确处理输入末尾的长序列。 In that last test case, the sequence of three 5s gets ignored because you don't ever check if it's longer than the previous longest sequence (which was length 1).在最后一个测试用例中,三个 5 的序列被忽略,因为您永远不会检查它是否比前一个最长序列(长度为 1)长。
You need to repeat this code outside of the loop in max_run
, just before you return maxbal
:您需要在max_run
的循环外重复此代码,就在您return maxbal
之前:
if bal >= maxbal:
maxbal = bal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.