Skip to content

Instantly share code, notes, and snippets.

@kojiromike
Created October 16, 2013 02:54
Show Gist options
  • Save kojiromike/7001930 to your computer and use it in GitHub Desktop.
Save kojiromike/7001930 to your computer and use it in GitHub Desktop.
I would like Python's any/all better if they took predicates.
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