2023-05-25 08:19:15 -06:00
|
|
|
__all__ = ["popCount", "bit_count", "bit_indices"]
|
2018-11-10 15:16:52 -05:00
|
|
|
|
|
|
|
|
2021-06-04 10:03:21 -06:00
|
|
|
try:
|
|
|
|
bit_count = int.bit_count
|
|
|
|
except AttributeError:
|
2021-05-28 16:46:20 +01:00
|
|
|
|
2021-06-04 10:03:21 -06:00
|
|
|
def bit_count(v):
|
2021-05-28 16:46:20 +01:00
|
|
|
return bin(v).count("1")
|
|
|
|
|
2020-06-08 15:53:48 +01:00
|
|
|
|
2021-06-04 10:03:21 -06:00
|
|
|
"""Return number of 1 bits (population count) of the absolute value of an integer.
|
2020-06-08 15:53:48 +01:00
|
|
|
|
2021-06-04 10:03:21 -06:00
|
|
|
See https://docs.python.org/3.10/library/stdtypes.html#int.bit_count
|
|
|
|
"""
|
2023-05-25 08:19:15 -06:00
|
|
|
popCount = bit_count # alias
|
2021-05-28 16:46:20 +01:00
|
|
|
|
|
|
|
|
|
|
|
def bit_indices(v):
|
|
|
|
"""Return list of indices where bits are set, 0 being the index of the least significant bit.
|
|
|
|
|
|
|
|
>>> bit_indices(0b101)
|
|
|
|
[0, 2]
|
|
|
|
"""
|
|
|
|
return [i for i, b in enumerate(bin(v)[::-1]) if b == "1"]
|