Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Closest Pair to Kth index element in Tuple using Python
When working with tuples, you may need to find the tuple from a list that has the closest value to a reference tuple at a specific index position. Python's enumerate() method combined with abs() function provides an efficient solution.
Problem Statement
Given a list of tuples and a reference tuple, find which tuple in the list has the value closest to the reference tuple's Kth index element ?
Example
tuple_list = [(5, 6), (66, 76), (21, 35), (90, 8), (9, 0)]
print("The list is:")
print(tuple_list)
reference_tuple = (17, 23)
print("The reference tuple is:")
print(reference_tuple)
K = 2
print("The value of K has been initialized to:")
print(K)
min_diff, result_index = float('inf'), None
for idx, val in enumerate(tuple_list):
diff = abs(reference_tuple[K - 1] - val[K - 1])
if diff < min_diff:
min_diff, result_index = diff, idx
print("The tuple nearest to Kth index element is:")
print(tuple_list[result_index])
The list is: [(5, 6), (66, 76), (21, 35), (90, 8), (9, 0)] The reference tuple is: (17, 23) The value of K has been initialized to: 2 The tuple nearest to Kth index element is: (21, 35)
How It Works
The algorithm compares the Kth index element (index K-1) of the reference tuple with the same index element in each tuple from the list:
Reference tuple at index 1:
reference_tuple[1] = 23Compare with each tuple's second element: 6, 76, 35, 8, 0
Calculate absolute differences: |23-6|=17, |23-76|=53, |23-35|=12, |23-8|=15, |23-0|=23
Minimum difference is 12, so
(21, 35)is the closest tuple
Alternative Implementation
Here's a more concise version using the min() function ?
tuple_list = [(5, 6), (66, 76), (21, 35), (90, 8), (9, 0)]
reference_tuple = (17, 23)
K = 2
closest_tuple = min(tuple_list, key=lambda x: abs(reference_tuple[K-1] - x[K-1]))
print("The tuple nearest to Kth index element is:")
print(closest_tuple)
The tuple nearest to Kth index element is: (21, 35)
Conclusion
Use enumerate() with abs() to find the closest tuple by tracking minimum differences. The min() function with a lambda key provides a more concise alternative for the same result.
