[英]why does python not return all the test cases at once? why does the last test case could only be displayed after I pressed enter again?
[英]Program passes all other test cases except the last one. How to fix last test case?
我需要找到一個數字中的最大重復次數,並且我似乎已經在 test_sweep 中的第 31 行找出了除 testcase 之外的所有其他測試用例。
我試圖重寫這個,但我相當確定我的代碼應該可以工作。
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)
應該通過所有錯誤。 max_run 在第 31 行失敗。
您的問題是您沒有正確處理輸入末尾的長序列。 在最后一個測試用例中,三個 5 的序列被忽略,因為您永遠不會檢查它是否比前一個最長序列(長度為 1)長。
您需要在max_run
的循環外重復此代碼,就在您return maxbal
之前:
if bal >= maxbal:
maxbal = bal
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.