# Why is my for loop ending after the first term?

## Question:

very new coder here. I’m trying to solve the classic twonums LeetCode problem (https://leetcode.com/problems/two-sum/) using some of the basics I have learned so far. I can get my program to find the indices of the solutions, but can’t seem to make it recognize when the indices are the same and ignore that solution. Most likely I am just not ready for this problem yet, but I’m curious if it’s possible with these tools and I’m missing something. Any and all help is appreciated.

``````num = [3, 3]
target = 6
def twonum(num):
for x in num:
for y in num:
a = num.index(x)
b = num.index(y)
if (x + y == target) and (a != b):
return(f'{b, a}')
break
ans = twonum(num)
print(ans)
``````

`num.index(x)` gives you the first index of `x` in `num`, which may not be what you want if there are multiple occurrences. Try replacing:

``````    for x in num:
for y in num:
a = num.index(x)
b = num.index(y)
``````

with:

``````    for a, x in enumerate(num):
for b, y in enumerate(num):
``````

If there is a guaranteed solution (i.e., that there are two numbers in the list that sum to the target) then you can do this:

``````def twosum(lst, tgt):
d = {}
for i, n in enumerate(lst):
try:
j = d[tgt-n]
return [i, j]
except KeyError:
d[n] = i

print(twosum([1, 5, 3, 3, 2, 4], 9))
``````

Output:

``````[5, 1]
``````

Note:

If there is no solution this will implicitly return None

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.