我被困在如何解決這個問題上,嘗試在 vscode 和hackerrank IDE 上執行它,即使網路上的所有解決方案都與我的相同,但兩者都出現錯誤
import math
import os
import random
import re
import sys
#
# Complete the 'plusMinus' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
#
def plusMinus(arr):
# Write your code here
neg,pos,zero=0
for i in range(0,len(arr)):
if(arr[i]<0):
neg =0
elif(arr[i]>0):
pos =0
else:
zero =0
print(pos/len(arr))
print(neg/len(arr))
print(zero/len(arr))
return 0
if __name__ == '__main__':
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr)
Traceback (most recent call last):
File "/tmp/submission/20211128/06/29/hackerrank-a7793862d075fcff390bb368bc113c47/code/Solution.py", line 35, in <module>
plusMinus(arr)
File "/tmp/submission/20211128/06/29/hackerrank-a7793862d075fcff390bb368bc113c47/code/Solution.py", line 17, in plusMinus
neg,pos,zero=0
TypeError: cannot unpack non-iterable int object
uj5u.com熱心網友回復:
閱讀回溯揭示了你得到的錯誤的原因:
Traceback (most recent call last):
File "/tmp/submission/20211128/06/29/hackerrank-a7793862d075fcff390bb368bc113c47/code/Solution.py", line 35, in <module>
plusMinus(arr)
File "/tmp/submission/20211128/06/29/hackerrank-a7793862d075fcff390bb368bc113c47/code/Solution.py", line 17, in plusMinus
neg,pos,zero=0
TypeError: cannot unpack non-iterable int object
正確的語法是
# map the elements of the iterable on the right-hand side to the
# declared variable names
neg, pos, zero = 0, 0, 0
或者
# assign the same value to all declared variables
neg = pos = zero = 0
正如所寫,它試圖將整數解包0為三個單獨的值neg, pos, zero。由于0不是像元組這樣的可迭代物件(例如,0, 0, 0是),因此不能解包為多個值,python 拋出錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/368767.html
上一篇:鏈表未插入新值“C語言”
