Python: Third largest number from a list of numbers using set
Write a Python program to find the third largest number from a given list of numbers.Use the Python set data type.
Sample Solution:
Python Code:
# Define a function 'third_largest' that takes a list of 'nums' as input.
def third_largest(nums):
# Convert the 'nums' list into a set to remove duplicates.
nums = set(nums)
# Check if the length of 'nums' is less than 3. If so, return None since it doesn't have a third largest element.
if len(nums) < 3:
return None
# Convert the 'nums' set back into a list and sort it in reverse order (largest to smallest).
nums = list(nums)
nums.sort(reverse=True)
# Return the third element in the sorted list, which is the third largest number.
return nums[2]
# Define a list of numbers 'nums' for testing.
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Original list of numbers:")
print(nums)
# Call the 'third_largest' function and print the third largest number for the given list.
print("Third largest number of the said list of numbers:")
print(third_largest(nums))
# Repeat the process for different input lists.
nums = [1, 2, 3, 4, 5, 5, 6, 7, 7, 8, 8, 9, 10]
print("\nOriginal list of numbers:")
print(nums)
print("Third largest number of the said list of numbers:")
print(third_largest(nums))
nums = [1, 2, 3]
print("\nOriginal list of numbers:")
print(nums)
print("Third largest number of the said list of numbers:")
print(third_largest(nums))
nums = [1, 2, 2]
print("\nOriginal list of numbers:")
print(nums)
print("Third largest number of the said list of numbers:")
print(third_largest(nums))
nums = [1, 2]
print("\nOriginal list of numbers:")
print(nums)
print("Third largest number of the said list of numbers:")
print(third_largest(nums))
Sample Output:
Original list of numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9] Third largest number of the said list of numbers: 7 Original list of numbers: [1, 2, 3, 4, 5, 5, 6, 7, 7, 8, 8, 9, 10] Third largest number of the said list of numbers: 8 Original list of numbers: [1, 2, 3] Third largest number of the said list of numbers: 1 Original list of numbers: [1, 2, 2] Third largest number of the said list of numbers: None Original list of numbers: [1, 2] Third largest number of the said list of numbers: None
Flowchart:
Python Code Editor:
Previous: Combine three numbers to get the target number.
Next: Return unique strings from a list of strings.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics