(no) fast boolean evaluation ?
Paddy
paddy3118 at googlemail.com
Sat Aug 4 12:33:10 EDT 2007
On Aug 4, 4:18 pm, Paddy <paddy3... at googlemail.com> wrote:
> On Aug 2, 10:47 pm, Stef Mientki <S.Mientki-nos... at mailbox.kun.nl>
> wrote:
>
> > hello,
>
> > I discovered that boolean evaluation in Python is done "fast"
> > (as soon as the condition is ok, the rest of the expression is ignored).
>
> > Is this standard behavior or is there a compiler switch to turn it on/off ?
>
> > thanks,
> > Stef Mientki
>
> The following program shows a(clumsy)? way to defeat the short-
> circuiting:
>
> def f(x):
> print "f(%s)=%s" % ('x',x),
> return x
> def g(x):
> print "g(%s)=%s" % ('x',x),
> return x
>
> print "\nShort circuit"
> for i in (True, False):
> for j in (True, False):
> print i,j,":", f(i) and g(j)
>
> print "\nShort circuit defeated"
> for i in (True, False):
> for j in (True, False):
> print i,j,":", g(j) if f(i) else (g(j) and False)
>
> The output is:
>
> Short circuit
> True True : f(x)=True g(x)=True True
> True False : f(x)=True g(x)=False False
> False True : f(x)=False False
> False False : f(x)=False False
>
> Short circuit defeated
> True True : f(x)=True g(x)=True True
> True False : f(x)=True g(x)=False False
> False True : f(x)=False g(x)=True False
> False False : f(x)=False g(x)=False False
>
> - Paddy.
And here are the bits for boolean OR:
print "\n\nShort circuit: OR"
for i in (True, False):
for j in (True, False):
print i,j,":", f(i) or g(j)
print "\nShort circuit defeated: OR"
for i in (True, False):
for j in (True, False):
print i,j,":", (g(j) or True) if f(i) else g(j)
- Paddy.
More information about the Python-list
mailing list