简体   繁体   English

1、2、3、4位组合为5位中的0

[英]Combinaison of 1, 2, 3, 4 bits as 0 in 5bits

I'm trying to get all possible combination with 1 bit as 0, 2 bits as 0, ..., 4 bits as 0 in 5bits我正在尝试获得所有可能的组合,其中 1 位为 0,2 位为 0,...,4 位为 5 位中的 0

for example for 1 bit it should be like that: [11110, 11101, 11011, 10111, 01111]例如 1 位应该是这样的: [11110, 11101, 11011, 10111, 01111]

I'm using a list comprehension:我正在使用列表理解:

five_mask = int('11111', 2)
# for 1 bit
[five_mask ^ 2**i for i in range(0, 5)]
# for 2 bits
[five_mask ^ (2**i | 2**j) for i in range(0, 5) for j in range(i+1, 5)]
# for 3 bits
[five_mask ^ (2**i | 2**j | 2**k) for i in range(0, 5) for j in range(i+1, 5) for k in range(j+1, 5)]
...

It works but I thing there's a less repetitive and pretty way, any idea?它有效,但我认为有一种不那么重复且漂亮的方法,知道吗?

Since Python 3.10 we can use int.bit_count (in older versions we can use bin(i).count('1') ).从 Python 3.10 开始,我们可以使用int.bit_count (在旧版本中,我们可以使用bin(i).count('1') )。

n = 5

a = [[] for _ in range(n+1)]
for i in range(2**n):
    a[i.bit_count()].append(i)

Result:结果:

[[0],
 [1, 2, 4, 8, 16],                          # for 4 bits
 [3, 5, 6, 9, 10, 12, 17, 18, 20, 24],      # for 3 bits
 [7, 11, 13, 14, 19, 21, 22, 25, 26, 28],   # for 2 bits
 [15, 23, 27, 29, 30],                      # for 1 bit
 [31]]

Try with itertools.product :尝试使用itertools.product

import itertools

output = dict()
for i in itertools.product(("0","1"),repeat=5):
    key = i.count("0")
    value = int("".join(i), 2)
    if key not in output:
        output[key] = list()
    output[key].append(value)

>>> output
{5: [0],
 4: [1, 2, 4, 8, 16],
 3: [3, 5, 6, 9, 10, 12, 17, 18, 20, 24],
 2: [7, 11, 13, 14, 19, 21, 22, 25, 26, 28],
 1: [15, 23, 27, 29, 30],
 0: [31]}

One nice approach is to use the combinations function from itertools.一种不错的方法是使用 itertools 中的组合 function。

from itertools import combinations

d = {k:[sum(t) for t in combinations([2**i for i in range(5)],5-k)] for k in range(6)}

The resulting dictionary:结果字典:

{0: [31],
 1: [15, 23, 27, 29, 30],
 2: [7, 11, 19, 13, 21, 25, 14, 22, 26, 28],
 3: [3, 5, 9, 17, 6, 10, 18, 12, 20, 24],
 4: [1, 2, 4, 8, 16],
 5: [0]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM