Instagram
youtube
Facebook
Twitter

Python Program to Find All Pairs in a List with a Given Sum

A Python Program to Find All Pairs in a List with a Given Sum

Code Explanation:

Function Definition:
The function find_pairs(nums, target_sum) is defined to find all number pairs in the list that add up to the target sum.

Initialize Data Structures:
pairs = [] is an empty list to store the result pairs.
seen = set() is used to keep track of numbers already visited.

Loop Through List:
Iterates through each number in the list nums.

Calculate Complement:
For each number, it calculates the complement as target_sum - num.

Check for Valid Pair:
If the complement exists in the seen set, a valid pair is found and added to pairs.

Track Seen Numbers:
The current number is added to the seen set for future pair checking.

Return Result:
The function returns all the valid pairs found.

Input and Output:
A list of integers is predefined.
The user inputs a target sum, and the program prints all pairs with that sum.

 

Program:

def find_pairs(nums, target_sum):

    pairs = []

    seen = set()

    for num in nums:

        complement = target_sum - num

        if complement in seen:

            pairs.append((complement, num))

        seen.add(num)

    return pairs

numbers = [2, 4, 5, 7, 1, 3, 6]

target = int(input("Enter target sum: "))

result = find_pairs(numbers, target)

print("Pairs with sum", target, "are:", result)