Skip to content

Instantly share code, notes, and snippets.

@brentp
Created April 14, 2010 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brentp/365485 to your computer and use it in GitHub Desktop.
Save brentp/365485 to your computer and use it in GitHub Desktop.
from itertools import chain, groupby
def as_pairs (xs, ys, grouper=lambda _: _):
"""
>>> aordered = iter([1, 1, 2, 4, 6, 9])
>>> bordered = iter([1, 3, 4, 5, 6, 7])
>>> for a, b in as_pairs(aordered, bordered):
... a, b
([1, 1], [1])
([2], None)
(None, [3])
([4], [4])
(None, [5])
([6], [6])
(None, [7])
([9], None)
"""
xs = chain(xs, [None])
ys = chain(ys, [None])
xnext = groupby(xs, grouper).next
ynext = groupby(ys, grouper).next
x, xgroup = xnext()
y, ygroup = ynext()
while (x,y) != (None, None):
if x == y:
yield list(xgroup), list(ygroup)
x, xgroup = xnext()
y, ygroup = ynext()
elif y is None or (x is not None and x < y):
yield list(xgroup), None
x, xgroup = xnext()
else:
yield (None, list(ygroup))
y, ygroup = ynext()
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment