Using while loop and if statement to tell if a binary has an odd or even number of 1's.

Tim Rowe digitig at gmail.com
Thu Feb 5 06:45:25 EST 2009


2009/2/5 Duncan Booth <duncan.booth at invalid.invalid>:

>>> I remember a programming exercise when I was an undergraduate and
>>> anyone who *didn't* use that trick got marked down for writing
>>> inefficient code.
>>
>> Is adding and a modulus *really^ more efficient than flipping a bool
>> as I suggested? I think I'd want to see measurements!
>>
>>
> I meant the bitwise twiddling, but actually I misread it. I thought Mark
> was using the n&~n+1 trick to pull out bits from least significant upwards
> when of course he's just clearing the low bit not extracting it.

Ah, ok. Yes, that's faster than my bit shifting. A million bytes with
your method on my computer with your bit-twiddling takes 1.047
seconds, with my bit-shifting it takes 1.578. On the other hand,
unless that was demonstrated to be a bottleneck I'd still go for the
bit shifting because I think it's clearer. And I'd want a word with a
tutor who insisted on premature optimisation ("The root of all evil",
according to C A R Hoare), especially in a scripting language!

-- 
Tim Rowe



More information about the Python-list mailing list