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

Tim Chase python.list at tim.thechases.com
Wed Feb 4 20:43:15 EST 2009


> Using while loop and if statement, I'm trying to get Python to
> tell me whether there are even or odd number of 1's in a
> binary representation. For example, if I give Python a
> 00000111, then I want it to say that the binary representation
> given has an odd number of 1's. If I give it 00010111, then it
> will tell me that there is an even number of 1's. I'd
> appreciate any suggestion.

A couple come to mind.  First, start by counting the bits.  If 
it's a string, this is easy:

   b = "00010111"
   result = b.count('1')

If it's an integer datatype instead of as string, as long as you 
know the number of bits to expect, you can use

   x = 0xf7
   result = sum((x >> i) & 1 for i in range(8))

where 8 is the number of bits you expect.  If you don't know the 
number of bits to expect, you'd have to do it in a more 
open-ended loop:

   x = 0xDEADBEEF
   result = 0
   while x:
     result += x & 1
     x >>= 1

Once you have the resulting count, you can then check if it's 
even or odd:

   if result & 1:
     print "Odd"
   else:
     print "Even"

Hope this helps,

-tkc







More information about the Python-list mailing list