How to implement the two sum algorithm to find two values in a list that add up to target with Python

1 Answer

0 votes
def two_sum(lst, target):
    indexes = {}
 
    for i, num in enumerate(lst):
        val = target - num
        if val in indexes:
            return [indexes[val], i]
        else:
            indexes[num] = i
 
    return []
 
lst = [1, 5, 7, 6, 4, 3, 2]
target = 9
 
result = two_sum(lst, target)
 
print(result)  
 
 

 
'''
run:
 
[1, 4]
 
'''

 



answered Jul 17, 2023 by avibootz
edited Jul 18, 2023 by avibootz
...