获取Python中的零和一个二进制数 [英] Get the the number of zeros and ones of a binary number in Python
问题描述
我正在尝试解决一个二元难题,我的策略是将网格转换为零和一,并且我想确保的是每行都具有相同的0和1.
有没有办法在不迭代数字的情况下计算一个数字有多少个1和0?
我目前正在做的是:
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')
有没有更有效的计算方法(或数学方法)?
如果length
是中等级别(例如小于20),则可以将列表用作查找表.
仅当您进行大量查找时才值得生成列表,但在这种情况下似乎可以.
例如对于0
计数的16位表,请使用此
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位数据还需要不到一秒钟的时间
:这似乎稍微快一点:
zeros = [20 - bin(n).count('1') for n in range(1<<20)]
ones = [bin(n).count('1') for n in range(1<<20)]
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?
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)]
这篇关于获取Python中的零和一个二进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!