Created
September 5, 2019 17:50
-
-
Save malcolmgreaves/ff7fe50c36c7d30ed81bdc896ee42f79 to your computer and use it in GitHub Desktop.
Splits a sequence according to a boolean function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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