ValueError: invalid literal for int() with base 10: '2 3 6 6 5'

Question:

While solving a problem on Hackerrank, i am getting this error –

Traceback (most recent call last):
  File "Solution.py", line 6, in <module>
    x = int(input())
ValueError: invalid literal for int() with base 10: '2 3 6 6 5'
    

Here is the code i have written to get the runner-up score in an array of scores –

        from array import *
        n = int(input())
        A = array('i', [])
        
        for a in range(n):
            x = int(input())
            A.append(int(x))
        
        for i in range(0, len(A)):
            for j in range(i+1, len(A)):
                if A[i] > A[j]:
                    temp = A[i]
                    A[i] = A[j]
                    A[j] = temp
        print(A[len(A)-2])
    

Funny thing is, it works in PyCharm but not in HackerRank.

Asked By: striker00

||

Answers:

You should really post a reproducible example, because merely stating that the code is run on Hackerrank is not sufficient to reproduce the problem.

However, it appears that your code is being called with an input of '2 3 6 6 5', and if you want to append all of these numbers to the list, then you would need to change:

            x = int(input())
            A.append(int(x))

to:

            for x in input().split():
                A.append(int(x))

Your existing code will fail if the input is a string containing a space-separated list of integers. And where the input string contains just the one integer, it is unnecessarily converting it to int twice (the second call to int will simply return the value which is already an int).

Answered By: alani
l =[]
n = int(input())
for x in input().split():
    l.append(int(x))
m=max(l)
while max(l)==m:
    l.remove(m)
print(max(l))
Answered By: suhas gogi
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.