Open In App

Python – Maximum and Minimum K elements in Tuple

Last Updated : 02 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while dealing with tuples, we can have problem in which we need to extract only extreme K elements, i.e maximum and minimum K elements in Tuple. This problem can have applications across domains such as web development and Data Science. Let’s discuss certain ways in which this problem can be solved.
 

Input : test_tup = (3, 7, 1, 18, 9), k = 2 
Output : (3, 1, 9, 18)

Input : test_tup = (3, 7, 1), k=1 
Output : (1, 7) 

Method #1 : Using sorted() + loop 
The combination of above functionalities can be used to solve this problem. In this, we perform the sort operation using sorted(), and the problem of extraction of max and min K elements using loop. 

Python3




# Python3 code to demonstrate working of
# Maximum and Minimum K elements in Tuple
# Using sorted() + loop
 
# initializing tuple
test_tup = (5, 20, 3, 7, 6, 8)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# initializing K
K = 2
 
# Maximum and Minimum K elements in Tuple
# Using sorted() + loop
res = []
test_tup = list(sorted(test_tup))
 
for idx, val in enumerate(test_tup):
    if idx < K or idx >= len(test_tup) - K:
        res.append(val)
res = tuple(res)
 
# printing result
print("The extracted values : " + str(res))


Output

The original tuple is : (5, 20, 3, 7, 6, 8)
The extracted values : (3, 5, 8, 20)

Time complexity: O(n log n) where n is the length of the input tuple. 
Auxiliary space: O(n) where n is the length of the input tuple

Method #2 : Using list slicing + sorted() 
The combination of above functions can be used to solve this problem. In this, we perform the task of max, min extraction using slicing rather than brute force loop logic.

Python3




# Python3 code to demonstrate working of
# Maximum and Minimum K elements in Tuple
# Using slicing + sorted()
 
# initializing tuple
test_tup = (5, 20, 3, 7, 6, 8)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# initializing K
K = 2
 
# Maximum and Minimum K elements in Tuple
# Using slicing + sorted()
test_tup = list(test_tup)
temp = sorted(test_tup)
res = tuple(temp[:K] + temp[-K:])
 
# printing result
print("The extracted values : " + str(res))


Output

The original tuple is : (5, 20, 3, 7, 6, 8)
The extracted values : (3, 5, 8, 20)

Time complexity: O(n log n), where n is the length of the tuple. 
Auxiliary space: O(n), where n is the length of the tuple. 

Method #3 : Using heapq module:

Python3




import heapq
test_tup = (5, 20, 3, 7, 6, 8)
# printing original tuple
print("The original tuple is : " + str(test_tup))
K = 2
smallest = heapq.nsmallest(K, test_tup)
largest = heapq.nlargest(K, test_tup)
result = tuple(sorted(smallest + largest))
print("The extracted values : " +str(result))
#This code is contributed by Jyothi pinjala


Output

The original tuple is : (5, 20, 3, 7, 6, 8)
The extracted values : (3, 5, 8, 20)

Time Complexity: O(n log k) n is the number of elements in tuple and k is the value of the constant representing the  number of largest and smallest elements to be sorted
Auxiliary Space: O(k) k is the elements

Method 4 :  using the built-in functions min() and max() and a loop to extract the K elements.

step-by-step approach :

  1. Initialize a tuple named test_tup with the values (5, 20, 3, 7, 6, 8).
  2. Print the original tuple using the print() function and the string concatenation operator +.
  3. Initialize a variable K with the value 2.
  4. Use the built-in min() and max() functions to find the minimum and maximum values in test_tup. Assign these values to min_val and max_val respectively.
  5. Create two empty lists min_list and max_list to store the K minimum and maximum values.
  6. Loop through each element in test_tup. For each element, check if it is less than or equal to max_val. If it is, check if max_list has less than K elements. If it does, append the element to max_list. If it doesn’t, remove the minimum value from max_list using the min() function, append the new element to max_list, and update max_val to the new maximum value. Repeat the same process for finding the K minimum values, but check if the element is greater than or equal to min_val instead.
  7. Combine the two lists min_list and max_list using the + operator and convert the result to a tuple using the tuple() function. Assign this tuple to a variable named result.
  8. Print the extracted values by converting result to a string using the str() function and concatenating it with a string using the + operator. Use the print() function to display the result.

Python3




# Python3 code to demonstrate working of
# Maximum and Minimum K elements in Tuple
# Using built-in functions and loop
 
# initializing tuple
test_tup = (5, 20, 3, 7, 6, 8)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# initializing K
K = 2
 
# Find the minimum and maximum elements in the tuple
min_val = min(test_tup)
max_val = max(test_tup)
 
# Create two lists to store the K minimum and maximum elements
min_list = []
max_list = []
 
# Loop through the tuple and add elements to the appropriate list
for elem in test_tup:
    if elem <= max_val:
        if len(max_list) < K:
            max_list.append(elem)
        else:
            max_list.remove(min(max_list))
            max_list.append(elem)
        max_val = max(max_list)
    if elem >= min_val:
        if len(min_list) < K:
            min_list.append(elem)
        else:
            min_list.remove(max(min_list))
            min_list.append(elem)
        min_val = min(min_list)
 
# Combine the two lists and convert the result back to a tuple
result = tuple(min_list + max_list)
 
# Print the original tuple and the extracted values
print("The extracted values : " + str(result))


Output

The original tuple is : (5, 20, 3, 7, 6, 8)
The extracted values : (5, 8, 5, 3)

The time complexity of this method is O(nK), where n is the length of the tuple.

 The auxiliary space is O(K) to store the minimum and maximum lists.

Method#5 :  Using while loop + sort() 

Algorithm :

  1. Initialize a tuple with some elements.
  2. Print the original tuple.
  3. Initialize empty lists min1 and max1.
  4. Initialize the value of k and i as 2 and 0 respectively.
  5. Traverse the tuple using while loop to get k minimum elements.
    a. Append the minimum element to the min1 list using the min() function.
    b. Remove the minimum element from the tuple using the remove() function.
    c. Increase the value of i by 1.
  6. Initialize the value of i as 0 again.
  7. Traverse the tuple using while loop to get k maximum elements.
    a. Append the maximum element to the max1 list using the max() function.
    b. Remove the maximum element from the tuple using the remove() function.
    c. Increase the value of i by 1.
  8. Join the two lists min1 and max1 into a single list res.
  9. Sort the list res using the sort() function.
  10. Convert the list into a tuple res using the tuple() function.
  11. Print the tuple with k minimum and maximum elements in the tuple using print() function.

Python3




# Python program to print maximum and minimum k elements in the tuple
# Initializing the tuple
tup = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
 
# Printing the original tuple
print('Given tuple is: ', tup)
 
min1 = []
max1 = []
 
# Converting tuple into list
tup = list(tup)
 
k = 2
i = 0
 
# Traversing for k min and max elements using while
while i < k:
    min1.append(min(tup))
    tup. remove(min(tup))
    i = i+1
 
i = 0
while i < k:
    max1. append(max(tup))
    tup. remove(max(tup))
    i = i+1
 
# Joining two lists
res = min1+max1
 
# sorting the list using sort()
res.sort()
 
# Converting the list into tuple
res = tuple(res)
 
# Printing the tuple with k min and max elements in the tuple
print('The minimum ', k, 'and maximum ', k, 'elements in the tuple are', res)
 
# Thos code is contributed by SHAIK HUSNA


Output

Given tuple is:  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
The minimum  2 and maximum  2 elements in the tuple are (0, 1, 8, 9)

Time Complexity : O(kn), where k is the number of minimum and maximum elements to be found, and n is the size of the original tuple

Auxiliary Space  :  O(k)

Method 6:Using a loop and two lists

1.Define the input tuple and the number of maximum or minimum elements to extract

2.Define two empty lists to store the maximum and minimum K elements

3.Iterate over each element in the input tuple

4.Append the element to both the maximum and minimum lists

5.Sort the maximum list in descending order and the minimum list in ascending order

6.If the length of the maximum or minimum list is greater than K, remove the last element

7.Print the maximum and minimum K elements

Python3




tup = (5, 20, 3, 7, 6, 8)
k = 2
 
max_k_elements = []
min_k_elements = []
 
for elem in tup:
    max_k_elements.append(elem)
    max_k_elements.sort(reverse=True)
    if len(max_k_elements) > k:
        max_k_elements.pop()
     
    min_k_elements.append(elem)
    min_k_elements.sort()
    if len(min_k_elements) > k:
        min_k_elements.pop()
 
print("Maximum", k, "elements:", max_k_elements)
print("Minimum", k, "elements:", min_k_elements)


Output

Maximum 2 elements: [20, 8]
Minimum 2 elements: [3, 5]

time Space : O(kn)

Auxiliary Space  :  O(k)



Previous Article
Next Article

Similar Reads

Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression The combination of above functions can be used to perform this
8 min read
Python program to convert Set into Tuple and Tuple into Set
Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set method is to convert other type values to set this meth
7 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Python - Convert Tuple to Tuple Pair
Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ('A'
10 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read
Python Program to Merge tuple list by overlapping mid tuple
Given two lists that contain tuples as elements, the task is to write a Python program to accommodate tuples from the second list between consecutive tuples from the first list, after considering ranges present between both the consecutive tuples from the first list. Input : test_list1 = [(4, 8), (19, 22), (28, 30), (31, 50)], test_list2 = [(10, 12
11 min read
three90RightbarBannerImg