Last active
May 8, 2017 15:09
-
-
Save TApicella/89c96dec7a70b0e638bb11d9397eb6d9 to your computer and use it in GitHub Desktop.
Philly Daily Programmer: 5-8-2016
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Given a sorted list of distinct integers, write a function that returns whether there are two integers in the list that add up to 0. For example, you would return true if both -14435 and 14435 are in the list, because -14435 + 14435 = 0. Also return true if 0 appears in the list. | |
[1, 2, 3] -> false | |
[-5, -3, -1, 2, 4, 6] -> false | |
https://repl.it/HmSh/10 | |
''' | |
test1 = [] #False | |
test2 = [0] #True | |
test3 = [-1, 1] #True | |
test4 = [1, 2] #False | |
test5 = [-2, 1, 2] #True | |
test6 = [-5, 0, 4] #True | |
test7 = [1, 2, 3] #False | |
test8 = [-5, -3, -1, 2, 4, 6] #False | |
alltests = [test1, test2, test3, test4, test5, test6, test7, test8] | |
def runTest(test): | |
front = 0 | |
back = len(test)-1 | |
if len(test)==0: return False | |
elif len(test)==1 and test[front]==0: return True | |
else: | |
while(front != back): | |
if test[front] == 0 or test[back] == 0: return True | |
elif test[front] > 0 or test[back] < 0: return False | |
elif test[front]+test[back] == 0: return True | |
elif abs(test[front]) >= abs(test[back]): front+=1 | |
else: back-=1 | |
return False | |
for t in alltests: | |
print("Running test %s: %s" % (str(t), str(runTest(t)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment