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.
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.
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).
You need to repeat this code outside of the loop in max_run
, just before you return maxbal
:
if bal >= maxbal:
maxbal = bal
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.