bpo-29882: Add an efficient popcount method for integers (#771)

* bpo-29882: Add an efficient popcount method for integers

* Update 'sign bit' and versionadded in docs

* Add entry to whatsnew document

* Doc: use positive example, mention population count

* Minor cleanups of the core code

* Move popcount_digit closer to where it's used

* Use z instead of self after conversion

* Add 'absolute value' and 'population count' to docstring

* Fix clinic error about missing summary line

* Ensure popcount_digit is portable with 64-bit ints

Co-authored-by: Mark Dickinson <dickinsm@gmail.com>
This commit is contained in:
Niklas Fiekas 2020-05-29 18:28:02 +02:00 committed by GitHub
parent 364b5ead15
commit 8bd216dfed
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 135 additions and 2 deletions

View file

@ -478,6 +478,27 @@ class`. In addition, it provides a few more methods:
.. versionadded:: 3.1
.. method:: int.bit_count()
Return the number of ones in the binary representation of the absolute
value of the integer. This is also known as the population count.
Example::
>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
>>> (-n).bit_count()
3
Equivalent to::
def bit_count(self):
return bin(self).count("1")
.. versionadded:: 3.10
.. method:: int.to_bytes(length, byteorder, \*, signed=False)
Return an array of bytes representing an integer.

View file

@ -70,6 +70,9 @@ Summary -- Release highlights
New Features
============
* The :class:`int` type has a new method :meth:`int.bit_count`, returning the
number of ones in the binary expansion of a given integer, also known
as the population count. (Contributed by Niklas Fiekas in :issue:`29882`.)
Other Language Changes