gpt4 book ai didi

python - 生成包含集合所有元素的子集的所有可能排列

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:26 25 4
gpt4 key购买 nike

设 S(w) 为一组单词。我想生成子集 s 的所有可能的 n 组合,以便这些子集的并集始终等于 S(w)。

所以你有一个集合 (a, b, c, d, e) 而你不需要所有的 3 种组合:

((a, b, c), (d), (e))

((a, b), (c, d), (e))

((a), (b, c, d), (e))

((a), (b, c), (d, e))

等...

对于每个组合,您有 3 个集合,这些集合的并集就是原始集合。没有空集,没有缺失元素。

必须有一种方法可以使用 itertools.combination + collection.Counter 来做到这一点,但我什至无法从某个地方开始......有人可以帮忙吗?

卢克

编辑:我需要捕获所有可能的组合,包括:

((a, e), (b, d) (c))

等...

最佳答案

是这样的吗?

from itertools import combinations, permutations
t = ('a', 'b', 'c', 'd', 'e')
slicer = [x for x in combinations(range(1, len(t)), 2)]
result = [(x[0:i], x[i:j], x[j:]) for i, j in slicer for x in permutations(t, len(t))]

一般解决方案,对于任何 n 和任何元组长度:

from itertools import combinations, permutations
t = ("a", "b", "c")
n = 2
slicer = [x for x in combinations(range(1, len(t)), n - 1)]
slicer = [(0,) + x + (len(t),) for x in slicer]
perm = list(permutations(t, len(t)))
result = [tuple(p[s[i]:s[i + 1]] for i in range(len(s) - 1)) for s in slicer for p in perm]

[
(('a',), ('b', 'c')),
(('a',), ('c', 'b')),
(('b',), ('a', 'c')),
(('b',), ('c', 'a')),
(('c',), ('a', 'b')),
(('c',), ('b', 'a')),
(('a', 'b'), ('c',)),
(('a', 'c'), ('b',)),
(('b', 'a'), ('c',)),
(('b', 'c'), ('a',)),
(('c', 'a'), ('b',)),
(('c', 'b'), ('a',))
]

关于python - 生成包含集合所有元素的子集的所有可能排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18154860/

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