[Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose
Richard D. Moores
rdmoores at gmail.com
Wed Nov 24 10:32:08 CET 2010
On Tue, Nov 23, 2010 at 20:09, 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
>
>> So what's the connection with the tests I've run?
>
> I'm wagering it will be faster than a modulo operation. Let us know
> how it turns out :)
You'd win. See <http://tutoree7.pastebin.com/QPT9cAEf>
My thanks to Emile for the list comprehension suggestion.
Dick
More information about the Tutor
mailing list