Python - Maximum and Minimum K elements in Tuple
Last Updated :
02 Aug, 2023
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))
OutputThe 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))
OutputThe 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
OutputThe 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 :
- Initialize a tuple named test_tup with the values (5, 20, 3, 7, 6, 8).
- Print the original tuple using the print() function and the string concatenation operator +.
- Initialize a variable K with the value 2.
- 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.
- Create two empty lists min_list and max_list to store the K minimum and maximum values.
- 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.
- 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.
- 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))
OutputThe 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 :
- Initialize a tuple with some elements.
- Print the original tuple.
- Initialize empty lists min1 and max1.
- Initialize the value of k and i as 2 and 0 respectively.
- 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. - Initialize the value of i as 0 again.
- 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. - Join the two lists min1 and max1 into a single list res.
- Sort the list res using the sort() function.
- Convert the list into a tuple res using the tuple() function.
- 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
OutputGiven 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)
OutputMaximum 2 elements: [20, 8]
Minimum 2 elements: [3, 5]
time Space : O(kn)
Auxiliary Space : O(k)
Similar Reads
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Basic Programs
How to Add Two Numbers in PythonThe task of adding two numbers in Python involves taking two input values and computing their sum using various techniques . For example, if a = 5 and b = 7 then after addition, the result will be 12.Using the "+" Operator+ operator is the simplest and most direct way to add two numbers . It perform
4 min read
Find Maximum of two numbers in PythonFinding the maximum of two numbers in Python helps determine the larger of the two values. For example, given two numbers a = 7 and b = 3, you may want to extract the larger number, which in this case is 7. Let's explore different ways to do this efficiently.Using max()max() function is the most opt
2 min read
Factorial of a Number - PythonThe factorial of a number is the product of all positive integers less than or equal to that number. For example, the factorial of 5 (denoted as 5!) is 5 Ã 4 Ã 3 Ã 2 Ã 1 = 120. In Python, we can calculate the factorial of a number using various methods, such as loops, recursion, built-in functions,
4 min read
Python Program for Simple InterestThe task of calculating Simple Interest in Python involves taking inputs for principal amount, time period in years, and rate of interest per annum, applying the Simple Interest formula and displaying the result. For example, if p = 1000, t = 2 (years), and r = 5%, the Simple Interest is calculated
3 min read
Python Program for Compound InterestLet us discuss the formula for compound interest. The formula to calculate compound interest annually is given by: A = P(1 + R/100) t Compound Interest = A - P Where, A is amount P is the principal amount R is the rate and T is the time spanFind Compound Interest with Python Python3 # Python3 progra
3 min read
Python Program to Check Armstrong NumberGiven a number x, determine whether the given number is Armstrong number or not. A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if. abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + .... Example: Input : 153 Output : Yes 153 is an Armstrong nu
6 min read
Array Programs
Python Program to Find Sum of ArrayGiven an array of integers, find the sum of its elements. Examples: Input : arr[] = {1, 2, 3}Output : 6Explanation: 1 + 2 + 3 = 6This Python program calculates the sum of an array by iterating through each element and adding it to a running total. The sum is then returned. An example usage is provid
4 min read
Python Program to Find Largest Element in an ArrayTo find the largest element in an array, iterate over each element and compare it with the current largest element. If an element is greater, update the largest element. At the end of the iteration, the largest element will be found. Given an array, find the largest element in it. Input : arr[] = {1
4 min read
Python Program for Array RotationHere we are going to see how we can rotate array with Python code. Array Rotation: Â Python Program for Array Rotation ExamplePartitioning the sub arrays and reversing them Approach: Input arr[] = [1, 2, 3, 4, 5, 6, 7, 8], d = 1, size = 8 1) Reverse the entire list by swapping first and last numbers
7 min read
Python Program for Reversal algorithm for array rotationWrite a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. In this article, we will explore the Reversal Algorithm for array rotation and implement it in Python. Example Input: arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2 Output: arr[] = [3, 4, 5, 6, 7, 1, 2] Rotation of the above array
2 min read
Python Program to Split the array and add the first part to the endThere is a given array and split it from a specified position, and move the first part of the array add to the end. Examples: Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end .Input : arr[] =
5 min read
Python Program for Find remainder of array multiplication divided by nWrite a Python program for a given multiple numbers and a number n, the task is to print the remainder after multiplying all the numbers divided by n. Examples: Input: arr[] = {100, 10, 5, 25, 35, 14}, n = 11Output: 9Explanation: 100 x 10 x 5 x 25 x 35 x 14 = 61250000 % 11 = 9Input : arr[] = {100, 1
3 min read
Python Program to check if given array is MonotonicGiven an array A containing n integers. The task is to check whether the array is Monotonic or not. An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all
7 min read
List Programs
Python program to interchange first and last elements in a listGiven a list, write a Python program to swap the first and last element of the list using Python.Examples: The last element of the list can be referred to as a list[-1]. Therefore, we can simply swap list[0] with list[-1].Python# Initialize a list my_list = [1, 2, 3, 4, 5] # Interchange first and la
5 min read
Python Program to Swap Two Elements in a ListIn this article, we will explore various methods to swap two elements in a list in Python. The simplest way to do is by using multiple assignment.Example:Pythona = [10, 20, 30, 40, 50] # Swapping elements at index 0 and 4 # using multiple assignment a[0], a[4] = a[4], a[0] print(a)Output[50, 20, 30,
1 min read
How To Find the Length of a List in PythonThe length of a list refers to the number of elements in the list. There are several methods to determine the length of a list in Python. For example, consider a list l = [1, 2, 3, 4, 5], length of this list is 5 as it contains 5 elements in it. Let's explore different methods to find the length of
2 min read
Check if element exists in list in PythonIn this article, we will explore various methods to check if element exists in list in Python. The simplest way to check for the presence of an element in a list is using the in Keyword. Example:Pythona = [10, 20, 30, 40, 50] # Check if 30 exists in the list if 30 in a: print("Element exists in the
3 min read
Different ways to clear a list in PythonIn this article, we will explore various methods to clear a list in Python. The simplest way to do is by using a loop.Using clear() MethodUsing clear() method we can remove all elements from a list. This method modifies the list in place and removes all its elements.Pythona = [1, 2, 3, 4, 5] a.clear
2 min read
Reversing a List in PythonIn this article, we are going to explore multiple ways to reverse a list. Python provides several methods to reverse a list using built-in functions and manual approaches. The simplest way to reverse a list is by using the reverse() method. Let's take an example to reverse a list using reverse() met
4 min read
Matrix Programs
Adding and Subtracting Matrices in PythonIn this article, we will discuss how to add and subtract elements of the matrix in Python. Example: Suppose we have two matrices A and B. A = [[1,2],[3,4]] B = [[4,5],[6,7]] then we get A+B = [[5,7],[9,11]] A-B = [[-3,-3],[-3,-3]] Now let us try to implement this using Python 1. Adding elements of
4 min read
Add Two Matrices - PythonThe task of adding two matrices in Python involves combining corresponding elements from two given matrices to produce a new matrix. Each element in the resulting matrix is obtained by adding the values at the same position in the input matrices. For example, if two 2x2 matrices are given as:Two 2x2
3 min read
Python Program to Multiply Two MatricesGiven two matrices, we will have to create a program to multiply two matrices in Python. Example: Python Matrix Multiplication of Two-DimensionPythonmatrix_a = [[1, 2], [3, 4]] matrix_b = [[5, 6], [7, 8]] result = [[0, 0], [0, 0]] for i in range(2): for j in range(2): result[i][j] = (matrix_a[i][0]
5 min read
Matrix Product - PythonThe task of calculating the matrix product in Python involves finding the product of all elements within a matrix or 2D list . This operation requires iterating through each element in the matrix and multiplying them together to obtain a single cumulative product. For example, given a matrix a = [[1
3 min read
Transpose a matrix in Single line in PythonTranspose of a matrix is a task we all can perform very easily in Python (Using a nested loop). But there are some interesting ways to do the same in a single line. In Python, we can implement a matrix as a nested list (a list inside a list). Each element is treated as a row of the matrix. For examp
4 min read
Python - Matrix creation of n*nMatrices are fundamental structures in programming and are widely used in various domains including mathematics, machine learning, image processing, and simulations. Creating an nÃn matrix efficiently is an important step for these applications. This article will explore multiple ways to create such
3 min read
Python | Get Kth Column of MatrixSometimes, while working with Python Matrix, one can have a problem in which one needs to find the Kth column of Matrix. This is a very popular problem in Machine Learning Domain and having solution to this is useful. Let's discuss certain ways in which this problem can be solved. Method #1 : Using
6 min read
Python - Vertical Concatenation in MatrixGiven a String Matrix, perform column-wise concatenation of strings, handling variable lists lengths. Input : [["Gfg", "good"], ["is", "for"]] Output : ['Gfgis', 'goodfor'] Explanation : Column wise concatenated Strings, "Gfg" concatenated with "is", and so on. Input : [["Gfg", "good", "geeks"], ["i
3 min read
String Programs
Dictionary Programs
Python - Ways to remove a key from dictionaryWe are given a dictionary and our task is to remove a specific key from it. For example, if we have the dictionary d = {"a": 1, "b": 2, "c": 3}, then after removing the key "b", the output will be {'a': 1, 'c': 3}.Using pop()pop() method removes a specific key from the dictionary and returns its cor
3 min read
Merging or Concatenating two Dictionaries in PythonCombining two dictionaries is a common task when working with Python, especially when we need to consolidate data from multiple sources or update existing records. For example, we may have one dictionary containing user information and another with additional details and we'd like to merge them into
2 min read
Python - Convert key-values list to flat dictionaryWe are given a list that contains tuples with the pairs of key and values we need to convert that list into a flat dictionary. For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age':
3 min read
Python - Insertion at the beginning in OrderedDictGiven an ordered dict, write a program to insert items in the beginning of the ordered dict. Examples: Input: original_dict = {'a':1, 'b':2} item to be inserted ('c', 3) Output: {'c':3, 'a':1, 'b':2}Input: original_dict = {'akshat':1, 'manjeet':2} item to be inserted ('nikhil', 3) Output: {'nikhil':
2 min read
Python | Check order of character in string using OrderedDict( )Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there wonât be any duplicate characters in the pattern. Examples: Input: string = "engineers rock"pattern = "er";Output: trueExplanation: All
3 min read
Python dictionary with keys having multiple inputsPrerequisite: Python-Dictionary. How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets. Example 1: Python3 # Python code to demonstrate
4 min read
Tuple Programs
Find the Size of a Tuple in PythonThere are several ways to find the "size" of a tuple, depending on whether we are interested in the number of elements or the memory size it occupies. For Example: if we have a tuple like tup = (10, 20, 30, 40, 50), calling len(tup) will return 5, since there are five elements in the tuple.Using len
3 min read
Python - Maximum and Minimum K elements in TupleSometimes, 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
8 min read
Create a List of Tuples with Numbers and Their Cubes - PythonWe are given a list of numbers and our task is to create a list of tuples where each tuple contains a number and its cube. For example, if the input is [1, 2, 3], the output should be [(1, 1), (2, 8), (3, 27)].Using List ComprehensionList comprehension is one of the most efficient ways to achieve th
3 min read
Python - Adding Tuple to List and Vice - VersaAdding a tuple to a list in Python can involve appending the entire tuple as a single element or merging its elements into the list. Conversely, adding a list to a tuple requires converting the list to a tuple and concatenating it with the existing tuple, as tuples are immutable. For example, adding
4 min read
Python - Closest Pair to Kth index element in TupleIn the given problem, condition K specifies the maximum allowable difference between corresponding elements of tuples, i.e., it represents the proximity threshold for finding the nearest tuple. The goal is to find the tuple in the list whose elements have the smallest maximum difference compared to
7 min read
Python - Join Tuples if similar initial elementSometimes, while working with Python tuples, we can have a problem in which we need to perform concatenation of records from the similarity of initial element. This problem can have applications in data domains such as Data Science. Let's discuss certain ways in which this task can be performed. Inp
8 min read
Searching and Sorting Programs
Linear Search - PythonGiven an array, arr of n elements, and an element x, find whether element x is present in the array. Return the index of the first occurrence of x in the array, or -1 if it doesnât exist.Examples:Input: arr[] = [10, 50, 30, 70, 80, 20, 90, 40], x = 30Output : 2Explanation: For array [10, 50, 30, 70,
4 min read
Bubble Sort - PythonBubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. Bubble Sort algorithm, sorts an array by repeatedly comparing adjacent elements and swapping them if they are in the wrong order. The algorithm iterates through the a
2 min read
Selection Sort - PythonSelection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
2 min read
Insertion Sort - PythonInsertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list.Insertion SortThe insertionSort function takes an array arr as input. It first calculates the length of the array (n). If the le
3 min read
Python Program for Recursive Insertion SortInsertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Python Program for Recursive Insertion Sort for Iterative algorithm for insertion sortAlgorithm // Sort an arr[] of size ninsertionSort(arr, n) Loop from i = 1 to n-1. a) Pick element arr[i] and inser
4 min read
Binary Search (Recursive and Iterative) - PythonBinary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Below is the step-by-step algorithm for Binary Search:D
6 min read
Pattern Printing Programs