Skip to content

Instantly share code, notes, and snippets.

@fogleman
Last active August 29, 2015 14:04
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 fogleman/d5e9accb30296195c030 to your computer and use it in GitHub Desktop.
Save fogleman/d5e9accb30296195c030 to your computer and use it in GitHub Desktop.
Python Split Function
def split(values, func):
group = []
previous = None
for value in values:
if previous and func(previous, value):
yield group
group = []
group.append(value)
previous = value
if group:
yield group
if __name__ == '__main__':
# split a sequence of 100 sorted random numbers wherever the delta >= 10
import random
values = sorted(random.sample(range(1000), 100))
print values
for group in split(values, lambda a, b: (b - a) >= 10):
print group
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment