获取Python中的零和一个二进制数 [英] Get the the number of zeros and ones of a binary number in Python

查看:69
本文介绍了获取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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆