我想找到一种干净聪明的方式(用 Python),以找到长度为 x 的由 1 和 0 组成的所有字符串的排列。理想情况下,这应该是快速的,不需要进行太多次迭代...
因此,对于 x = 1,我希望得到: ['0','1'] x =2 ['00','01','10','11'] 等等...
目前我有以下代码,但它很慢,似乎也不优雅:
因此,对于 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]