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
Advertisement
Answer
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])