How to use min() + lambda In Python

The combination of above functions offer shorthand to solve this problem. In this, we use min() to find minimum element difference and lambda function is used to perform iterations and computations. 

Python
# Python3 code to demonstrate working of 
# Closest Pair to Kth index element in Tuple
# Using min() + lambda

# initializing list
test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]

# printing original list
print("The original list is : " + str(test_list))

# initializing tuple
tup = (17, 23)

# initializing K 
K = 1

# Closest Pair to Kth index element in Tuple
# Using min() + lambda
res = min(range(len(test_list)), key = lambda sub: abs(test_list[sub][K - 1] - tup[K - 1]))

# printing result 
print("The nearest tuple to Kth index element is : " + str(test_list[res])) 

Output
The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
The nearest tuple to Kth index element is : (19, 23)

Time complexity: O(n), where n is the length of the input list
Auxiliary space: O(1), since we are not using any additional data structures or variables proportional to the size of the input list.

Python – Closest Pair to Kth index element in Tuple

In the given problem, condition K specifies the maximum allowable difference between corresponding elements of tuples, i.e., it represents the proximity threshold for finding the nearest tuple. The goal is to find the tuple in the list whose elements have the smallest maximum difference compared to the given tuple tup, and this difference should not exceed KKK.

Input : test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] tup = (17, 23) K = 2 
Output : (19, 23) 

Input : test_list = [(3, 4, 9), (5, 6, 7)] tup = (1, 2, 5) K = 3 
Output : (5, 6, 7)

Similar Reads

Method 1: Using enumerate() + loop

The combination of above functions offer brute force way to solve this problem. In this, we use enumerate() to monitor index and abs() to keep the minimum difference updated checked for each element over a loop....

Method 2: Using min() + lambda

The combination of above functions offer shorthand to solve this problem. In this, we use min() to find minimum element difference and lambda function is used to perform iterations and computations....

Method 3:Using a lambda function and the min() function

Step-by-step algorithm:...

Method 4:Using the heapq.nsmallest() function:

Algorithm:...

Method 5 : using the sorted() function with a custom key.

step-by-step approach :...

Method 6: Using a List Comprehension and min

This code snippet calculates the tuple from test_list that is closest to the target_tuple based on the Euclidean distance. It creates a list of tuples containing each original tuple and its distance to the target, finds the one with the minimum distance using a key in the min function, and prints that tuple as the output....