Program to find maximum and minimum K elements in tuple using Python

by | Jul 8, 2021 | Python Programs

Home » Python » Python Programs » Program to find maximum and minimum K elements in tuple using Python

Introduction

The task is to find the extremes (maxima and minima) in the given tuple. This is useful while dealing with applications in data science, robotics and many more.

Program to find maximum and minimum K elements in tuple using Python

We will discuss different ways to find the maximum and minimum K elements.

Program

Approach 1

ip_tuple = (7, 1, 12, 15, 9, 3)
print("The given tuple is : "+str(ip_tuple))
# Using setdefault(), sorted() and lambda()
k = 2

# Using sorted() + loop
output = []
ip_tuple = list(ip_tuple)
temp = sorted(ip_tuple)

for i, ele in enumerate(temp):
    if i< k or i >= len(temp) - k:
        output.append(ele)
output = tuple(output)
print("The output values are: "+str(output))

Output:

Program to find maximum and minimum K elements in tuple using Python Output

Approach 2

ip_tuple = (7, 1, 12, 15, 9, 3)
print("The given tuple is : "+str(ip_tuple))
# Using setdefault(), sorted() and lambda()
k = 2


# Using slicing + sorted()
ip_tuple = list(ip_tuple)
temp = sorted(ip_tuple)
output = tuple(temp[:k] + temp[-k:])


print("The output values are: "+str(output))

Explanation

In approach 1, we have used the combination application of sorting and loop. The sorted() function will sort the given elements of tuple. Using loop we have checked the condition of max and min K elements and appended the result to output list. The output is printed on the screen using print function.

Whereas in approach 2, we have used slicing of elements along with sorting. The result is stored in the output variable and printed in the screen using print function.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author