Python – Closest Sum Pair in List
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 +
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.
The original list is : [7, 8, 10, 3, 18, 1] The closest sum pair is : 11
Method #2 : Using loop +
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.
The original list is : [7, 8, 10, 3, 18, 1] The closest sum pair is : [(8, 3), (10, 1)]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course