0

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)
azro
  • 53,056
  • 7
  • 34
  • 70
Snails
  • 9
  • 2
  • 1
    What output do you expect ? It also seems you don't really understand what `return` and `break` does, regarding how you wrote that – azro Sep 21 '22 at 17:35
  • The return value from that function should not be a string `"{x, y}"`, it should be a list `[x, y]`. – jarmod Sep 21 '22 at 17:39
  • Welcome to Stack Overflow. "but can't seem to make it recognize when the indices are the same and ignore that solution. " What exactly do you mean? What happens when you run this code? What do you think should happen instead? Why? – Karl Knechtel Sep 21 '22 at 17:50
  • The title of this question does not seem to describe what you are asking at all, but I gave you a duplicate link for that question, too. Before posting again, please read [ask] and https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ and https://meta.stackoverflow.com/questions/261592 and [mre]. – Karl Knechtel Sep 21 '22 at 17:53

2 Answers2

-1

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):
Samwise
  • 68,105
  • 3
  • 30
  • 44
-1

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

DarkKnight
  • 19,739
  • 3
  • 6
  • 22