# all permutations of a binary sequence x bits long

### Question

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 = list(perms)
perms.sort()
self.to_bits = {}
self.to_code = {}
for x in enumerate(perms):
self.to_bits[x] = ''.join([str(y) for y in x])
self.to_code[''.join([str(y) for y in x])] = x
``````
1
24
2/8/2011 12:33:51 AM

`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']
``````
58
2/8/2011 12:31:14 AM

There's no need to be overly clever for something this simple:

``````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))
``````