[Tutor] Finding even and odd numbers

Eric Brunson brunson at brunson.com
Wed Sep 19 22:32:23 CEST 2007



 >>> t = timeit.Timer( '1000%2')
 >>> t.timeit(1000000)
0.25893402099609375
 >>> t = timeit.Timer( '1000&1')
 >>> t.timeit(1000000)
0.2567589282989502

It's almost insignificantly faster.

However as a programmer and a mathematician, I disagree with your 
position that the bitwise operation is more or less readable than the 
modulus operation. 

If you wrap either in a function called "isOdd()" that's all someone has 
see to know what it's doing.  My internal implementation of "isOdd()" 
should be of no consequence to someone unless they are modifying that 
particular piece of code, and if they're doing that, % is just as common 
an operation as &.

However, with that said, the overhead of the function call is 
significantly greater than the cost of the actual operation, around four 
times slower:

 >>> t = timeit.Timer( 'isOdd(1000)', 'def isOdd(num): return num&1')
 >>> t.timeit(1000000)
1.1442101001739502
 >>> t = timeit.Timer( 'isOdd(1000)', 'def isOdd(num): return num%2')
 >>> t.timeit(1000000)
1.1032519340515137


Terry Carroll wrote:
> On Wed, 19 Sep 2007, Boykie Mackay wrote:
>
>   
>> if not n&1:
>>     return false
>>
>> The above should return false for all even numbers,numbers being
>> represented by n.I have tried to wrap my head around the 'not n&1' but
>> I'm failing to understand what's going on.Could someone please explain
>> the statement.
>>     
>
> Others have explained why this works, but let me rail against this code 
> for a moment.  IMHO, a bitwise operation is appropriate only when the 
> field being operated on is a set of bits with bitwise information; for 
> example, if the right-most bit was a flag bit of some sort, N&1 is a 
> perfectly appropriate operation.
>
> But evenness/oddness is a property of numbers, and the code would be much 
> easier to understand if the parameter was treated as a number, rather than 
> as a field of bits, i.e.:
>
>   
>>>> def isodd(n):
>>>>         
> ...  return bool(n%2)
> ...
>   
>>>> isodd(4)
>>>>         
> False
>   
>>>> isodd(7)
>>>>         
> True
>   
>
> Mind you, I'll bet that the bit-checking method is slightly faster than
> the modulus operation in my little piece of code above.  

 ><
> I'll also bet
> that, if you added up the amount of time that was saved by using the
> bitwise approach over the modulus approach, over all executions of the
> program everywhere, it probably would be a smaller amount of time than it
> would take for a programmmer maintaining the program to find out what that
> line of code is supposed to do.
>
> </soapbox>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



More information about the Tutor mailing list