1

I'm still new to python and I was wondering if there was a way to simplify this function into something close to a one-liner:

filters = [lambda x: is_big(x), lambda x: is_wide(x), lambda x: is_gray(x)]
def filter(input):
    for func in filters:
        if(not func(input)):
            return False
        else:
            continue
    return True

Assume the functions in the filters list return booleans. Basically is there any way I can do something like all(apply input to each filter)?

Dzhao
  • 683
  • 1
  • 9
  • 22

3 Answers3

6
all(func(input) for func in filters)
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • Oh interesting. Is there any documentation I can read up on this short hand notation of `func(input) for func in filters`? – Dzhao Mar 28 '16 at 17:22
  • 2
    Could you elaborate more on short circuit? Doesn't `all` return False after the first False? – Bahrom Mar 28 '16 at 17:22
  • 1
    @Dzhao: it's a generator expression. http://stackoverflow.com/questions/9060653/list-comprehension-without-python – Karoly Horvath Mar 28 '16 at 17:24
5

Yes, you can use all():

result = all(f(input) for f in filters)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 1
    But doesn't `all` already stop executing after a first fail? See my edited answer for what I mean. – Bahrom Mar 28 '16 at 17:26
  • @BAH is right, so you should use a list comprehension instead of a generator expression. – zondo Mar 28 '16 at 17:32
1

Here's a list comprehension to get filtered output from your input:

filtered = [x for x in input if all(f(x) for f in filters)]

You could also use the built in filter:

complete_filter = lambda x: all(f(x) for f in filters)
filtered = filter(complete_filter, input)

On a side note (not sure what others mean by the fact that all doesn't short circuit). See below:

def f():
    print "in f"
    return True

def g():
    print "in g"
    return False

def h():
    print "in h"
    return True

filters = [f, g, h]
print all(fn() for fn in filters)

This prints

in f
in g
False
>>> 
Bahrom
  • 4,752
  • 32
  • 41
  • 2
    It ***did not*** execute function `h`. Otherwise you would have seen `"in h"` in the output. Am I missing something here? Unless I'm not seeing something really obvious here, it short circuited on `g` returning `False`. – Bahrom Mar 28 '16 at 17:33