本文介绍了的二进制序列的所有排列X比特长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找个干净和巧妙的方法(在Python)发现的1和0 x字符的长字符串的所有排列。理想情况下,这将是快速而并不需要做太多的迭代...

因此​​,对于x = 1我想:['0','1']X = 2['00','01','10','11']

等。

现在我有这个,这是缓慢的,似乎不雅:

  self.nbits = N
    项= []
    对于x中的xrange第(n + 1):
        那些= X
        零= N-X
        项目= []
        对我的xrange(的):
            item.append(1)
        对我的xrange(零):
            item.append(0)
        items.append(项目)
    烫发=设置()
    在项目的项目:
        用于烫发的和itertools.permutations(项目):
            perms.add(烫)
    烫发=列表(烫发)
    perms.sort()
    self.to_bits = {}
    self.to_ code = {}
    对于x在历数(烫发):
        self.to_bits [X [0]] =''。加入([海峡(y)的y的x中[1]])
        self.to_ code [(在X [STR(Y)的Y 1])''。加入] = X [0]
 

解决方案

itertools.product 在为此:

 >>>进口itertools
>>> [。加入(SEQ)为以次在itertools.product(01,重复= 2)]
['00','01','10','11']
>>> [。加入(SEQ)为以次在itertools.product(01,重复= 3)]
['000','001','010','011','100','101','110','111']
 

I would like to find a clean and clever way (in python) to find all permutations of strings of 1s and 0s x chars long. Ideally this would be fast and not require doing too many iterations...

So, for x = 1 I want:['0','1']x =2['00','01','10','11']

etc..

Right now I have this, which is slow and seems inelegant:

    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]
解决方案

itertools.product is made for this:

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

这篇关于的二进制序列的所有排列X比特长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 23:10