簡體   English   中英

為什么python不一次返回所有測試用例? 為什么最后一個測試用例只能在我再次按下回車后才能顯示?

[英]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?

輸入:

4
4
1 -2 3 -4
3
0 0 0
5
1 -1 1 -1 1
6
40 -31 -9 0 13 -40

第一次運行代碼時的輸出:

YES
[1, -2, 3, -4]
NO
YES
[1, -1, 1, -1, 1]

再次按回車時的輸出:

YES
[40, -31, -9, 0, 13, -40]

編碼:

numberOfTestCase = int(input())

for i in range(numberOfTestCase):

    listLength = int(input())
    aList = [int(x) for x in input().split()]
    sumList = 0
    for x in range(listLength):
        sumList = aList[x] + sumList

    if sumList == 0:
        print("NO")
    else:
        print("YES")
        print(aList)

那么這個程序有什么作用呢? 該程序旨在計算列表的總和是否等於或不等於零,如果不等於零則返回列表。

輸入說明
第一行:表示有多少個測試用例
第二行:表示第一個列表中有多少個數字
第三行:第一個測試用例/列表
第四.....n:為不同的測試用例重復第二行和第三行

我的問題:為什么 python 不立即返回所有測試用例? 為什么最后一個測試用例只能在我再次按下回車后才能顯示?

Python 不會一次返回所有測試用例,因為檢查總和並打印“YES”或“NO”的if語句位於for循環內。 在每次循環迭代中,您的代碼執行以下操作:

  1. 將列表長度作為輸入
  2. 將列表值作為輸入
  3. sumList的列表值求和
  4. 檢查sumList == 0
  5. 打印“否”或“是”和列表

因此,如果我理解正確,解決您的問題的一種方法可能是創建兩個for循環,它們在range(numberOfTestCase)迭代。 第一個獲取所有輸入並將它們存儲在listLengthaList 第二個檢查條件是否滿足並打印結果。

numberOfTestCase = int(input())

listLength = []
aList = []

for i in range(numberOfTestCase):

    listLength.append(int(input()))
    tmpList = [int(x) for x in input().split()]
    aList.append(tmpList)

for i in range(numberOfTestCase):
  sumList = 0
  for x in range(listLength[i]):
      sumList = aList[i][x] + sumList

  if sumList == 0:
      print("NO")
  else:
      print("YES")
      print(aList)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM