Created
April 14, 2010 05:51
-
-
Save brentp/365485 to your computer and use it in GitHub Desktop.
This file contains 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
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