Python Forum

Full Version: Find the second largest number
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The task is to find the second largest number in an array.
For eg
INPUT: 5
1, 4, 5, 5, 3
OUTPUT: 4

I tried the following code, but it shows up an error that map() has no len().
def runner_up(arr):
    a = max(arr)
    for i in range(len(arr)):
        if arr[i] == a:        
            arr.remove(a)  #remove all the maximum values. There can be more than one
    return max(arr)

size_of_arr = int(input())
arr = map(int, input().split())
print (runner_up(arr))
If I don't use map, I will not be able to take the input and if I use map, I will not be able to get the length of the array. What should I try? I will like to know how to fix my code and also if there are any other methods to solve this problem.
With some tiny changes:

#!/usr/bin/python3
def runner_up(arr):
    a = max(arr)
    for i in range(len(arr)):
        if arr[i] == a: 
            arr.remove(a)
            break
    return max(arr)
 
arr = list(map(int, input().split()))
print (runner_up(arr))
Another approach is 'find maximum value from elements of list which are not equal to maximum element value in list' :-)

>>> lst = [1, 4, 5, 5, 3] 
>>>  max([num for num in lst if num != max(lst)]) 
4
perfringo solution is pythonic
The "standard" way is to sort the list and choose whatever you want.
my_list = [1, 4, 5, 5, 3]
second_highest = sorted(set(my_list))[-2]
print(second_highest)
Output:
4
That's just what woooee described
You are welcome.
Just observation: code must be more defensive in real life usage - edge cases must be handled (empty list, all list elements with same value etc).
Exactly.