Last Updated : 11 Apr, 2025
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() functionThe 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.
Python
s1 = {4, 12, 10, 9, 4, 13}
print("Minimum element: ", min(s1))
print("Maximum element: ", max(s1))
Minimum element: 4 Maximum element: 13
Explanation: min() and max() returns the minimun and maximum elements respectively of the set here.
2. Using sorted() functionNote: 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.
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.
Python
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])
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 loopsWe can iterate through the set while maintaining min and max variables, updating them as needed, to determine the minimum and maximum elements.
Python
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)
Minimum element: 1 Maximum element: 9
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4