Home > front end >  Trying to find the 2nd largest number in python using max function
Trying to find the 2nd largest number in python using max function

Time:08-04

so i have return this code -

n = int(input())
arr = list(map(int, input().split()))    
# arr.sort(reverse = True)
arr1 = max(arr)
arr2 = max(arr, key=lambda x: min(arr)-1 if (x == arr1) else x)
print(arr2)

Unable to understand how this min(arr)-1 is helping out here.

CodePudding user response:

The logics behind the code you posted are to first find the largest number from the list with a normal call to max, and then find the second largest number by calling max again, but with a key function that by default returns the current number as the key, except that if it's the largest number, it returns a key that is guaranteed to be the smallest in the list so that it won't get returned by max again. In this case, the smallest number minus one is the key that is used by the code to make it the smallest of all.

CodePudding user response:

In the expression:

arr2 = max(arr, key=lambda x: min(arr)-1 if (x == arr1) else x)

A lambda expression is being provided as the key argument to the max() function. This means that this lambda will actually provide the values for the input arr list. The lambda says that if the x value happens to be the maximum value, then replace it with the minimum value minus 1. This effectively removes the maximum value from the list from being considered by the max() function. This then leaves behind the second to highest value as the maximum value.

Another way to do this, which seems more intuitive to me, would be to use a list comprehension:

arr2 = max([x for x in arr if x != max(arr)])

Here we just explicitly remove the max value and then let max() find the second to highest value.

  • Related