Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
生成具有固定位置的二进制组合(Python)_Python_Itertools - Fatal编程技术网

生成具有固定位置的二进制组合(Python)

生成具有固定位置的二进制组合(Python),python,itertools,Python,Itertools,我想生成一个元组列表,其中包含大小为n=16的0/1的所有可能组合,但某些位置是固定的。所以有些位置固定为0或1(x,x,x,x,x,1,x,x,x,x,0,0,x,x,x,x,x,x)。我知道我们可以使用itertools生成所有可能的组合,而无需任何固定位置: import itertools permutations = list(itertools.product([0, 1], repeat=16)) 我曾想过生成repeat=13的所有组合,然后插入固定位置,但这对我来说似乎很麻

我想生成一个元组列表,其中包含大小为n=16的0/1的所有可能组合,但某些位置是固定的。所以有些位置固定为0或1(x,x,x,x,x,1,x,x,x,x,0,0,x,x,x,x,x,x)。我知道我们可以使用
itertools
生成所有可能的组合,而无需任何固定位置:

import itertools

permutations = list(itertools.product([0, 1], repeat=16))

我曾想过生成repeat=13的所有组合,然后插入固定位置,但这对我来说似乎很麻烦。有没有更简单更快的方法来实现这一点?

我喜欢递归:

n_bits = 8
fixed = {0:"0",
        3:"1"}

def permut_fixed(n_bits, fixed):
    def aux(base, bits_left):
        if bits_left<=0:
            return [base]
        if len(base) in fixed:
            return aux(base+fixed[len(base)], bits_left-1)
        else:
            return [*aux(base+"0", bits_left-1), *aux(base+"1", bits_left-1)]
    return aux("", n_bits)

print(permut_fixed(n_bits, fixed))
# ['00010000', '00010001', ..., '01111011', '01111100', '01111101', '01111110', '01111111']
print(len(permut_fixed(n_bits, fixed)))
# 64 which is 2**6 and we have 6 slots to fill
n_位=8
固定={0:“0”,
3:"1"}
def permut_固定(n_位,固定):
def aux(基本位,左位):

如果位_离开仅根据
itertools.product
进行一点更改:

def custom_product(f, repeat=0):
    return itertools.product(*[f.get(i, [0, 1]) for i in range(repeat)])

fixed = {4: [1], 8: [0], 9: [0]}
print(*custom_product(fixed, 16), sep="\n")

结果的格式与您的预期相同。

“我在考虑用repeat=13生成所有组合,然后插入固定位置”->这看起来是适合我的方法。您正在生成所需的内容。当然,有几种方法可以做到这一点,有些方法可能比其他方法更优雅/高效。完全等效地,您生成了三个xxx部分(在1之前,在1和00之间,在00之后)。我还认为您已经找到了正确的方法。但作为旁注,你有没有考虑过1和0的组合实际上只是二进制数?您可以为0到2**13之间的x值动态生成它们(x,'013b')。这是一个很好的排列练习,谢谢如果我的答案真的有效,只需在答案旁边打勾即可。;)