Open In App

Python – Closest Pair to Kth index element in Tuple

Last Updated : 07 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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)

Method 1: Using enumerate() + loop

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. 

Python
# 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.

Method 2: Using min() + lambda

The combination of above functions offer shorthand to solve this problem. In this, we use min() to find minimum element difference and lambda function is used to perform iterations and computations. 

Python
# Python3 code to demonstrate working of 
# Closest Pair to Kth index element in Tuple
# Using min() + lambda

# 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 min() + lambda
res = min(range(len(test_list)), key = lambda sub: abs(test_list[sub][K - 1] - tup[K - 1]))

# 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 input list
Auxiliary space: O(1), since we are not using any additional data structures or variables proportional to the size of the input list.

Method 3:Using a lambda function and the min() function

Step-by-step algorithm:

  1. Initialize the list of tuples, the target tuple and the index K.
  2. 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.
  3. Assign the result of the min() function to a variable named “res”.
  4. Print the value of “res” as the nearest tuple to the Kth index element of the target tuple.
Python
# 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.

Method 4:Using 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.

Python
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.


 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.

Python
# 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.

Method 6: Using a List Comprehension and min

This code snippet calculates the tuple from test_list that is closest to the target_tuple based on the Euclidean distance. It creates a list of tuples containing each original tuple and its distance to the target, finds the one with the minimum distance using a key in the min function, and prints that tuple as the output.

Python
test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
target_tuple = (17, 23)
k = 2

result = min([(pair, ((pair[0] - target_tuple[0])**2 + (pair[1] - target_tuple[1])**2)**0.5) for pair in test_list], key=lambda x: x[1])[0]
print("Output:", result)

Output
('Output:', (19, 23))

Time complexity:O(n)

Auxiliary space:O(n)



Previous Article
Next Article

Similar Reads

Python - Convert Tuple to Tuple Pair
Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ('A'
10 min read
Python | Divide constant to Kth Tuple index
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Let’s discuss certain ways in which N can be divided by Kth element of tuple in list. Method #1: Using loop Using loops this task can be performed. In this, we just iterate the lis
4 min read
Python - Kth Index Tuple List Mean
Sometimes, while working with Python tuple, we can have a problem in which we need to compute average of any particular index of tuples in a list. This kind of problem can have application in data domain such as web development. Let's discuss certain ways in which this task can be performed. Input : test_list = [('Gfg', 1), ('is', 5), ('best', 7)],
6 min read
Python - Remove Kth Index Duplicates in Tuple
Sometimes, while working with Python records, we can have a problem in which we need to remove all the tuples, which have similar Kth index elements in list of records. This kind of problem is common in day-day and web development domain. Let's discuss certain ways in which this task can be performed. Input : test_list = [(4, 5, 6), (2, 3, 4), (1,
7 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python | Adding N to Kth tuple element
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Let's discuss certain ways in which N can be added to Kth element of tuple in list. Method #1 : Using loop Using loops this task can be performed. In this, we just iterate the list
3 min read
Python | Remove duplicates based on Kth element tuple list
Sometimes, while working with records, we may have a problem in which we need to remove duplicates based on Kth element of a tuple in the list. This problem has application in domains that uses records as input. Let's discuss certain ways in which this problem can be solved. Method #1: Using loop This is a brute-force method to perform this particu
8 min read
Python - Concatenate Kth element in Tuple List
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data in concatenated format. Lets discuss certain ways how one can achieve solutions to this problem. Method #
8 min read
Python - Extract Kth element of every Nth tuple in List
Given list of tuples, extract Kth column element of every Nth tuple. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)], K = 2, N = 3 Output : [3, 8, 10] Explanation : From 0th, 3rd, and 6th tuple, 2nd elements are 3, 8, 10. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6,
8 min read
Practice Tags :