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


Groups > comp.lang.python > #32132 > unrolled thread

Re: bit count or bit set && Python3

Started byMRAB <python@mrabarnett.plus.com>
First post2012-10-25 16:18 +0100
Last post2012-10-25 16:18 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: bit count or bit set && Python3 MRAB <python@mrabarnett.plus.com> - 2012-10-25 16:18 +0100

#32132 — Re: bit count or bit set && Python3

FromMRAB <python@mrabarnett.plus.com>
Date2012-10-25 16:18 +0100
SubjectRe: bit count or bit set && Python3
Message-ID<mailman.2847.1351178334.27098.python-list@python.org>
On 2012-10-25 15:47, Charles Hixson wrote:
> In Python3 is there any good way to count the number of on bits in an
> integer (after an & operation)?
> Alternatively, is there any VERY light-weight implementation of a bit
> set?  I'd prefer to use integers, as I'm probably going to need
> thousands of these, if the tests work out.  But before I can test, I
> need a decent bit counter.  (shift, xor, &, and | are already present
> for integer values, but I also need to count the number of "true" items
> after the logical operation.  So if a bitset is the correct approach,
> I'll need it to implement those operations, or their equivalents in
> terms of union and intersection.)
>
> Or do I need to drop into C for this?
>
There's a nice algorithm for counting the ones. It takes one iteration
per set bit:

def count_set_bits(number):
     count = 0
     while number:
         count += 1
         number &= number - 1
     return count

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web