(no) fast boolean evaluation ? missing NOT
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Aug 3 09:08:59 EDT 2007
Stef Mientki a écrit :
(snip)
> Gabriel: you pointed me to this page:
> The exact behavior is defined in the Language Reference
> <http://docs.python.org/ref/Booleans.html>
>
> <quote>
> or_test ::= and_test | or_test "or" and_test
> </quote
>
> Can you imagine, while I'm not a programmer, just a human,
> that I don't understand one bit of this line.
This is a variant[2] of the BNF notation[1] for languages grammar.
You'll find such notation in almost any programming language.
[1] http://en.wikipedia.org/wiki/Backus-Naur_form
[2] http://docs.python.org/ref/notation.html
> So now I'm left with just one question:
> for bitwise operations I should use &, |, ^
yes.
> for boolean operations I should use and, or, xor
yes.
> but after doing some test I find strange effects:
> >>> A = 4
> >>> B = 5
> >>> A and B
> 5
> >>> A & B
> 4
> >>> A or B
> 4
> >>> A | B
> 5
Nothing strange here. You now know how boolean operators works. Bitwise
operators are something different (while still related). Represent
yourself ints as bit fields, ie (restricting ourselves to 4-bits words
for the example):
0 => 0000
1 => 0001
2 => 0010
3 => 0011
4 => 0100
5 => 0101
6 => 0110
7 => 0111
8 => 1000
(etc)
The bitwise operators works this way:
1/ the & operator compares each bit of it's operands, and for each
returns '1' if both bits are '1', else '0'. So you have:
A & B => 4 & 5 => 0100 & 0101 => 0100 => 4
0100
& 0101
----
0100
2/ the | operator compares each bit of it's operands, and for each
returns '1' if one of the bits is '1', else '0'. So you have:
A | B => 4 | 5 => 0100 | 0101 => 0101 => 5
0100
| 0101
----
0101
HTH
More information about the Python-list
mailing list