【问题标题】:all permutations of a binary sequence x bits long二进制序列 x 位长的所有排列
【发布时间】:2018-12-02 22:44:51
【问题描述】:

我想找到一种干净而聪明的方法(在 python 中)来查找长度为 1 和 0 x 字符的字符串的所有排列。理想情况下,这会很快,并且不需要进行太多迭代......

所以,对于 x = 1,我想要: ['0','1'] x =2 ['00','01','10','11']

等等。

现在我有这个,它很慢而且看起来不优雅:

    self.nbits = n
    items = []
    for x in xrange(n+1):
        ones = x
        zeros = n-x
        item = []
        for i in xrange(ones):
            item.append(1)
        for i in xrange(zeros):
            item.append(0)
        items.append(item)
    perms = set()
    for item in items:
        for perm in itertools.permutations(item):
            perms.add(perm)
    perms = list(perms)
    perms.sort()
    self.to_bits = {}
    self.to_code = {}
    for x in enumerate(perms):
        self.to_bits[x[0]] = ''.join([str(y) for y in x[1]])
        self.to_code[''.join([str(y) for y in x[1]])] = x[0]

【问题讨论】:

  • 请注意,您实际上并不是在描述排列。
  • 我感觉有一个代码高尔夫回答流即将到来。 :-)

标签: python algorithm combinatorics


【解决方案1】:

itertools.product 就是为此而生的:

>>> import itertools
>>> ["".join(seq) for seq in itertools.product("01", repeat=2)]
['00', '01', '10', '11']
>>> ["".join(seq) for seq in itertools.product("01", repeat=3)]
['000', '001', '010', '011', '100', '101', '110', '111']

【讨论】:

  • 谢谢,这就是我要找的!
【解决方案2】:

对于这么简单的事情没有必要过于聪明:

def perms(n):
    if not n:
        return

    for i in xrange(2**n):
        s = bin(i)[2:]
        s = "0" * (n-len(s)) + s
        yield s

print list(perms(5))

【讨论】:

    【解决方案3】:

    您可以使用itertools.product() 来执行此操作。

    import itertools
    def binseq(k):
        return [''.join(x) for x in itertools.product('01', repeat=k)]
    

    【讨论】:

    • 请注意,您可以使用map 作为循环结构来加快速度:map(''.join, itertools.product('01', repeat=k))
    • @ncoghlan 不过,他们不会做同样的事情。
    • 考虑到时间(2011 年初),我可能在谈论 Python 2,它仍然会生成一个列表。实际上,在 Py3 中,基于map 的版本会生成一个惰性迭代器,而不是一个具体的列表(这可能是也可能不是你想要的)。
    【解决方案4】:

    Python 2.6+:

    ['{0:0{width}b}'.format(v, width=x) for v in xrange(2**x)]
    

    【讨论】:

    • 聪明,但(至少在我的机器上,大小适中 2**(16...20))比 Josh 的回答慢了 ~3。
    【解决方案5】:

    向我面前的所有聪明解决方案致敬。这是一种低级的、弄脏你的方法:

    def dec2bin(n):
        if not n:
            return ''
        else:
            return dec2bin(n/2) + str(n%2)
    
    def pad(p, s):
        return "0"*(p-len(s))+s
    
    def combos(n):
        for i in range(2**n):
            print pad(n, dec2bin(i))
    

    这应该可以解决问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-20
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      相关资源
      最近更新 更多