Mark Dickinson <dicki...@gmail.com> wrote: > 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 remember a programming exercise when I was an undergraduate and anyone who *didn't* use that trick got marked down for writing inefficient code. -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list