Determining combination of bits

Scott David Daniels Scott.Daniels at Acm.Org
Mon Nov 8 16:21:31 EST 2004


Sean Berry wrote:
> Just to set everyone's mind at ease... I haven't had a homework assignment 
> for about four years now.
OK, then here's a great little bit of education:

    n & -n == least significant bit of n

So, for example:

     def bits(n):
         assert n >= 0 # This is an infinite loop if n < 0
         while n:
             lsb = n & -b
             yield lsb
             n ^= lsb

-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list