Maximum and Minimum element in a Set in Python
We are given a set and our task is to find the maximum and minimum elements from the given set. For example, if we have a = {3, 1, 7, 5, 9}, the maximum element should be 9, and the minimum element should be 1.
Let’s explore different methods to do it:
1. Using min() & max() function
The built-in min() and max() function in Python can be used to get the minimum or maximum element of all the elements in a set. It iterates through all the elements and returns the minimum or maximum element.
s1 = {4, 12, 10, 9, 4, 13}
print("Minimum element: ", min(s1))
print("Maximum element: ", max(s1))
Output
Minimum element: 4 Maximum element: 13
Explanation: min() and max() returns the minimun and maximum elements respectively of the set here.
Note: Using min() or max() function on a heterogeneous set (containing multiple data types), such as {"Geeks", 11, 21, 'm'}, raises a 'TypeError' because Python cannot compare different data types.
2. Using sorted() function
The built-in sorted() function in Python can be used to get the maximum or minimum of all the elements in a set. We can use it to sort the set and then access the first and the last element for min and max values.
s = {5, 3, 9, 1, 7}
# Sorting the set (converts it into a sorted list)
sorted_s = sorted(s)
print("Minimum element: ", sorted_s[0])
print("Maximum element: ", sorted_s[-1])
Output
Minimum element: 1 Maximum element: 9
Explanation: sorted() function returns a new list with elements arranged in ascending order. The first element, sorted_s[0], represents the minimum value, while the last element, sorted_s[-1], gives the maximum value.
3. Using loops
We can iterate through the set while maintaining min and max variables, updating them as needed, to determine the minimum and maximum elements.
s = {5, 3, 9, 1, 7}
# Initialize min and max with extreme values
min_val = float('inf')
max_val = float('-inf')
# Iterate through the set to find min and max
for ele in s:
if ele < min_val:
min_val = ele
if ele > max_val:
max_val = ele
print("Minimum element:", min_val)
print("Maximum element:", max_val)
Output
Minimum element: 1 Maximum element: 9
Explanation:
- float('inf') and float('-inf') are used to initialize min_val and max_val with extreme maximum and minimum values respectively, ensuring any element in the set will update them.
- loop iterates through each element, updating min_val if the current element is smaller and max_val if it is larger and after complete iteration we get our max and min values.