How to use enumerate() + loop In Python
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.
# Python3 code to demonstrate working of
# Closest Pair to Kth index element in Tuple
# Using enumerate() + loop
# 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 enumerate() + loop
min_dif, res = 999999999, None
for idx, val in enumerate(test_list):
dif = abs(tup[K - 1] - val[K - 1])
if dif < min_dif:
min_dif, res = dif, idx
# 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 test_list.
Auxiliary space: O(1), as we only use a constant number of variables regardless of the input size.
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