3

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

4

1 回答 1

3

像这样的东西?

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',))
]
于 2013-08-09T20:26:58.697 回答