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-inmin() andmax() 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.
Pythons1={4,12,10,9,4,13}print("Minimum element: ",min(s1))print("Maximum element: ",max(s1))OutputMinimum element: 4Maximum element: 13
Explanation: min() andmax() 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-insorted() 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.
Pythons={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])OutputMinimum element: 1Maximum 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 thesetwhile maintaining min and max variables, updating them as needed, to determine the minimum and maximum elements.
Pythons={5,3,9,1,7}# Initialize min and max with extreme valuesmin_val=float('inf')max_val=float('-inf')# Iterate through the set to find min and maxforeleins:ifele<min_val:min_val=eleifele>max_val:max_val=eleprint("Minimum element:",min_val)print("Maximum element:",max_val)OutputMinimum element: 1Maximum element: 9
Explanation:
- float('inf') andfloat('-inf') are used to initializemin_valandmax_valwith extreme maximum and minimum values respectively, ensuring any element in the set will update them.
- loop iterates through each element, updatingmin_valif the current element issmallerandmax_valif it islargerand after complete iteration we get our max and min values.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice