Python program to find all possible pairs with a given sum



Examples :

  Input:  lst = [1, 5, 3, 7, 9] K = 12  Output:  [(5, 7), (3, 9)]  Input:  lst = [2, 1, 5, 7, -1, 4] K = 6  Output:  [(2, 4), (1, 5), (7, -1)] 

Method # 1: Pythonic Naive

This is a naive approach to the above problem. First, we take an empty list & # 39; res & # 39; and start the loop and loop through each element of the given list of integers. At each iteration, extract the element, store it in “num”, find the remaining difference for the sum K and check if there is a difference in the given list or not.

# Python3 program for finding all pairs in
# list of integers with a given amount

 

def findPairs (lst, K): 

res = []

while lst:

num = lst.pop ()

diff = K - num

if diff in lst:

res.append ((diff, num))

  

res.reverse ()

  return res

  
# Driver code

lst = [ 1 , 5 , 3  , 7 , 9 ]

K = 12

print (findPairs (lst, K))

Exit:

 [(5, 7) , (3, 9)] 

Method # 2: Using collections.Counter

This approach follows the same method as which was discussed above using collections.Counter .

Exit:

 [(5, 7), (3, 9)] 

Method # 3: itertools.combinations (Naive Method)

This is a naive approach to using itertools.combinations . We use a for loop to go through each combination and find the one we want.

# Python3 program to find all pairs in
# list of integers with a given amount

from collections import Counter

  

def findPairs (lst, K): 

res = []

count = Counter (lst)

 

for x in lst:

y = K - x

if (x! = y and count [y]) or (x = = y and count [y] & gt;  1 ):

  res.append ((x, y)) 

count.subtract ((x, y))

 

  return res

  
# Driver code

lst = [ 1 , 5 , 3 , 7 , 9 ]

K = 12

print (findPairs (lst, K))

# Python3 program to find all pairs in
# list of integers with a given amount

 

from itertools import combinations

 

def findPairs (lst, K) : 

res = []

for var in combinations (lst, 2 ):

if var [ 0 ] + var [ 1 ] = = K:

res.append ((var [ 0 ], var [ 1 ]))

 

  return res

 
# Driver code

lst = [ 1 , 5 , 3 , 7 , 9 ]

K = 12

print (findPairs (lst, K))

Exit:

 [(5, 7), (3, 9)] 

Method # 4: itertools.combinations (effective method)

# Python3 program to find all pairs in
# list of integers with a given sum

from itertools import combinations

 

def findPairs (lst, K):

 

return [pair for pair in combinations (lst, 2 ) if sum (pair) = = K]

 
# Driver code

lst = [ 1 , 5 , 3 , 7 , 9 ]

K = 12

print (findPairs (lst, K))

Exit:

 [(5, 7), (3, 9)]