Method 5 : using the sorted() function with a custom key.
step-by-step approach :
Step 1: Initialize the list of tuples, the target tuple, and the index of the element to compare in each tuple.
Step 2: Define a custom key function that takes a tuple as input and returns the absolute difference between the Kth element of the tuple and the corresponding element in the target tuple.
Step 3: Use the sorted() function to sort the list of tuples based on the custom key function.
Step 4: Retrieve the first tuple from the sorted list.
Step 5: Print the result.
# initializing the list of tuples
test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
# initializing the target tuple
tup = (17, 23)
# initializing the index of the element to compare in each tuple
K = 1
# define a custom key function
def key_func(t):
return abs(t[K-1] - tup[K-1])
# use the sorted() function to sort the list of tuples based on the custom key function
sorted_list = sorted(test_list, key=key_func)
# retrieve the first tuple from the sorted list
res = sorted_list[0]
# print the 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 log n), where n is the length of the list of tuples. The sorted() function uses the Timsort algorithm, which has a time complexity of O(n log n).
Auxiliary space: O(n), where n is the length of the list of tuples. The sorted() function creates a new sorted list, which has the same length as the original 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)
Contact Us