Python program to find the maximum and minimum K elements in a tuple

Here, we have a tuple and we need to find k maximum and k minimum elements present in the tuple in Python programming language.
Submitted by Shivang Yadav, on June 07, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

Example:

tuple = ("python", "includehelp", 43, 54.23)

Finding maximum and minimum k elements in a tuple

We have a tuple and value k. Then we will return k maximum and k minimum elements from the tuple.

Example

Consider the below example with sample input and output:

Input: 
myTuple = (4, 2, 5,7, 1, 8, 9), k = 2

Output: 
(9, 8) , (1, 2)

A simple method to solve the problem is by sorting the tuple and then finding k maximum and k minimum values from the tuple by extracting k from start and k from end.

Python program to find the maximum and minimum K elements in a tuple

# Python program to find maximum and minimum k elements in tuple # Creating a tuple in python myTuple = (4, 9, 1, 7, 3, 6, 5, 2) K = 2 # Finding maximum and minimum k elements in tuple sortedColl = sorted(list(myTuple)) vals = [] for i in range(K): vals.append(sortedColl[i]) for i in range((len(sortedColl) - K), len(sortedColl)): vals.append(sortedColl[i]) # Printing print("Tuple : ", str(myTuple)) print("K maximum and minimum values : ", str(vals))

Output

Tuple :  (4, 9, 1, 7, 3, 6, 5, 2)
K maximum and minimum values :  [1, 2, 7, 9]

Alternate Method

We can use slicing methods on the sorted list created from the tuple to extract first k and last k values.

Program

# Python program to find maximum and minimum k elements in tuple # Creating a tuple in python myTuple = (4, 9, 1, 7, 3, 6, 5, 2) K = 2 # Finding maximum and minimum k elements in tuple sortedColl = sorted(list(myTuple)) vals = tuple(sortedColl[:K] + sortedColl[-K:]) # Printing print("Tuple : ", str(myTuple)) print("K maximum and minimum values : ", str(vals))

Output

Tuple :  (4, 9, 1, 7, 3, 6, 5, 2)
K maximum and minimum values :  (1, 2, 7, 9)

Python Tuple Programs »

Advertisement
Advertisement

Related Programs

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement



Copyright © 2024 www.includehelp.com. All rights reserved.