Skip to content

Instantly share code, notes, and snippets.

@zahlman
Created September 25, 2014 18:00
Show Gist options
  • Select an option

  • Save zahlman/a5bc019cd42ca2650e56 to your computer and use it in GitHub Desktop.

Select an option

Save zahlman/a5bc019cd42ca2650e56 to your computer and use it in GitHub Desktop.
Generator for grouping adjacent values
def group_adjacent(things, predicate, distance):
"""Make groups of things that are within distance of each other when the predicate is applied."""
result = []
for thing in things:
if result and abs(predicate(thing) - predicate(result[-1])) > distance:
yield result
result = []
result.append(thing)
if result:
yield result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment