Method 3:Using a lambda function and the min() function
Step-by-step algorithm:
- Initialize the list of tuples, the target tuple and the index K.
- Use the min() function and a lambda function to find the tuple in the list with the smallest absolute difference between its Kth element and the Kth element of the target tuple.
- Assign the result of the min() function to a variable named “res”.
- Print the value of “res” as the nearest tuple to the Kth index element of the target tuple.
# initializing list
test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
# initializing tuple
tup = (17, 23)
# initializing K
K = 1
# Using a lambda function and the min() function
res = min(test_list, key=lambda x: abs(x[K-1] - tup[K-1]))
# printing result
print("The nearest tuple to Kth index element is : " + str(res))
Output
The nearest tuple to Kth index element is : (19, 23)
Time complexity: O(n), where n is the length of the list of tuples. This is because the min() function iterates over the list once to find the tuple with the smallest absolute difference between its Kth element and the Kth element of the target tuple.
Auxiliary space: O(1), since we only store a constant amount of data, such as the list of tuples, the target tuple, the index K, and the result tuple.
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)
Contact Us