Find all Pairs Whose Sum is Equal to Given number in Python

In this program, we will learn to write Python code to find all the pairs in an array whose sum is equal to a given number.

For Example:

Input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], target sum = 12

Output: [(2, 10), (3, 9), (4, 8), (5, 7)]

Program to find all pairs in Python

def find_pairs(arr, target_sum):
    pairs = []
    for i in range(len(arr)):
        for j in range(i+1, len(arr)):
            if arr[i] + arr[j] == target_sum:
                pairs.append((arr[i], arr[j]))
    return pairs

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target_sum = 12
result = find_pairs(arr, target_sum)
print("All pairs Whose sum is equal to ",target_sum," is: \n",result)

Output:

All pairs Whose sum is equal to  12  is: 
[(2, 10), (3, 9), (4, 8), (5, 7)]