Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@href
Created September 9, 2013 09:57
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 href/6493672 to your computer and use it in GitHub Desktop.
Save href/6493672 to your computer and use it in GitHub Desktop.
Simple function / class to put records into groups if they belong together
class United(object):
""" Puts items added through 'append' into the same group as the last
item which was appended, as long as the matchfn which is passed the last
and the current item returns true.
e.g.
united = United(lambda last, current: last == current)
united.append(1)
-> united.groups => [[1]]
united.append(1)
-> united.groups => [[1, 1]]
united.append(2)
-> united.groups => [[1, 1], [2]]
united.append(1)
-> united.groups => [[1, 1], [2], [1]]
"""
def __init__(self, matchfn):
self.matchfn = matchfn
self.groups = []
self.new_group()
def new_group(self):
self.groups.append([])
@property
def current_group(self):
return self.groups[-1]
def append(self, item):
if not self.current_group:
self.current_group.append(item)
else:
if not self.matchfn(self.current_group[-1], item):
self.new_group()
self.current_group.append(item)
def unite(iterator, matchfn):
""" Iterates through the given records and groups the records if two
records passed to the match function result in True.
e.g.
unite([1, 1, 1, 2, 2], lambda last, current: last == current)
-> [[1, 1, 1], [2, 2]]
Note that for this to work the records need to be sorted, not unlike
when using the collection's group function. See 'United' doc above to
learn why.
"""
united = United(matchfn)
for item in iterator:
united.append(item)
return united.groups
if __name__ == '__main__':
result = utils.unite([1, 1, 1, 2, 2], lambda last, current: last == current)
expected = [[1,1,1], [2, 2]]
assert result == expected
united = utils.United(lambda last, current: last == current)
united.append(1)
assert united.groups == [[1]]
united.append(1)
assert united.groups == [[1, 1]]
united.append(2)
assert united.groups == [[1, 1], [2]]
united.append(1)
assert united.groups == [[1, 1], [2]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment