I am trying to get the second-highest number from the list which takes in user input but I keep getting this-
ValueError: invalid literal for int() with base 10:
I tried a sample case where n = 5 and I entered the list as [2,3,6,6,5] and I’m getting the same error
How do I go about it, the code is given below:
list1 = []
n = int(input())
for i in range(0,n+1):
ele = int(input()) //error coming in this line
list1.append(ele)
new_list = set(list1)
new_list.remove(max(new_list))
print(max(new_list))
this is the traceback
Traceback (most recent call last):
File "/tmp/submission/20220221/18/09/hackerrank-1dcd86ec44b50895801520a4a2d0e542/code/Solution.py", line 4, in <module>
ele = int(input())
ValueError: invalid literal for int() with base 10: '2 3 6 6 5'
>Solution :
Commonly, you might want to always make a list, so you could do something like
- get the value
- remove the braces
- make a list of the entries by dividing them up by their commas (conveniently makes a list of length 1 if no comma is present!)
- convert them to integers
You can actually do this all at once with a List Comprehension wrapping the cleanup
[int(x) for x in input().strip("[]").split(",")]
>>> [int(x) for x in input().strip("[]").split(",")]
1
[1]
>>> [int(x) for x in input().strip("[]").split(",")]
[1,2,3]
[1, 2, 3]
The rest follows from your work to make a set to remove duplicates, find the max, etc.
You could alternatively use eval() to convert strings into Python objects, but this is highly dangerous if you accept inputs from an unknown source (in the worst case, a totally unknown one such as an web client) as it directly exposes all the functionality and privilege of the process to the caller