Last active
July 26, 2022 12:11
-
-
Save ptmcg/f4451702dbdacea71bafe9e01a3c2ffc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import typing | |
from functools import lru_cache | |
T = typing.TypeVar("T") | |
PredicateFunction = typing.Callable[[T], bool] | |
SourceIterable = typing.Iterable[T] | |
ObjectList = typing.List[T] | |
def splitby( | |
pred: PredicateFunction, | |
seq: SourceIterable | |
) -> typing.Tuple[ObjectList, ObjectList]: | |
"""Function to apply a predicate function to a sequence of items, and return lists of | |
values where the predicate returns True and values where the predicate returns False. | |
""" | |
ret = ([], []) | |
pred_with_cache = lru_cache(pred) | |
for ob in seq: | |
ret[not pred_with_cache(ob)].append(ob) | |
return ret | |
if __name__ == '__main__': | |
def is_odd(x): | |
return bool(x % 2) | |
odds, evens = splitby(is_odd, range(10)) | |
print(evens) | |
print(odds) | |
# [0, 2, 4, 6, 8] | |
# [1, 3, 5, 7, 9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment