简体   繁体   English

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

[英]Generate all possible permutations of subsets containing all the element of a set

Let S(w) be a set of words. 令S(w)为一组单词。 I want to generate all the possible n-combination of subsets s so that the union of those subsets are always equal to S(w). 我想生成子集s的所有可能的n组合,以使这些子集的并集始终等于S(w)。

So you have a set (a, b, c, d, e) and you wan't all the 3-combinations: 因此,您有一个集合(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))

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

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

etc ... 等...

For each combination you have 3 set and the union of those set is the original set. 对于每个组合,您有3套,这些套的并集是原始套。 No empty set, no missing element. 没有空集,没有缺少元素。

There must be a way to do that using itertools.combination + collection.Counter but I can't even start somewhere... Can someone help ? 必须使用itertools.combination + collection.Counter来做到这一点,但我什至无法从某处开始……有人可以帮忙吗?

Luke 卢克

EDIT: I would need to capture all the possible combination, including: 编辑:我将需要捕获所有可能的组合,包括:

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

etc ... 等...

something like this? 这样的东西?

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

general solution, for any n and any tuple length: 通用解,对于任何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',))
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM