- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Given an integer list, find the third maximum number if it exists
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.
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: my_result = [num, my_result, my_result] elif num > my_result: my_result = [my_result, num, my_result] elif num > my_result: my_result = [my_result, my_result, num] if float('-inf') in my_result: print(max(my_num)) else: print(my_result) 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)
The list is : [45, 31, 78, 9, 0, 54, 12, 18] The third maximum number is : 45
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.
- Check if a list exists in given list of lists in Python
- Third Maximum Number in C++
- Check if table exists in MySQL and display the warning if it exists?
- Check if subarray with given product exists in an array in Python
- How to find the index of an item given a list containing it in Python?
- Find the sublist with maximum value in given nested list in Python
- Python - Check if a number and its triple exists in an array
- Python - Check if a number and its double exists in an array
- How to check if a python module exists without importing it?
- Check if element exists in list of lists in Python
- How to find if a directory exists in Python?
- Check if a pair with given product exists in Linked list in C++
- Python - Given an integer 'n', check if it is a power of 3, and return True, otherwise False.