Equivalent code to the bool() built-in function

Westley Martínez anikom15 at gmail.com
Tue Apr 19 09:43:45 EDT 2011


On Tue, 2011-04-19 at 19:00 +1000, Chris Angelico wrote:
> On Tue, Apr 19, 2011 at 6:43 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
> > but I don't see how
> >
> > (arbitrary expression) + (another expression) + ... + (last expression)
> >
> > can have any guarantees applied. I mean, you can't even guarantee that
> > they won't raise an exception. Can you explain what you mean?
> 
> What Christian posted isn't something I've often done, but here's
> something slightly different that exploits the same
> comparisons-return-summable-values concept:
> 
> A condition with N subconditions is deemed to be satisfied if a
> minimum of M of them are true. This is a general case of the boolean
> Or (N = 2, M = 1) and And (N = 2, M = 2), but does not have a direct
> equivalent in binary operators. You simply sum the subconditions,
> compare against M, and you have your answer.
> 
> if (((port<1024) + (!ip.startswith("192.168.")) +
> (greylist[ip]>time()) + (++spewcnt>10))>=3) // flag this packet as
> suspicious
> 
> Contrived example as I don't recall any specifics right now, but this
> will pick up any packets where three or more of the conditions are
> met. Useful only in fairly specific situations, but I don't know of
> any way to do this with just AND/OR/NOT that would be as clear and
> simple.
> 
> Chris Angelico

Exclusive or:
>>> if not (True and False and False and False) or
           (False and True and False and False) or
           (False and False and True and False) or
           (False and False and False and True):
...     print(True)

Maybe a little silly.




More information about the Python-list mailing list