Checking sum of items in a list if equals target value

Another way, assuming you can sort the list is the following

original_l = [1,2,6,4,9,3]
my_l = [ [index, item] for item,index in zip(original_l, range(0,len(original_l)))]
my_l_sort = sorted(my_l, key=lambda x: x[1])
start_i = 0
end_i = len(my_l_sort)-1
result = []
target = 7
while start_i < end_i:
    if my_l_sort[start_i][1] + my_l_sort[end_i][1] == target:
        result.append([my_l_sort[start_i][0], my_l_sort[end_i][0]])
    elif my_l_sort[start_i][1] + my_l_sort[end_i][1] < target:
if len(result) != 0:
    print(f"Match for indices {result[0]}")
    print("No match")

The indices 0 and 1 of result[0] are respectively the 2 positions, given as a 2 element string, in original_l that holds the values that summed give the target.

Browse More Popular Posts

Leave a Comment