Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://stupidpythonideas.blogspot.com/2014/01/grouping-into-runs-of-adjacent-values.html
- def adjacent_key(cutoff=1, key=None, predicate=None):
- if key is None:
- key = lambda v: v
- if predicate is None:
- def predicate(lhs, rhs):
- return lhs - cutoff <= rhs <= lhs + cutoff
- class K(object):
- __slots__ = ['obj']
- def __init__(self, obj):
- self.obj = obj
- def __eq__(self, other):
- ret = predicate(key(self.obj), key(other.obj))
- if ret:
- self.obj = other.obj
- return ret
- return K
- def first_and_last(iterable):
- start = end = next(iterable)
- for end in iterable: pass
- return start, end
- def runs(iterable, *args, **kwargs):
- for k, g in itertools.groupby(iterable, adjacent_key(*args, **kwargs)):
- yield first_and_last(g)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement