all permutations of a binary sequence x bits long all permutations of a binary sequence x bits long python python

all permutations of a binary sequence x bits long


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


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 sprint list(perms(5))


You can use itertools.product() for doing this.

import itertoolsdef binseq(k):    return [''.join(x) for x in itertools.product('01', repeat=k)]