Skip to content

Instantly share code, notes, and snippets.

Created December 18, 2012 11:40
Show Gist options
  • Save anonymous/4327307 to your computer and use it in GitHub Desktop.
Save anonymous/4327307 to your computer and use it in GitHub Desktop.
Group by ranges in Python
import itertools
def group_ranges(values, ranges):
# Utilities
split_at = lambda f: lambda l: \
(itertools.takewhile(lambda e: not f(e), l), itertools.dropwhile(lambda e: not f(e), l))
# Reducer
def f((values, acc), delim):
(pre, post) = split_at(lambda e: e >= delim)(values)
return (list(post), acc + [list(pre)])
# Evaluation
(leftovers, groups) = reduce(f, ranges, (sorted(values), []))
return groups + [leftovers]
# Demo
test_data = range(0, 15)
test_ranges = [2, 5, 9]
# Think ranges = [(0, 2), (2, 5), (5, 9)]
print group_ranges(test_data, test_ranges)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment