Python – Closest Sum Pair in List
Last Updated :
20 Mar, 2023
Sometimes, we desire to get the elements that sum to a particular element. But in cases we are not able to find that, our aim changes to be one to find the closest one. This can have application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using dictionary comprehension + max() The combination of above functionalities can be used to perform this task. In this, we perform the logic part in dictionary comprehension and closest pair is extracted using max(). The list should be sorted to perform this method.
Python3
test_list = [ 7 , 8 , 10 , 3 , 18 , 1 ]
print ("The original list is : " + str (test_list))
K = 12
test_list.sort()
res = { i + j :(i, j) for i in test_list for j in test_list if i ! = j and i + j < K}
res = max (res)
print ("The closest sum pair is : " + str (res))
|
Output :
The original list is : [7, 8, 10, 3, 18, 1]
The closest sum pair is : 11
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2 : Using loop + combinations() This is yet another way in which this task can be performed. In this, we iterate through the list, compute all possible pairs and return the closest possible sum generated using min(). This return actual pairs.
Python3
from itertools import combinations
test_list = [ 7 , 8 , 10 , 3 , 18 , 1 ]
print ("The original list is : " + str (test_list))
K = 12
res = {}
for ele in combinations(test_list, 2 ):
ele_sum = sum (ele)
try :
res[ele_sum].append(ele)
except KeyError:
res[ele_sum] = [ele]
res = res[ min (res, key = lambda ele: abs (ele - K))]
print ("The closest sum pair is : " + str (res))
|
Output :
The original list is : [7, 8, 10, 3, 18, 1]
The closest sum pair is : [(8, 3), (10, 1)]
Time Complexity: O(n), where n is the length of the dictionary
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res dictionary
Method #3: Using sorting + two pointer technique
This is yet another way in which this task can be performed. In this, we first sort the list and apply two pointer technique to get the closest sum.
Python3
test_list = [ 7 , 8 , 10 , 3 , 18 , 1 ]
print ( "The original list is : " + str (test_list))
K = 12
test_list.sort()
l, r, n = 0 , len (test_list) - 1 , len (test_list)
res = test_list[l] + test_list[r]
while l < r:
if test_list[l] + test_list[r] < K:
l + = 1
else :
r - = 1
if abs (test_list[l] + test_list[r] - K) < abs (res - K):
res = test_list[l] + test_list[r]
print ( "The closest sum pair is : " + str (res))
|
Output
The original list is : [7, 8, 10, 3, 18, 1]
The closest sum pair is : 11
Time Complexity: O(NLogN)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...