Using while loop and if statement to tell if a binary has an odd or even number of 1's.
MRAB
google at mrabarnett.plus.com
Thu Feb 5 10:36:14 EST 2009
Mark Dickinson wrote:
> On Feb 5, 1:18 am, Chris Rebert <c... at rebertia.com> wrote:
>> For an integer:
>> is_even = bin(the_int)[2:].count('1') % 2 == 0
>
> But the OP has to use if and while. How about:
>
> while 2+2 != 5:
> if 'wkw' in 'just being awkward':
> is_even = bin(the_int)[2:].count('1') % 2 == 0
> break
>
> or (Python 2.5 compatible):
>
> def count_set_bits(n):
> # make sure we include an if, to
> # satisfy OP's requirements:
> if n < 0:
> raise ValueError
> count = 0
> while n:
> count += 1
> n &= n-1
> return count
>
> is_even = count_set_bits(the_int) % 2 == 0
>
> ...but anyone submitting this as a homework
> solution had better be prepared to explain why
> it works.
>
I haven't seen that algorithm before. Very clever! :-)
More information about the Python-list
mailing list