Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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}')
                break
ans = twonum(num)
print(ans)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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):
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading