python - 二进制序列 x 位长的所有排列

标签 python algorithm combinatorics

我想找到一种干净而聪明的方法(在 python 中)来查找长度为 1 和 0 x 字符的字符串的所有排列。理想情况下,这会很快,并且不需要进行太多迭代......

所以,对于 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]

最佳答案

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

关于python - 二进制序列 x 位长的所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4928297/

相关文章:

c++ - 如何提高大整数的乘法效率?

java - 在不将它们存储到内存中的情况下一一获得组合的算法

python - Matplotlib:限制绘图宽度同时允许灵活的高度

python - OpenCV evaluateFeatureDetector for Python?

algorithm - 计算 O(1) 中数字的位数

r - 在 R 中打印不重复的组合

c# - X 的所有可能组合分成 N 个堆栈

android - 问题+澄清 : Sending message from Raspberry Pi to Android Phone using Google cloud Messaging

python - 在 keras 中使用 TFRecords

algorithm - 如何简化/优化 3d 路径?