【问题标题】:Generating binary combinations with fixed places (Python)生成具有固定位置的二进制组合(Python)
【发布时间】:2021-05-28 12:35:17
【问题描述】:

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

import itertools

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

我正在考虑使用 repeat=13 生成所有组合,然后插入固定位置,但这对我来说似乎太麻烦了。有没有更简单、更快捷的方法来实现这一目标?

【问题讨论】:

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

标签: python itertools


【解决方案1】:

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

结果的格式和你预期的一样。

【讨论】:

    【解决方案2】:

    我喜欢递归:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多