Often it is useful to know whether all elements of sequence meet certain criteria, or if only some pass a test. These two functions "every" and "any" do just that.
Example usage:
>>> every(lambda c: c > 5,(6,7,8,9))
1
>>> every(lambda c: c < 5,(6,7,8,9))
0
>>> any(lambda c: c > 5,(6,7,8,9))
1
>>> any(lambda c: c < 5,(6,7,8,9))
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | def every (pred, seq):
"""every takes a one argument predicate
function and a sequence. Returns true
if every element in seq returns true for
predicate, else returns false.
The predicate function should return true or false.
"""
for i in seq:
if not pred(i): return 0
return 1
def any (pred, seq):
"""any takes a one argument predicate
function and a sequence. Returns true
if any element in seq returns true for
predicate, else returns false.
The predicate function should return true or false.
"""
for i in seq:
if pred(i): return 1
return 0
|
Numeric (aka Numpy) has interesting, fast implementations of these. Also consider:
The functional forms are elegant and fast.
Errors in example. The example usage indicated, produces the wrong (the inverse) output, which I guess is caused by a typo.
Regards
Jorgen Cederberg
No early bail-out. These versions can be much slower if the evidence is found early in the sequence - they don't bail out immediately like those in the recipe.