Find 2 numbers in an unsorted array equal to a given sum

前端 未结 18 884
太阳男子
太阳男子 2020-11-29 19:56

We need to find pair of numbers in an array whose sum is equal to a given value.

A = {6,4,5,7,9,1,2}

Sum = 10 Then the pairs are - {6,4} ,

18条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 20:30

    Create a dictionary with pairs Key (number from the list) and the Value is the number which is necessary to obtain a desired value. Next, check the presence of the pairs of numbers in the list.

    def check_sum_in_list(p_list, p_check_sum):
        l_dict = {i: (p_check_sum - i) for i in p_list}
        for key, value in l_dict.items():
            if key in p_list and value in p_list:
                return True
        return False
    
    
    if __name__ == '__main__':
        l1 = [1, 3, 7, 12, 72, 2, 8]
        l2 = [1, 2, 2, 4, 7, 4, 13, 32]
    
        print(check_sum_in_list(l1, 10))
        print(check_sum_in_list(l2, 99))
    
    Output:
    True
    Flase
    

    version 2

    import random
    
    
    def check_sum_in_list(p_list, p_searched_sum):
        print(list(p_list))
        l_dict = {i: p_searched_sum - i for i in set(p_list)}
        for key, value in l_dict.items():
            if key in p_list and value in p_list:
                if p_list.index(key) != p_list.index(value):
                    print(key, value)
                    return True
        return False
    
    
    if __name__ == '__main__':
        l1 = []
        for i in range(1, 2000000):
            l1.append(random.randrange(1, 1000))
    
        j = 0
        i = 9
        while i < len(l1):
            if check_sum_in_list(l1[j:i], 100):
                print('Found')
                break
            else:
                print('Continue searching')
                j = i
                i = i + 10
    
    Output:
    ...
    [154, 596, 758, 924, 797, 379, 731, 278, 992, 167]
    Continue searching
    [808, 730, 216, 15, 261, 149, 65, 386, 670, 770]
    Continue searching
    [961, 632, 39, 888, 61, 18, 166, 167, 474, 108]
    39 61
    Finded
    [Finished in 3.9s]
    

提交回复
热议问题