Skip to main content
 首页 » 编程设计

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

2024年08月28日40lvdongjie

设 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',)) 
]