我想找个干净和巧妙的方法(在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']