Can this be written more concisely in a functional style

Bengt Richter bokr at oz.net
Tue Nov 18 02:55:46 CET 2003


On 17 Nov 2003 16:48:36 -0800, jcb at iteris.com (MetalOne) wrote:

>1)
>def f(xs):
>    for x in xs:
>        if test(x): return True
>    return False
>
>I know that I can do (2), but it operates on the whole list and the original
>may break out early.  I want the efficiency of (1), but the conciseness of (2).
>
>2)
>return True in map(test,xs)
That's not quite the same, unless you guarantee that test(x)==bool(test(x))==True when
test(x) is logically true, and never returns True otherwise. (E.g., what if test were
def test(x): return x ? f(range(5)) will give you a True when you hit 1 but, map(test,range(5))
will just be the numbers, and there will be no True in that).

I guess with generator expressions you will soon be able to write

    def f(xs): return True in (bool(test(x)) for x in xs)

We can fake the generator expression and a test that will show us how far it went, to see...

 >>> def test(x): print x; return x=='3'
 ...
(Ok, that does guarantee a bool, but some other test might conceivably not).

 >>> def gx(fun, seq):
 ...      for x in seq: yield bool(fun(x))
 ...
 >>> xs = 'abc123def456'

and

 >>> def f(xs): return True in gx(test, xs)
 ...
 >>> f(xs)
 a
 b
 c
 1
 2
 3
 True

Regards,
Bengt Richter




More information about the Python-list mailing list