Com*_*nce 25 python algorithm combinatorics
我想找到一个干净而聪明的方法(在python中)来查找1s和0s x chars long的字符串的所有排列.理想情况下,这将是快速的,不需要做太多的迭代......
因此,对于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]
Run Code Online (Sandbox Code Playgroud)
Jos*_*der 60
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']
Run Code Online (Sandbox Code Playgroud)
对于这么简单的事情,没有必要过于聪明:
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))
Run Code Online (Sandbox Code Playgroud)
您可以itertools.product()
用于执行此操作。
import itertools
def binseq(k):
return [''.join(x) for x in itertools.product('01', repeat=k)]
Run Code Online (Sandbox Code Playgroud)
Python 2.6+:
['{0:0{width}b}'.format(v, width=x) for v in xrange(2**x)]
Run Code Online (Sandbox Code Playgroud)