Table of Contents
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.
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:
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.
0 Comments