Python - Given an integer list, find the third maximum number if it exists

PythonServer Side ProgrammingProgramming

When it is required to find the third maximum in a list of integers, a method is defined that takes a list as a parameter. It initializes a list of floating point numbers to infinity. The values in the list are iterated over, and compared with infinite values. Depending on the result, the output is displayed on the console.

Example

Below is a demonstration of the same

def third_max_num(my_num):
   my_result = [float('-inf'), float('-inf'), float('-inf')]
   for num in my_num:
      if num not in my_result:
         if num > my_result[0]: my_result = [num, my_result[0], my_result[1]]
         elif num > my_result[1]: my_result = [my_result[0], num, my_result[1]]
         elif num > my_result[2]: my_result = [my_result[0], my_result[1], num]
   if float('-inf') in my_result:
      print(max(my_num))
   else:
      print(my_result[2])

my_list = [45, 31, 78, 9, 0, 54, 12, 18]
print("The list is :")
print(my_list)
print("The third maximum number is :")
third_max_num(my_list)

Output

The list is :
[45, 31, 78, 9, 0, 54, 12, 18]
The third maximum number is :
45

Explanation

  • A method named ‘third_max_num’ is defined that takes a list as a parameter.

  • A list of three floating point values of infinity are defined.

  • The values in the list are iterated, and if the number in the list is not present in the list of infinite numbers, the value in the list is compared to the first element of infinite list.

  • If the list element is greater, then the output is the list of the number, the first and second values from the infinite list.

  • The same thing is performed for all the three infinite values of the list.

  • If the infinite value is finally present in the final output, the maximum of these numbers is displayed as output.

  • Outside the function, a list is defined and is displayed on the console.

  • The method is called by passing this list as a parameter.

  • The output is displayed on the console.

raja
Updated on 20-Sep-2021 10:59:47

Advertisements