Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Maximum and Minimum K elements in Tuple

Python – Maximum and Minimum K elements in Tuple

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)

RELATED ARTICLES

Most Popular

Recent Comments