Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Maximum and Minimum K elements in Tuple using Python
When working with tuples, you might need to extract the K smallest and K largest elements. Python provides several approaches to accomplish this using sorting and slicing techniques.
Using sorted() with Enumeration
This method sorts the tuple and uses enumeration to select elements from both ends ?
my_tuple = (7, 25, 36, 9, 6, 8)
print("The tuple is:")
print(my_tuple)
K = 2
print("The value of K has been initialized to", K)
my_result = []
temp = sorted(my_tuple)
for idx, val in enumerate(temp):
if idx < K or idx >= len(temp) - K:
my_result.append(val)
my_result = tuple(my_result)
print("The result is:")
print(my_result)
The tuple is: (7, 25, 36, 9, 6, 8) The value of K has been initialized to 2 The result is: (6, 7, 25, 36)
Using Slicing (Alternative Method)
A more concise approach using list slicing to get K smallest and K largest elements ?
my_tuple = (7, 25, 36, 9, 6, 8)
K = 2
# Sort the tuple
sorted_tuple = tuple(sorted(my_tuple))
print("Sorted tuple:", sorted_tuple)
# Get K smallest and K largest
min_k = sorted_tuple[:K]
max_k = sorted_tuple[-K:]
result = min_k + max_k
print(f"K={K} minimum and maximum elements:", result)
Sorted tuple: (6, 7, 8, 9, 25, 36) K=2 minimum and maximum elements: (6, 7, 25, 36)
How It Works
The algorithm follows these steps:
- Sort the tuple: Convert elements to ascending order
- Select elements: Take first K elements (minimum) and last K elements (maximum)
- Combine results: Merge both sets into a single tuple
Comparison
| Method | Code Lines | Readability | Performance |
|---|---|---|---|
| Enumeration | More | Moderate | O(n log n) |
| Slicing | Fewer | High | O(n log n) |
Conclusion
Both methods effectively find K minimum and maximum elements by sorting the tuple first. The slicing approach offers cleaner, more readable code while maintaining the same time complexity.
Advertisements
