bit count or bit set && Python3
Chris Angelico
rosuav at gmail.com
Thu Oct 25 11:31:53 EDT 2012
On Fri, Oct 26, 2012 at 2:25 AM, Christian Heimes <christian at python.org> wrote:
> Simple, easy, faster than a Python loop but not very elegant:
>
> bin(number).count("1")
Unlikely to be fast.
What you may want is some sort of hybrid loop/lookup approach. Do you
know what your highest bit number is going to be? For instance, are
all your integers 32-bit? You could use something like this:
c = bitcount[n&255] + bitcount[n>>8&255] + bitcount[n>>16&255] + bitcount[n>>24]
where bitcount is a list of 256 values, giving the counts for each
value from 0 to 255.
Profile and test. :)
ChrisA
More information about the Python-list
mailing list