Skip to content

Instantly share code, notes, and snippets.

@purpleP
Created June 9, 2018 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save purpleP/e7494ab3e7c545540ac49657c066356e to your computer and use it in GitHub Desktop.
Save purpleP/e7494ab3e7c545540ac49657c066356e to your computer and use it in GitHub Desktop.
from bisect import bisect_left, bisect_right
def pairs_sums_to(k, xs):
xs = [*sorted(xs)]
lo, hi = 0, len(xs) - 1
while True:
left_pos = bisect_left(xs, k, lo, hi)
if left_pos > hi or left_pos == lo:
return
s1 = xs[left_pos]
s2 = k - s1
lo = bisect_right(xs, s2, lo, hi)
hi = left_pos - 1
if xs[lo - 1] == s2:
yield s1, s2
print(list(pairs_sums_to(10, [0, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9, 10, 11])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment