我想知道如何生成给定长度的每个偶数为0‘S和1’S的二进制数的最好方法.我目前正在用一种强力方法来生成字符串,我认为这是一种垃圾的方法:
def max_bits(b):
return (1 << b) - 1
def binary_options(digits):
target = digits / 2
return [f"{i:b}" for i in range(max_bits(digits - 1), 2 ** digits) if f"{i:b}".count("0") == target]
我使用二进制数作为索引,对拆分为两个偶数部分的数组的所有可能组合求和,所以我实际上不需要存储这些组合,我可以边走边求和,我也不需要将二进制数作为字符串.请参见下面的示例.
arr = [1,2,3,4]
comb1 = 1001 # 1 + 4 and 2 + 3
comb2 = 1010 # 1 + 3 and 2 + 4
comb3 = 1100 # 1 + 2 and 3 + 4
非常感谢.
编辑:
很抱歉之前没有提到这一点,但我不需要生成解的逆,所以我只需要潜在排列的一半.例如,在上面的示例中,我有1001
、1010
和1100
,但没有0110
、0101
或0011
.
发帖主题:Re:Kolibrios
马克提供了最好的解决方案.为了只生成一半的二进制数(因为我不需要倒数),我使用下面的函数.我还将二进制数存储为整数,而不是字符串,并使用this answer中提供的方法将整数的位用作索引.
def binary_options(digits):
target = digits / 2
return [i for i in range(int('1' * (digits - 1), 2)) if i.bit_count() == target]