any(), all() and empty iterable

Aaron Brady castironpi at gmail.com
Tue Apr 14 22:28:43 EDT 2009


On Apr 14, 7:32 pm, John O'Hagan <m... at johnohagan.com> wrote:
> On Tue, 14 Apr 2009, Mark Dickinson wrote:
> > On Apr 14, 7:21 pm, Luis Alberto Zarrabeitia Gomez <ky... at uh.cu>
>
> > wrote:
> > > It's more than that. Python's following the rules here. Maybe it could be
> > > documented better, for those without a background in logic/discrete
> > > mathematics, but not changed.
>
> > Agreed.
>
> > I'd like to guess that in 93.7% of cases, when a programmer
> > has used all(seq) without having thought in advance about what the
> > right thing to do is when seq is empty, the current behaviour is
> > already the right one.  I tried to test this hypothesis, but a
> > Google code search for uses of all() turned up very little
> > besides definitions.  For example:
>
> > if all(t.already_filed() for t in my_tax_forms):
> >     go_to_bed_happy()
> > else:
> >     file_for_extension()
>
> But what about this:
>
> if all(evidence):
>         suspect_is_guilty
> else:
>         suspect_is_innocent
>
> :)
> > The current definition also makes reasoning about programs and
> > program transformations easier, thanks to invariants like:
>
> > all(seq1 + seq2) === all(seq1) and all(seq2)
>
> > and
>
> > all(all(s) for s in seqs) === all(chain(*seqs))
>
> > and
>
> > any(not s for s in seq) == not all(seq)
>
> > These invariants wouldn't hold if all([]) were False, or raised
> > an exception.
>
> [...]
>
> OK, that's pretty compelling!

You could spell it out with a normal form like this:

all( x1, x2, ..., xn )=== if True and x1 and x2 and ... and xn.

any( ..., xn )=== if False or... or xn.

since 'if A' === 'if True and A'; and 'if A' === 'if False or A', then
the transformation should hold.

> if all(evidence):
>         suspect_is_guilty
> else:
>         suspect_is_innocent
>
> :)

Ha ha ha.  However, if you try this: if sum( evidence )> 0.9* len
( evidence ), you will get an exception.  Juries should recognize that
'verdict( evidence= set() )' is undefined, so either answer could be
evaluated to.  Especially when you consider that testimony, and not
just court exhibits, are included in the evidence they consider.  Or,
if you have, 'verdict( testimony= set([something]), evidence= set
() )', then the logic you presented isn't an accurate formulation of
the function you want.  Fyi.



More information about the Python-list mailing list