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

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

我试图在 5 位中获得所有可能的组合,1 位为 0,2 位为 0,...,4 位为 0

例如 1 位应该是这样的:[11110, 11101, 11011, 10111, 01111]

我正在使用列表理解:

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)]
...

它有效,但我认为有一种重复性较低且漂亮的方法,知道吗?

试试 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]}

一个不错的方法是使用 itertools 中的组合函数。

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)}

生成的字典:

{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]}

从 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)

结果:

[[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]]