Skip to content

Instantly share code, notes, and snippets.

@gavinwahl
Created March 18, 2015 17:18
Show Gist options
  • Save gavinwahl/fda562798e5ed0863e1b to your computer and use it in GitHub Desktop.
Save gavinwahl/fda562798e5ed0863e1b to your computer and use it in GitHub Desktop.
def terminal_split(items, is_terminal):
SENTINAL = object()
ret = [[]]
for item, next_item in izip_longest(items, items[1:], fillvalue=SENTINAL):
ret[-1].append(item)
if next_item is not SENTINAL and is_terminal(item) and not is_terminal(next_item):
ret.append([])
return ret
def is_terminal(x):
return x == 2
self.assertEqual(terminal_split([1, 1, 2, 1, 1], is_terminal), [[1, 1, 2], [1, 1]])
self.assertEqual(terminal_split([1, 1, 2, 2, 1, 1], is_terminal), [[1, 1, 2, 2], [1, 1]])
self.assertEqual(terminal_split([1, 2, 2, 1, 2], is_terminal), [[1, 2, 2], [1, 2]])
self.assertEqual(terminal_split([2, 2], is_terminal), [[2, 2]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment