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
# Python3 code to demonstrate
# Closest Sum Pair in List
# using dictionary comprehension + max()
# Initializing list
test_list = [7, 8, 10, 3, 18, 1]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 12
# Closest Sum Pair in List
# using dictionary comprehension + max()
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)
# printing result
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
# Python3 code to demonstrate
# Closest Sum Pair in List
# using loop + combinations
from itertools import combinations
# Initializing list
test_list = [7, 8, 10, 3, 18, 1]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 12
# Closest Sum Pair in List
# using dictionary comprehension + max()
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))]
# printing result
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
# Python3 code to demonstrate
# Closest Sum Pair in List
# using sorting + two pointer technique
# Initializing list
test_list = [7, 8, 10, 3, 18, 1]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 12
# Closest Sum Pair in List
# using sorting + two pointer technique
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]
# printing result
print ("The closest sum pair is : " + str(res))
OutputThe original list is : [7, 8, 10, 3, 18, 1]
The closest sum pair is : 11
Time Complexity: O(NLogN)
Auxiliary Space: O(1)
Similar Reads
Python - Find Minimum Pair Sum in list Sometimes, we need to find the specific problem of getting the pair which yields the minimum sum, this can be computed by getting initial two elements after sorting. But in some case, we donât with to change the ordering of list and perform some operation in the similar list without using extra spac
4 min read
Python | Consecutive Pair Minimums Sometimes, while working with Python list, one can have a problem in which one needs to find perform the minimum of list in pair form. This is useful as a subproblem solution of bigger problem in web development and day-day programming. Letâs discuss certain ways in which this problem can be solved.
4 min read
Python | Pair summation of list elements Sometimes, while working with Python list, one can have a problem in which one needs to find perform the summation of list in pair form. This is useful as a subproblem solution of bigger problem in web development and day-day programming. Let's discuss certain ways in which this problem can be solve
4 min read
Python | Three element sum in list The problem of getting the number of pairs that lead to a particular solution has been dealt with many times, this article aims at extending that to 3 numbers and discussing several ways in which this particular problem can be solved. Let's discuss certain ways in which this can be performed.Method
10 min read
Python - Total equal pairs in List Given a list, the task is to write a python program to compute total equal digit pairs, i.e extract the number of all elements with can be dual paired with similar elements present in the list. Input : test_list = [2, 4, 5, 2, 5, 4, 2, 4, 5, 7, 7, 8, 3] Output : 4 Explanation : 4, 2 and 5 have 3 occ
7 min read
Python - Pair iteration in list Pair iteration involves accessing consecutive or specific pairs of elements from a list. It is a common task particularly in scenarios such as comparing neighboring elements, creating tuple pairs, or analyzing sequential data. Python provides several ways to iterate through pairs efficiently ranging
2 min read