Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Created September 5, 2019 17:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malcolmgreaves/ff7fe50c36c7d30ed81bdc896ee42f79 to your computer and use it in GitHub Desktop.
Save malcolmgreaves/ff7fe50c36c7d30ed81bdc896ee42f79 to your computer and use it in GitHub Desktop.
Splits a sequence according to a boolean function.
from typing import Callable, TypeVar, Sequence, Tuple
T = TypeVar('T')
def split_seq(items: Sequence[T], is_left: Callable[[T], bool]) -> Tuple[Sequence[T], Sequence[T]]:
l, r = [], []
for x in items:
a = l if is_left(x) else r
a.append(x)
return l, r
def test_split_seq():
is_even = lambda x: x % 2 == 0
nums = tuple(range(10))
evens, odds = split_seq(nums, is_even)
assert len(evens) == len(odds)
assert len(evens) == 5
assert all(map(is_even, evens))
assert all(map(lambda x: not is_even(x), odds))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment