[Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose

Wayne Werner waynejwerner at gmail.com
Tue Nov 23 21:52:27 CET 2010


On Tue, Nov 23, 2010 at 1:56 PM, Richard D. Moores <rdmoores at gmail.com>wrote:

> On Tue, Nov 23, 2010 at 10:29, R. Alan Monroe <amonroe at columbus.rr.com>
> wrote:
> >> I've always disliked using "if not n % 2"  to test for even/odd ints
> >> because of its convoluted logic. But I ran some speed tests and found
> >> it was the way to go over "if n % 2 == 0".
> >
> > Did you try bitwise-and with 1?
>
> What's that?
>

>>> 2 & 1
0
>>> 3 & 1
1
>>> 10 & 1
0
>>> 11 & 1
0

For an example (base 2):
       1 0 1 1
    & 0 0 0 1
---------------------
       0 0 0 1

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101123/1d06a708/attachment.html>


More information about the Tutor mailing list