Skip to content

Instantly share code, notes, and snippets.

@pbassut
Created September 16, 2015 03:52
Show Gist options
  • Save pbassut/1a7eaa052fda6f384642 to your computer and use it in GitHub Desktop.
Save pbassut/1a7eaa052fda6f384642 to your computer and use it in GitHub Desktop.
def find_sumpairs(n, numbers):
# This assumes we can't count on the fact that the array will be sorted
# So, sort it to make sure. Not that this could be skipped and save an O(n log n)
best_case = sorted(numbers, reverse=True)
if (n / 2) > best_case[0]:
# if in a descending sorted array the left-most element
# is less than a half the number we're looking for,
# we can guarantee that the next number won't add up to n.
# So skip here
return False
elif (best_case[0] + best_case[1]) == n:
return True
for i, sum1 in enumerate(best_case):
for sum2 in best_case[i + 1:]:
if sum2 < (n - sum1):
break
if sum1 + sum2 == n:
return True
return False
print find_sumpairs(12, [1, 2, 3, 4, 5, 6, 7])
print find_sumpairs(20, [8, 4, 3, 7, 10, 5, 9, 11])
print find_sumpairs(2, [1, 3, 2])
print find_sumpairs(6, [4, 5, 3])
print find_sumpairs(7, [4, 5, 3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment