Why is my for loop ending after the first term?


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}')
ans = twonum(num)
Asked By: Snails



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)


    for a, x in enumerate(num):
        for b, y in enumerate(num):
Answered By: Samwise

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):
            j = d[tgt-n]
            return [i, j]
        except KeyError:
            d[n] = i

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


[5, 1]


If there is no solution this will implicitly return None

Answered By: Vlad
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.