Python Program to Filter Rows with a specific Pair Sum

When working with lists of numbers, we often need to filter rows that contain a specific pair sum. This involves checking if any two elements in each row add up to a target value and keeping only those rows that satisfy this condition.

Problem Overview

Given a list of lists (rows) and a target sum, we want to filter and keep only the rows where at least one pair of elements adds up to the target value ?

Method: Using Helper Function with List Comprehension

We'll create a helper function to check for pair sums and use list comprehension for filtering ?

def find_sum_pair(row, target):
    """Check if any two elements in the row sum to target"""
    for i in range(len(row)):
        for j in range(i + 1, len(row)):
            if row[i] + row[j] == target:
                return True
    return False

# Sample data: list of lists
data = [[71, 5, 21, 6], [34, 21, 2, 71], [21, 2, 34, 5], [6, 9, 21, 42]]
target_sum = 76

print("Original data:")
print(data)
print(f"Target sum: {target_sum}")

# Filter rows with the specific pair sum
filtered_rows = [row for row in data if find_sum_pair(row, target_sum)]

print("Filtered rows:")
print(filtered_rows)
Original data:
[[71, 5, 21, 6], [34, 21, 2, 71], [21, 2, 34, 5], [6, 9, 21, 42]]
Target sum: 76
Filtered rows:
[[71, 5, 21, 6]]

Alternative Method: Using Set for Faster Lookup

For better performance with larger rows, we can use a set-based approach ?

def find_sum_pair_optimized(row, target):
    """Optimized version using set for O(n) complexity"""
    seen = set()
    for num in row:
        complement = target - num
        if complement in seen:
            return True
        seen.add(num)
    return False

# Same data
data = [[71, 5, 21, 6], [34, 21, 2, 71], [21, 2, 34, 5], [6, 9, 21, 42]]
target_sum = 26

# Test with different target
filtered_rows = [row for row in data if find_sum_pair_optimized(row, target_sum)]

print(f"Rows with pairs summing to {target_sum}:")
print(filtered_rows)

# Show which pairs were found
for row in filtered_rows:
    print(f"Row {row}: Found pair that sums to {target_sum}")
Rows with pairs summing to 26:
[[71, 5, 21, 6]]
Row [71, 5, 21, 6]: Found pair that sums to 26

How It Works

The algorithm works by:

  • Nested loops approach: Check every possible pair (i, j) where i < j in each row
  • Set-based approach: For each number, check if its complement (target - number) exists in previously seen numbers
  • List comprehension: Filter rows by calling the helper function on each row

Comparison

Method Time Complexity Space Complexity Best For
Nested loops O(n²) O(1) Small rows, simple implementation
Set-based O(n) O(n) Large rows, better performance

Conclusion

Use the nested loops approach for simple cases and small data. For larger datasets, the set-based method provides better performance with O(n) time complexity. Both methods effectively filter rows containing pairs that sum to a target value.

---
Updated on: 2026-03-26T00:50:35+05:30

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements