Created
October 16, 2013 02:54
-
-
Save kojiromike/7001930 to your computer and use it in GitHub Desktop.
I would like Python's any/all better if they took predicates.
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
from functools import reduce | |
nopred = lambda i: i | |
def any(it, pred=nopred): | |
'''True if pred(i) is True for any member of the iterable `it`. | |
If pred is None, pred(i) == i. | |
Like the builtin `any`, return False if `it` is empty.''' | |
if not callable(pred): | |
pred = nopred | |
def accumulate(prev, cur): | |
return prev or pred(cur) | |
return reduce(accumulate, it, False) | |
def all(it, pred=nopred): | |
'''True if pred(i) is True for all members of the iterable `it`. | |
If pred is None, pred(i) == i. | |
Like the builtin `all`, return True if `it` is empty.''' | |
if not callable(pred): | |
pred = nopred | |
def accumulate(prev, cur): | |
return prev and pred(cur) | |
return reduce(accumulate, it, True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment