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

Program is skipping inner loop

I am trying to check whether any two numbers in a list add up to 0, but after the first iteration of j = 1, the program skips the inner loop.

def check_sum(num_list):
    # iterate through the list
    # check whether first number can pair with any other number in list
        # if yes, break
    # if no, check second number, but only check with remaining numbers in the list
    i = 0
    j = 1

    while i < len(num_list):
        check_num = num_list[i]
        print("i = {0}".format(i))
        print("outer: {0}".format(check_num))

        while j < len(num_list):
            print("j = {0}".format(j))
            print("inner: {0}".format(num_list[j]))

            if check_num + num_list[j] == 0:
                return True
            else:
                j+=1
        i+=1
    
    return False

check_sum([10, -14, 26, 5, -3, 13, -5])

Output

Output

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

>Solution :

Move your j = 1 inside first loop.

def check_sum(num_list):
    # iterate through the list
    # check whether first number can pair with any other number in list
        # if yes, break
    # if no, check second number, but only check with remaining numbers in the list
    i = 0
    

    while i < len(num_list):
        check_num = num_list[i]
        print("i = {0}".format(i))
        print("outer: {0}".format(check_num))
        j = 1
        while j < len(num_list):
            print("j = {0}".format(j))
            print("inner: {0}".format(num_list[j]))

            if check_num + num_list[j] == 0:
                return True
            else:
                j+=1
        i+=1
    
    return False

check_sum([10, -14, 26, 5, -3, 13, -5])
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