Created
August 22, 2012 07:42
-
-
Save jonchang/3423507 to your computer and use it in GitHub Desktop.
Groups consecutive number ranges together
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
import itertools | |
def group_ranges(L): | |
""" | |
Collapses a list of integers into a list of the start and end of | |
consecutive runs of numbers. Returns a generator of generators. | |
>>> [list(x) for x in group_ranges([1, 2, 3, 5, 6, 8])] | |
[[1, 3], [5, 6], [8]] | |
""" | |
for w, z in itertools.groupby(L, lambda x, y=itertools.count(): next(y)-x): | |
grouped = list(z) | |
yield (x for x in [grouped[0], grouped[-1]][:len(grouped)]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment