Reputation: 1
I'm getting an invalid literal for int() with base 10
where it seems as if the input stream is concatenating values generated in a loop.
def collectData():
lst = makeCases()
cases = int(input())
for i in range(cases):
size = int(input())
case = []
for j in range(size):
value = int(input())
case +=[value]
insert(lst,case)
return lst
That is the function generating the issue. The value and size variables are the problem as they seem to concatenate subsequent values before the conversion.
The makeCases()
function generates a tuple on the form ("Case",[])
.
EDIT: The code works fine locally but won't work in the hackerrank IDE
Upvotes: 0
Views: 2170
Reputation: 2701
As Tom Karzes has said, input()
is returning something other than a number. Looking at the error message that is produced by Python, I assume you are using Python 3 but I will cover Python 2 too.
input()
checks if the given input from stdin is something it can eval
uate to. It is equivalent to eval(raw_input())
. (Pydoc)
>>> a = input()
123
>>> a
123
>>> abc = 3
>>> a = input()
abc
>>> a
3
It produces a different error when you input()
something it cannot eval
:
>>> a = input()
abc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'abc' is not defined
Since it performs eval
on the given input, it will assume that abc
may be a variable name. It searches for it but throws an error because it couldn't find it.
input()
is the new raw_input()
in Python 2. input()
returns a string even if the given input is a number. (Pydoc)
>>> a = input()
123
>>> a
'123'
This is the most likely reason you would convert it to an int()
after you get an input()
.
I can replicate your error message as so (in Python 3):
>>> a = int(input())
abc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
>>> a = int(input())
123 123
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '123 123'
In conclusion, the most likely reason why it is returning such an error is because you are giving it something it cannot convert to an int
.
Upvotes: 2