Generate all possible permutations of subsets containing all the element of a set

二次信任 提交于 2020-01-04 08:24:40

问题


Let S(w) be a set of words. 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).

So you have a set (a, b, c, d, e) and you wan't all the 3-combinations:

((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. 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 ?

Luke

EDIT: I would need to capture all the possible combination, including:

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

etc ...


回答1:


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:

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


来源:https://stackoverflow.com/questions/18154860/generate-all-possible-permutations-of-subsets-containing-all-the-element-of-a-se

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!