Method 4Using the heapq.nsmallest() function
Algorithm:
1.Initialize a list of tuples.
2.Initialize the tuple we want to find the closest match for.
3.Initialize the index of the tuple we want to compare.
4.Use the heapq.nsmallest() function to find the smallest element in the list based on the difference between the tuple elements at the specified index.
5.Return the closest tuple.
import heapq
# 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
# using the heapq.nsmallest() function to get the tuple with the smallest difference between the Kth element and the corresponding element in the target tuple
res = heapq.nsmallest(1, test_list, key=lambda x: abs(x[K-1] - tup[K-1]))[0]
# printing the result
print("The nearest tuple to Kth index element is : " + str(res))
#This code is contributed by Jyothi pinjala.
Output
The nearest tuple to Kth index element is : (19, 23)
Time complexity:
The time complexity of this code is O(nlogk), where n is the number of elements in the list and k is the value passed as the first argument to heapq.nsmallest(). In this case, k is 1, so the time complexity is effectively O(log n).
Space complexity:
The space complexity of this code is O(k), where k is the value passed as the first argument to heapq.nsmallest(). In this case, k is 1, so the space complexity is effectively constant.
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)