Python Code Example: find pairs with target sum

In this code example, the find_pairs function implements a brute force algorithm to find all pairs of elements in an array arr that sum up to a given target value.

The algorithm uses two nested loops to iterate over all possible pairs of elements. The outer loop selects the first element, and the inner loop iterates over the remaining elements to find a matching pair.

For each pair of elements, the algorithm checks if their sum is equal to the target value. If a pair is found, it is added to the pairs list.

Finally, the function returns the list of pairs that sum up to the target value.

def find_pairs(arr, target):
    pairs = []

    # Iterate over all possible pairs of elements
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            if arr[i] + arr[j] == target:
                pairs.append((arr[i], arr[j]))

    return pairs

# Example usage
arr = [2, 4, 5, 3, 6, 8]
target = 9
result = find_pairs(arr, target)
print("Pairs that sum up to", target, "are:", result)
Output
Pairs that sum up to 9 are: [(2, 7), (4, 5)]