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.
JavaScript
x
27
27
1
def check_sum(num_list):
2
# iterate through the list
3
# check whether first number can pair with any other number in list
4
# if yes, break
5
# if no, check second number, but only check with remaining numbers in the list
6
i = 0
7
j = 1
8
9
while i < len(num_list):
10
check_num = num_list[i]
11
print("i = {0}".format(i))
12
print("outer: {0}".format(check_num))
13
14
while j < len(num_list):
15
print("j = {0}".format(j))
16
print("inner: {0}".format(num_list[j]))
17
18
if check_num + num_list[j] == 0:
19
return True
20
else:
21
j+=1
22
i+=1
23
24
return False
25
26
check_sum([10, -14, 26, 5, -3, 13, -5])
27
Output
Advertisement
Answer
Move your j = 1 inside first loop.
JavaScript
1
27
27
1
def check_sum(num_list):
2
# iterate through the list
3
# check whether first number can pair with any other number in list
4
# if yes, break
5
# if no, check second number, but only check with remaining numbers in the list
6
i = 0
7
8
9
while i < len(num_list):
10
check_num = num_list[i]
11
print("i = {0}".format(i))
12
print("outer: {0}".format(check_num))
13
j = 1
14
while j < len(num_list):
15
print("j = {0}".format(j))
16
print("inner: {0}".format(num_list[j]))
17
18
if check_num + num_list[j] == 0:
19
return True
20
else:
21
j+=1
22
i+=1
23
24
return False
25
26
check_sum([10, -14, 26, 5, -3, 13, -5])
27