gpt4 book ai didi

python - 如何获得数量为 1's are equal to or more than the number of 0' 的 n 个二进制值的所有组合?

转载 作者:行者123 更新时间:2023-12-05 00:50:50 24 4
gpt4 key购买 nike

我想查找 0 和 1 的所有可能组合的列表。唯一的条件是 1 的数量必须大于或等于 0 的数量。例如对于 n = 4,输出应该是这样的:

[(0, 0, 1, 1), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]

有没有优雅的方法来做到这一点?

最佳答案

您可以使用 distinct_permutations:

from more_itertools import distinct_permutations

def get_combos(n):
for i in range((n+1)//2, n + 1):
for permutation in distinct_permutations([1] * i + [0] * (n - i), n):
yield permutation
print(list(get_combos(4)))
# [(0, 0, 1, 1), (0, 1, 0, 1), (0, 1, 1, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 1, 0, 0), (0, 1, 1, 1), (1, 0, 1, 1), (1, 1, 0, 1), (1, 1, 1, 0)]

这里,我们只考虑每个子列表的排列:

[0, 0, 1, 1]
[0, 1, 1, 1]
[1, 1, 1, 1]

请注意,对于较大的 nyield 语句非常有用,因为您不会一次生成所有排列。

我们需要使用 distinct_permutations 因为你只使用 1 和 0 ,所以常规排列会给你重复的元素。


如果不想安装其他库,可以使用:

from itertools import permutations

def get_combos(n):
for i in range(n // 2 if n%2 == 0 else n//2 + 1, n):
for permutation in permutations([1] * i + [0] * (n - i), n):
yield permutation
print(set(get_combos(4)))
# {(0, 1, 0, 1), (0, 1, 1, 1), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 1, 0), (0, 1, 1, 0), (1, 0, 1, 0), (1, 0, 0, 1), (1, 1, 0, 1), (0, 0, 1, 1)}

as set 将消除重复的元素,代价是需要一次处理整个排列集(即,通过调用 set,您将消耗立即生成整个生成器,而不是根据需要从中提取元素)。

有关 distinct_permutations 的更多详细信息

可能不清楚为什么需要这些。考虑这个列表:

[1, 2]

排列,默认情况下,会告诉你这个列表的所有排列都是

(1, 2)

(2, 1)

但是,permutations 不会检查元素是什么或它们是否重复,所以它只是像上面那样执行交换以及列表是否是

[1, 1]

你会回来的

[(1, 1), (1, 1)]

关于python - 如何获得数量为 1's are equal to or more than the number of 0' 的 n 个二进制值的所有组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74005380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com