builtin functions for and and or?
Steven Bethard
steven.bethard at gmail.com
Sun Feb 13 16:46:03 EST 2005
Roose wrote:
> I need this a lot: a one line way to do a n-ary and or 'or'.
>
> e.g.,
>
> result = True
> for x in L:
> if not boolean_function(x):
> result = False
>
> or
>
>>>>reduce(operator.__and__, [boolean_function(x) for x in L)
Can you use itertools?
py> def boolfn(x):
... print "boolfn: %r" % x
... return bool(x)
...
py> True in itertools.imap(boolfn, ['a', '', 'b'])
boolfn: 'a'
True
py> True in itertools.imap(boolfn, ['', '', ''])
boolfn: ''
boolfn: ''
boolfn: ''
False
py> False in itertools.imap(boolfn, ['a', '', 'b'])
boolfn: 'a'
boolfn: ''
True
py> False in itertools.imap(boolfn, ['a', 'a', 'b'])
boolfn: 'a'
boolfn: 'a'
boolfn: 'b'
False
It even shortcircuits when appropriate.
Steve
More information about the Python-list
mailing list