ActiveState Code

Recipe 52907: Predicate tests across sequences


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
Python
 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

Comments

  1. 1. At 1:21 p.m. on 13 oct 2001, Alex Martelli said:

    Numeric (aka Numpy) has interesting, fast implementations of these. Also consider:

    def every(pred, seq):
        return len(seq)==len(filter(pred,seq))
    def any(pred, seq):
        return len(filter(pred,seq))
    and/or:
    import operator
    def every(pred, seq):
        return reduce(operator.and,map(pred,seq))
    def any(pred, seq):
        return reduce(operator.or,map(pred,seq))
    

    The functional forms are elegant and fast.

  2. 2. At 8:06 a.m. on 5 jun 2002, Jørgen Cederberg said:

    Errors in example. The example usage indicated, produces the wrong (the inverse) output, which I guess is caused by a typo.

    Regards

    Jorgen Cederberg

  3. 3. At 12:41 a.m. on 20 sep 2002, Oren Tirosh said:

    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.

Sign in to comment