Returns a boolean value for whether any two distinct numbers in an array add up to an interger

I’m practicing Python, I want to write a function which takes an array of integers x, and an integer y,and returns a boolean value for whether any two distinct numbers in x add up to y, for example:

add_check([1, 1, 2], 2) # Returns True
add_check([1, 1, 2], 3) # Returns True

add_check([2, 3], 4) # Returns False

Here is my incomplete solution:

def add_check(x: list, y: int):

    # create a dict object and add all the element in the list to the list 
    dictionary = {}
    for i in range(len(x)):
        dictionary.update({x[i]: i})
        #print(dictionary)

    for i in range(len(x)):
        second_num = y - x[i]
        if second_num in dictionary.values():
            second_index = x.index(second_num)
            if i != second_index:
                print(True)
    else:
        print(False)

But when I run add_check([1, 1, 2], 2) it returns True False. I’m a bit confused now, can someone help please, many thanks.

Answer

A print statement just shows an info, but the code continues and the for/else structure work like this

The else statement will be executed if nobreak statement have been used in the loop

So you’d need to use a break after printing True

def add_check(x: list, y: int):
    dictionary = {}
    for i in range(len(x)):
        dictionary.update({x[i]: i})

    for i in range(len(x)):
        second_num = y - x[i]
        if second_num in dictionary.values():
            second_index = x.index(second_num)
            if i != second_index:
                print(True)
                break
    else:
        print(False)

Improvements and fixes

  • you could use a return rather than a print, that’s stop the code, and that’s nicer to let the caller do the job rather than the method

  • dictionary.values() contains indices, and not the values from x so it can be misleading, can a value can be an indice then not be found in x and raise an error like add_check([2, 3], 4) example

So you may check if the missing value for the sum is a key in the dictionnary, and if so, verofy that it’s last position (stored in dictionary) isn’t the current indice

def add_check(x: list, y: int):
    dictionary = {value: i for i, value in enumerate(x)}
    for i, value in enumerate(x):
        second_index = dictionary.get(y - value)
        if second_index and i != second_index:
            return True
    return False

print(add_check([1, 1, 2], 2))  # True
print(add_check([1, 2, 2], 4))  # True
print(add_check([1, 1, 2], 3))  # True
print(add_check([2, 3], 4))     # False