0

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?

Travis Wells
  • 321
  • 1
  • 2
  • 11
  • I suspect the reason this conditional isn't running is because you have the `quit()` line before the conditional which completely stops the code from running. – Monolith Dec 03 '19 at 00:48

1 Answers1

0

Get rid of the call to the python quit function if you want it to run:

# ...
else:
   print('true')
   # quit()
   if target-i in s:
      print('true')
      break
   else:
      print('false')
      break

The quit function in python completely stops the execution of the rest of your program. Side note: the quit() should not be used in production code.

EDIT: quit() is not a function but actually callable instance objects, I just called them functions here for simplicity.

Monolith
  • 1,067
  • 1
  • 13
  • 29