【问题标题】:TypeError: cannot unpack non-iterable int object, Plus Minus problem in HackerRankTypeError: cannot unpack non-iterable int object, HackerRank中的Plus Minus问题
【发布时间】:2022-01-05 12:00:59
【问题描述】:

我被困在如何解决这个问题上,试图在 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  

【问题讨论】:

  • 能否为以后的读者提供错误的回溯。
  • 根据 HackerRank,函数不应该返回值...?
  • @LarrytheLlama 函数不应返回值

标签: python arrays typeerror zero negative-number


【解决方案1】:

阅读回溯可以揭示您遇到错误的原因:

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 会抛出错误。

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 2021-01-27
    相关资源
    最近更新 更多