Determining combination of bits

news.west.cox.net sean.berry2 at cox.net
Tue Nov 9 00:06:31 EST 2004


"Scott David Daniels" <Scott.Daniels at Acm.Org> wrote in message 
news:418ff674$1 at nntp0.pdx.net...
> 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:
>

Better than the education I got at UCSB...

>    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
>

Perfect.  This not only does exactly what I wanted... but I have just 
started to learn about generators, and this does great.

Thank you very much for the help everyone.




> -Scott David Daniels
> Scott.Daniels at Acm.Org 





More information about the Python-list mailing list