Recently, I've written a 2-sum solver. I came to realize that my implementation was broken. So I fixed the bug but now encountered another problem. The loop is now ignoring the condition statement.
Here's the pseudo-code for the first algorithm. I will share this to give an understanding of what my newer algorithm is supposed to do.
s = [2]
target = 4
for i IN s:
if target-i in s:
return True
else:
return False
Output: True. Oh Oh. 4-2 = 2. The output was a false positive. There has to be two 2's!!
Here's the solution I used to fix the bug in python.
s=[2]
target = 4
# My 2-sum solver
for i in s:
xx=str(target-i)+str(i)
if xx[0] == xx[1]:
if xx.count(xx[0]) != s.count(int(xx[0])):
print('false')
break
else:
print('true')
break
output: false
The full script is below. Take notice at the statement I'm having trouble with.
Its if target-i in s
that is ignored.
s=[3,2]
target = 5
# My 2-sum solver
for i in s:
xx=str(target-i)+str(i)
if xx[0] == xx[1]:
if xx.count(xx[0]) != s.count(int(xx[0])):
print('false')
quit()
else:
print('true')
quit()
if target-i in s:
print('true')
break
else:
print('false')
break
Here my shell says the if statement is true, but the output is blank.
> target-i in s
True
Question
I am not sure what python want's me to do. Why is the statement ignored and what methods could be used to fix it?