Skip to content

Instantly share code, notes, and snippets.

@jonchang
Created August 22, 2012 07:42
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 jonchang/3423507 to your computer and use it in GitHub Desktop.
Save jonchang/3423507 to your computer and use it in GitHub Desktop.
Groups consecutive number ranges together
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