Reputation: 247
5
2 3 6 6 5
5
Traceback (most recent call last):
File "solution.py", line 2, in <module>
li=[input() for i in range(n)]
File "solution.py", line 2, in <listcomp>
li=[input() for i in range(n)]
EOFError: EOF when reading a line
When I write this code in pyCharm, it works properly but when I write this code in Hackerrank.com, it showes me error.
n = int(input())
li=[input() for i in range(n)]
mx = (max(li)) # it gives max number from list
li.remove(mx) # then i remove max no from the list
sec_mx = max(li) # now the second max is the new_max as you all knows
print(sec_mx)
Upvotes: 0
Views: 798
Reputation: 11193
Once you get the input in a list, you can use a verbose:
scores = [2, 3, 6, 6, 5]
scores.sort(reverse = True)
max = scores[0]
second_best = scores[scores.count(max)]
print(second_best) #=> 5
Upvotes: 2
Reputation: 527
You can simply sort list and you can access 2nd largest number from as last 2nd index i.e., -2
li = [12, 45, 45, 2, 41, 31, 10, 8, 6, 4]
print(sorted(set(li))[-2])
OR
sorted_list = sorted(set(li), reverse=True)
print(sorted_list[1])
Upvotes: 0
Reputation: 114330
input
reads until you hit a newline. This works for the first line, since it's a single integer followed by a newline, but not for the second, since the separator is now a space. The reason that it works in pyCharm is most likely that you are separating your input with newlines, contrary to what the website is providing you.
You are probably looking for something more like
li = [int(x) for x in input().split()]
Notice that you need to convert all the elements to int
before you can meaningfully call max
on the list. Otherwise, you will nee doing a lexicographixal comparison of strings, which will give unexpected results for numbers with more than one digit.
One other thing to be aware of is that list.remove
only removes the first occurrence of the maximum. This means that your code, even if corrected to remove the error, will produce 6 rather than 5.
I can think of a number of ways of getting around this:
li
in reverse order. Return the first element that does not equal li[0]
.Use bisection on a pre-sorted list:
from bisect import bisect_left
...
li.sort()
ind = bisect_left(li, li[-1]) - 1
second_max = li[ind]
Upvotes: 1