Finding Pairs that Sum to Target

  • Share this:

Code introduction


This function accepts a list of numbers and a target sum, and returns two numbers from the list that add up to the target sum. If no such pair is found, it returns None.


Technology Stack : 集合(set)

Code Type : Function

Code Difficulty : Intermediate


                
                    
def sum_pairs(numbers, target_sum):
    seen = {}
    for number in numbers:
        if target_sum - number in seen:
            return [target_sum - number, number]
        seen[number] = True
    return None                
              
Tags: