首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在python中生成唯一的二进制排列

在python中生成唯一的二进制排列
EN

Stack Overflow用户
提问于 2018-05-30 04:39:02
回答 3查看 2.4K关注 0票数 12

请问,我如何才能获得所有这些二进制排列,而不是在Python中重复?

 a = list(itertools.permutations([1, 1, 0, 0]))
 for i in range(len(a)):
     print a[i]

    (1, 1, 0, 0)
    (1, 1, 0, 0)
    (1, 0, 1, 0)
    ...

如果它的效率很高,那就太好了,因为我必须使用一个包含30个元素的列表才能做到这一点。

EN

回答 3

Stack Overflow用户

发布于 2018-05-30 04:49:24

正如@Antti在评论中所说的,这相当于查找输入列表的位置的combinations,它确定输出中的哪些位是1。

from itertools import combinations

def binary_permutations(lst):
    for comb in combinations(range(len(lst)), lst.count(1)):
        result = [0] * len(lst)
        for i in comb:
            result[i] = 1
        yield result

for perm in binary_permutations([1, 1, 0, 0]):
    print(perm)

输出:

[1, 1, 0, 0]
[1, 0, 1, 0]
[1, 0, 0, 1]
[0, 1, 1, 0]
[0, 1, 0, 1]
[0, 0, 1, 1]
票数 11
EN

Stack Overflow用户

发布于 2018-05-30 04:52:01

您要做的是选择元素将为1的两个位置。

代码

from itertools import combinations

def bit_patterns(size, ones):
    for pos in map(set, combinations(range(size), ones)):
        yield [int(i in pos) for i in range(size)]

输出

>>> print(*bit_patterns(4, 2), sep='\n')
[1, 1, 0, 0]
[1, 0, 1, 0]
[1, 0, 0, 1]
[0, 1, 1, 0]
[0, 1, 0, 1]
[0, 0, 1, 1]

替代方案

一种有趣的替代方法是将期望的输出看作只有两个1的二进制表示。我们可以使用这个定义来得到你想要的输出。

from itertools import combinations

def bit_patterns(size, ones):
    for t in combinations([1 << i for i in range(size)], ones):
        yield [int(n) for n in f'{sum(t):0{size}b}']
票数 1
EN

Stack Overflow用户

发布于 2018-05-30 05:42:55

下面是一个递归解决方案:

def bin_combs_iter(ones, zeros):
    if not zeros:
        yield [1] * ones
    elif not ones:
        yield [0] * zeros
    else:
        for x in bin_combs_iter(ones - 1, zeros):
            x.append(1)
            yield x
        for x in bin_combs_iter(ones, zeros - 1):
            x.append(0)
            yield x


def bin_combs(ones, zeros):
    return list(bin_combs_iter(ones, zeros))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50592576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档