Q:

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

belongs to collection: Python Tuple Programs

0

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:

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to find maximum and minimum k elements in a tuple in Python

# 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)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to create a list of tuples from giv... >>
<< Python program for adding a Tuple to List and Vice...