Program to find maximum and minimum of tuple

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:

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.

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.

Write a Python program to find the minimum and maximum value for each tuple position in a given list of tuples.

Sample Solution:

Python Code:

def max_min_list_tuples(nums):
    zip(*nums)
    result1 = map(max, zip(*nums))
    result2 = map(min, zip(*nums))
    return list(result1), list(result2)

nums = [(2,3),(2,4),(0,6),(7,1)]
print("Original list:")
print(nums)

result = max_min_list_tuples(nums)
print("\nMaximum value  for each tuple position in the said list of tuples:")
print(result[0])
print("\nMinimum value  for each tuple position in the said list of tuples:")
print(result[1])

Sample Output:

Original list:
[(2, 3), (2, 4), (0, 6), (7, 1)]

Maximum value  for each tuple position in the said list of tuples:
[7, 6]

Minimum value  for each tuple position in the said list of tuples:
[0, 1]

Flowchart:

Program to find maximum and minimum of tuple

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

In this tutorial, you will learn to write a python program that will display K maximum and minimum elements from a tuple. A tuple is one of the data structures in Python which are used to store multiple items in a single variable.

We will give a tuple and a value of K as input in our program and then we should get the K maximum and minimum elements as output.

Look at the examples to understand the input and output format.

Input:

tup=(1, 2, 3, 4, 5, 6)

k=1

Output: (1,6)

Input:

tup=(3, 4, 5, 6,10)

k=2

Output: (3, 4, 6, 10)

To solve this problem in python, we can use the following approaches-

  1. using a loop and sorted() method

  2. using slicing and sorted() method

We will be discussing both these approaches in detail below.

Approach 1: loop and sorted()

In this approach, we will use a loop and the sorted() method to get all the K maximum and minimum elements from the given tuple.

The sorted() method is a built-in method of Python that sorts the given data structure in ascending order and returns a sorted list. To get the maximum and minimum elements we will use a loop.

Algorithm

Follow the algorithm to understand the approach better.

Step 1- Define a function to find elements from a tuple

Step 2- Declare a result list

Step 3- Convert tuple to list

Step 4- Sort the list using sorted() and store it in a variable

Step 5- Iterate through the sorted tuple and search for maximum and minimum elements

Step 6- Add the elements in the list

Step 7- Print list as the final result

Step 8- Declare a tuple and K then pass in the function to get output

Python Program 1

In this program, we have defined a function that accepts a tuple and value of K as parameters and finds the K maximum and minimum elements from it. To convert a tuple to a list we will use the list() method. To get a counter value for a tuple we can get the enumerate() method. We have also used string methods like append()and len() in our program to add elements to a list and to get the length of a list respectively.

def Findel(tup,K):
    result = []
    test_tup = list(tup)
    temp = sorted(tup)
    for i, val in enumerate(temp):
        if i < K or i >= len(temp) - K:
            result.append(val)
    result = tuple(result)
    # printing result 
    print("Max and Min K elements : ",result)

tup = (13, 10, 23, 2, 5, 6, 12)
K = 2
print("The original tuple: ", tup)
Findel(tup,K)


The original tuple: (13, 10, 23, 2, 5, 6, 12)
Max and Min K elements : (2, 5, 13, 23)

Approach 2: slicing and sorted()

In this approach, we will use the concept of list slicing and the sorted() method to find elements from the tuple. We will use slicing instead of a loop to get the max and min elements in this. Slicing a list simply means creating another list which will be the subset of the original list, where the starting and the ending position is specified.

Algorithm

Follow the algorithm to understand the approach better.

Step 1- Define a function to find elements from a tuple

Step 2- Convert tuple to a list and store it in a variable

Step 3- Sort the elements in the list

Step 4- Declare a result list and with the help of slicing store only the elements which are needed

Step 5- Print this list as the final result

Step 6- Declare a tuple and K then pass in the function to get output

Python Program 2

In this program, we have defined a function that finds the required elements from the tuple using some methods and list slicing. Thelist() method will be used to convert tuple to a list. After sorting, the K max and min elements will be at the starting and end of the list.

def Findel(tup,K):
    tup = list(tup)
    temp = sorted(tup)
    result = tuple(temp[:K] + temp[-K:])
  
    print("Max and Min K elements : ",result)
tup = (13, 10, 23, 2, 5, 6, 12, 7, 1, 8)
K = 3
print("The original tuple: ", tup)
Findel(tup,K)


The original tuple: (13, 10, 23, 2, 5, 6, 12, 7, 1, 8)
Max and Min K elements : (1, 2, 5, 12, 13, 23)

Conclusion

In this tutorial, we have seen two different approaches of extracting K maximum and minimum elements from a tuple in Python. The values in the tuple and the value of K is already specified in the program.

How do you find the max and min value of a tuple?

The approach using the reduce() function from the functools module to find the minimum and maximum value in the first and second elements of each tuple in a list involves iterating over the elements of the list and applying the min() or max() function to each element.

How do you find the maximum of a tuple?

We can use Python built-in max() Method to find the maximum element in a tuple.

How do you find the minimum of a tuple?

Python 3 - Tuple min() Method.
Description. The min() method returns the elements from the tuple with minimum value..
Syntax. Following is the syntax for min() method − min(tuple).
Parameters. tuple − This is a tuple from which min valued element to be returned..
Return Value. ... .
Example. ... .
Result..

How do you find the minimum and maximum value in Python?

Use Python's min() and max() to find smallest and largest values in your data. Call min() and max() with a single iterable or with any number of regular arguments. Use min() and max() with strings and dictionaries.