all permutations of a binary sequence x bits long

久未见 提交于 2019-11-27 04:04:32

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 s

print list(perms(5))

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

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

Python 2.6+:

['{0:0{width}b}'.format(v, width=x) for v in xrange(2**x)]

Kudos to all the clever solutions before me. Here is a low-level, get-you-hands-dirty way to do this:

def dec2bin(n):
    if not n:
        return ''
    else:
        return dec2bin(n/2) + str(n%2)

def pad(p, s):
    return "0"*(p-len(s))+s

def combos(n):
    for i in range(2**n):
        print pad(n, dec2bin(i))

That should do the trick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!