Python Maximum and Minimum K elements in Tuple (original) (raw)

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.

Python `

import heapq

tup = (5, 20, 3, 7, 6, 8) K = 2

s = heapq.nsmallest(K, tup) l = heapq.nlargest(K, tup)

print(s) print(l)

`

**Explanation:

Using List Slicing + sorted()

Convert tuple to list, sort it, and slice the first and last K elements.

Python `

tup = (5, 20, 3, 7, 6, 8) K = 2

temp = sorted(tup) mi = temp[:K] ma = temp[-K:]

print(mi) print(ma)

`

**Explanation:

Using sorted() + loop

Sort the tuple and use a loop to extract the first K smallest and last K largest elements.

Python `

tup = (5, 20, 3, 7, 6, 8) K = 2

l = sorted(tup) mi, ma = [], []

for i, val in enumerate(l): if i < K: mi.append(val) if i >= len(l) - K: ma.append(val)

print(mi) print(ma)

`

**Explanation:

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.

Python `

tup = (5, 20, 3, 7, 6, 8) K = 2

m1, m2 = [], [] for elem in tup: if len(m1) < K: m1.append(elem) else: if elem < max(m1): m1.remove(max(m1)) m1.append(elem)

if len(m2) < K:
    m2.append(elem)
else:
    if elem > min(m2):
        m2.remove(min(m2))
        m2.append(elem)

m1.sort() m2.sort(reverse=True)

print( m1) print( m2)

`

**Explanation:

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.

Python `

tup = (5, 20, 3, 7, 6, 8) K = 2

m1 = [] m2 = [] for ele in tup:

if len(m1) < K:
    m1.append(ele)
else:
    if ele < max(m1):
        m1.remove(max(m1))
        m1.append(ele)

if len(m2) < K:
    m2.append(ele)
else:
    if ele > min(m2):
        m2.remove(min(m2))
        m2.append(ele)

m1.sort()
m2.sort(reverse=True)

print(m1) print( m2)

`

**Explanation:

Using while loop + min() / max()

This method repeatedly finds the minimum and maximum values using a while loop and appends them to separate lists.

Python `

tup = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) K = 2

tl = list(tup) m1 = [] m2 = []

i = 0 while i < K: val = min(tl) m1.append(val) tl.remove(val) i += 1

i = 0 while i < K: val = max(tl) m2.append(val) tl.remove(val) i += 1

m1.sort() m2.sort(reverse=True)

print(m1) print(m2)

`