Skip to content

Instantly share code, notes, and snippets.

@jfialkoff
Created June 5, 2014 15:53
Show Gist options
  • Save jfialkoff/dcd45201cde00c6d3cf7 to your computer and use it in GitHub Desktop.
Save jfialkoff/dcd45201cde00c6d3cf7 to your computer and use it in GitHub Desktop.
def groupreduce(iterable, groups, is_part_of_group, add_item_to_group):
"""
Reduces a sorted iterable into groups.
>>> iterable = iter((1, 2, 8, 12, 32, 35))
>>> groups = (10, 20, 30, 40, 50)
>>>
>>> def is_part_of_group(group_id, item):
>>> return group_id-10 <= item < group_id
>>>
>>> def add_item_to_group(group_obj, item):
>>> if group_obj is None:
>>> group_obj = []
>>> if item is not None:
>>> group_obj.append(item)
>>> return group_obj
>>>
>>> for group in groupreduce(iterable, groups, is_part_of_group,
>>> add_item_to_group):
>>> print(group)
[1, 2, 8]
[12]
[]
[32, 35]
[]
"""
last_item = None
for group in groups:
group_obj = None
while True:
if last_item:
item = last_item
last_item = None
else:
try:
item = next(iterable)
except StopIteration:
item = None
break
if is_part_of_group(group, item):
group_obj = add_item_to_group(group_obj, item)
else:
last_item = item
break
if group_obj is None:
group_obj = add_item_to_group(None, None)
yield group_obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment