Get the the number of zeros and ones of a binary number in Python

和自甴很熟 提交于 2020-08-02 17:50:13

问题


I am trying to solve a binary puzzle, my strategy is to transform a grid in zeros and ones, and what I want to make sure is that every row has the same amount of 0 and 1.

Is there a any way to count how many 1s and 0s a number has without iterating through the number?

What I am currently doing is:

def binary(num, length=4):
    return format(num, '#0{}b'.format(length + 2)).replace('0b', '')

n = binary(112, 8)
// '01110000'
and then
n.count('0')
n.count('1')

Is there any more efficient computational (or maths way) of doing that?


回答1:


If the length is moderate (say less than 20), you can use a list as a lookup table.

It's only worth generating the list if you're doing a lot of lookups, but it seems you might in this case.

eg. For a 16 bit table of the 0 count, use this

zeros = [format(n, '016b').count('0') for n in range(1<<16)]
ones = [format(n, '016b').count('1') for n in range(1<<16)]

20 bits still takes under a second to generate on this computer

Edit: this seems slightly faster:

zeros = [20 - bin(n).count('1') for n in range(1<<20)]
ones = [bin(n).count('1') for n in range(1<<20)]



回答2:


What you're looking for is the Hamming weight of a number. In a lower-level language, you'd probably use a nifty SIMD within a register trick or a library function to compute this. In Python, the shortest and most efficient way is to just turn it into a binary string and count the '1's:

def ones(num):
    # Note that bin is a built-in
    return bin(num).count('1')

You can get the number of zeros by subtracting ones(num) from the total number of digits.

def zeros(num, length):
    return length - ones(num)

Demonstration:

>>> bin(17)
'0b10001'
>>> # leading 0b doesn't affect the number of 1s
>>> ones(17)
2
>>> zeros(17, length=6)
4


来源:https://stackoverflow.com/questions/20517570/get-the-the-number-of-zeros-and-ones-of-a-binary-number-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!