Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #32135

Re: bit count or bit set && Python3

References <5089511E.4090009@earthlink.net> <k6bllq$3gt$1@ger.gmane.org>
Date 2012-10-26 02:31 +1100
Subject Re: bit count or bit set && Python3
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.2849.1351179123.27098.python-list@python.org> (permalink)

Show all headers | View raw


On Fri, Oct 26, 2012 at 2:25 AM, Christian Heimes <christian@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

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: bit count or bit set && Python3 Chris Angelico <rosuav@gmail.com> - 2012-10-26 02:31 +1100
  Re: bit count or bit set && Python3 Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-10-25 15:57 +0000
    Re: bit count or bit set && Python3 rusi <rustompmody@gmail.com> - 2012-10-25 09:17 -0700
      Re: bit count or bit set && Python3 Chris Angelico <rosuav@gmail.com> - 2012-10-26 03:29 +1100
        Re: bit count or bit set && Python3 rusi <rustompmody@gmail.com> - 2012-10-25 09:37 -0700
      Re: bit count or bit set && Python3 Mark Lawrence <breamoreboy@yahoo.co.uk> - 2012-10-25 17:44 +0100
      Re: bit count or bit set && Python3 Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-10-25 17:16 +0000
    Re: bit count or bit set && Python3 Serhiy Storchaka <storchaka@gmail.com> - 2012-10-25 22:07 +0300
    Re: bit count or bit set && Python3 Neil Cerutti <neilc@norwich.edu> - 2012-10-25 20:00 +0000
      Re: bit count or bit set && Python3 Neil Cerutti <neilc@norwich.edu> - 2012-10-25 20:04 +0000
      Re: bit count or bit set && Python3 Ian Kelly <ian.g.kelly@gmail.com> - 2012-10-25 14:20 -0600
        Re: bit count or bit set && Python3 Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-10-25 23:48 +0000
        Re: bit count or bit set && Python3 Neil Cerutti <neilc@norwich.edu> - 2012-10-26 12:56 +0000
    Re: bit count or bit set && Python3 Charles Hixson <charleshixsn@earthlink.net> - 2012-10-25 09:08 -0700
    Re: bit count or bit set && Python3 Mark Lawrence <breamoreboy@yahoo.co.uk> - 2012-10-25 22:51 +0100

csiph-web