How to find all possible pairs with given sum in Python lists
In this tutorial, we will see how to find all possible pairs with a given sum in Python lists.
Lists are similar to arrays in C++ and java but much easier to use. Lists are widely used in Python programming and every Python programmer should have command over it.
APPROACH 1
We will pick one element from the list and check if there’s another element in list that can be added to it to obtain the required sum.
INPUTS
INPUT: arr=[1,4,7,-5,9,3] GIVEN SUM: 4 EXPECTED OUTPUT: (1,3) (-5,9)
def findallpair(l,s): n=len(l) # we will take only n-1 elements in 1st loop because if we take the last element the 2nd loop will go out of index as j=i+1 for i in range(0,n-1): for j in range(i+1,n): if(l[i]+l[j]==s): print("Pair",i+1,":",end="") print(l[i],l[j]) #list containing elements in unsorted manner arr=[1,4,7,-5,9,3] #given value of sum summ=4 #function call findallpair(arr,summ)
Complexity: O(n2)
ACTUAL OUTPUT
Pair 1: 1 3 Pair 2: -5 9
APPROACH 2
We can use itertools.combinations() function. This function makes all possible pairs of a list item for us. After that, all we have to do is print correct pairs.
Easy, right?
So, First, we will see an example of itertools.combinations() then solve our question.
import itertools arr=[1,3,5] for i in itertools.combinations(arr,2): print(i)
OUTPUT
(1,3) (1,5) (3,5)
INPUTS
INPUT: arr=[1,4,7,-5,9,3] GIVEN SUM: 4 EXPECTED OUTPUT: (1,3) (-5,9)
import itertools def findallpair(l,s): #creating combinations of elements of size 2 i.e a pair for i in itertools.combinations(l,2): if(sum(i)==s): print(i) #list containing elements in unsorted manner arr=[1,4,7,-5,9,3] #given value of sum summ=4 #function call findallpair(arr,summ)
ACTUAL OUTPUT
(1,3) (-5,9)
Hope you liked this tutorial.
You can also read:
Leave a Reply