Home > Enterprise >  TypeError: cannot unpack non-iterable int object, Plus Minus problem in HackerRank
TypeError: cannot unpack non-iterable int object, Plus Minus problem in HackerRank

Time:11-29

I am stuck on what to do on this problem, tried to execute it on vscode and the hackerrank IDE, both are giving errors even though all solutions on web are same as mine

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  

CodePudding user response:

Reading the traceback reveals the cause of the error you're getting:

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  

The correct syntax would be either

# map the elements of the iterable on the right-hand side to the 
# declared variable names
neg, pos, zero = 0, 0, 0

or

# assign the same value to all declared variables
neg = pos = zero = 0 

As-written, it's trying to unpack the integer 0 into three separate values neg, pos, zero. Since 0 is not an iterable object like a tuple (as, for example, 0, 0, 0 is), and thus cannot be unpacked into multiple values, python throws an error.

  • Related