Given a tuple of numeric elements and an integer K, the task is to find the K smallest and K largest elements from the tuple.
Example:
Input:
t = (2, 4, 3, 6, 8, 11, 1, 9)
k=2
Output:
min = 1, 2
max = 9, 11
Here, the two smallest elements in the tuple 't' are 1 and 2, while the two largest elements are "9 and 11." Let's look at different methods of doing it in Python:
Using heapq Module
The heapq module implements a min-heap for efficient retrieval of the smallest or largest elements without full sorting.
Explanation:
- heapq.nsmallest(K, iterable): Returns the K smallest elements from the iterable.
- heapq.nlargest(K, iterable): Returns the K largest elements from the iterable.
Using List Slicing + sorted()
Convert tuple to list, sort it, and slice the first and last K elements.
Explanation:
- sorted(tup): Sorts the tuple in ascending order.
- temp[:K]: Slices the first K elements as the K minimum elements.
- temp[-K:]: Slices the last K elements as the K maximum elements.
Using sorted() + loop
Sort the tuple and use a loop to extract the first K smallest and last K largest elements.
Explanation:
- sorted(tup): Sorts the tuple in ascending order.
- enumerate(l): Loops over the sorted list with index and value.
- if i < K: Appends first K elements to min_ele.
- if i >= len(l) - K: Appends last K elements to max_ele.
Using min() and max() in a Loop
Iteratively track K smallest and K largest elements by comparing each tuple item with the current min and max lists.
Explanation:
- tl = list(tup): Converts the tuple into a list so elements can be removed after selection.
- while i < K: Repeats the loop K times to extract the required number of smallest and largest elements.
- min(tl): Finds the smallest element from the current list.
- m1.append(val) and tl.remove(val): Appends the smallest element to m1 and removes it from tl.
- The same logic is applied for finding and removing the largest elements using max(tl) for list m2.
- m1.sort() and m2.sort(reverse=True): Sort the smallest elements in ascending order and the largest elements in descending order for final output.
Using a loop and two lists
This method keeps track of the K smallest and K largest elements simultaneously in two separate lists while iterating through the tuple.
Explanation:
- m1, m2: track K smallest and largest elements.
- if len(list) < K: fill lists initially.
- if ele < max(m1) / if ele > min(m2): replace larger/smaller elements as needed.
Using while loop + min() / max()
This method repeatedly finds the minimum and maximum values using a while loop and appends them to separate lists.