【问题标题】:Generate all possible permutations of subsets containing all the element of a set生成包含集合的所有元素的子集的所有可能排列
【发布时间】:2013-08-11 20:49:54
【问题描述】:

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

等等……

【问题讨论】:

  • Here 它说你可以使用长度 r 来指定你想要 r 大小的组合。
  • 是的,但它提供了单个元素的组合。我需要包含我所有元素的集合。
  • 澄清一下:在 Roman Pekar 的解决方案中,最后一个结果是(('e', 'd', 'c'), ('b',), ('a',)),倒数第二个结果是(('e', 'd', 'c'), ('a',), ('b',))。那是你想要的吗?如果是,也许您应该将标题更改为“排列”而不是“组合”。

标签: python combinations subset multiset powerset


【解决方案1】:

这样的?

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

【讨论】:

  • 不错,但还不够。我需要的是一个集合切片器(不是列表切片器),所以切片器不受顺序的影响。我已经编辑了我的问题以使其更清楚。
  • 我能做的就是将你的答案与 squiguy 的答案结合起来。生成所有不同的组合并应用您的切片器...
  • 就是这样!谢谢:)
  • 添加了更通用的解决方案
猜你喜欢
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 2017-12-11
  • 1970-01-01
相关资源
最近更新 更多