我正在寻找一种算法和/或Python代码,以生成将一组n
元素划分为零个或多个r
元素组和余数的所有可能方法。例如,给定一个集合:
[1,2,3,4,5]
n = 5
和r = 2
,我想
((1,2,3,4,5),)
((1,2),(3,4,5))
((1,3),(2,4,5))
...
((1,2),(3,4),(5,))
((1,2),(3,5),(4,))
...
换句话说,从集合中提取0个两组项目的结果,加上从集合中提取1组两个项目的结果,加上从集合中提取2组2的结果,...如果n
更大,则会继续。
生成这些结果的顺序并不重要,也不是每个组中元素的顺序,也不是结果中组的顺序。 (例如((1,3),(2,4,5))
相当于((3,1),(4,5,2))
和((2,5,4),(1,3))
等等。)我正在寻找的是每个不同的结果至少生成一次,最好是恰好一次,尽可能高效。
强力方法是从r
元素中生成n
的所有可能组合,然后创建任意数量的这些组合的所有可能组(powerset),迭代在他们身上,只处理组中的组合没有共同元素的那些。即使是少量元素,它也需要远太长时间(它需要迭代超过2 ^(n!/ r!(nr)!)组,因此复杂性是双指数的。)
基于this question中给出的代码,基本上是r = 2
和n
的特殊情况,我提出了以下内容:
def distinct_combination_groups(iterable, r):
tpl = tuple(iterable)
yield (tpl,)
if len(tpl) > r:
for c in combinations(tpl, r):
for g in distinct_combination_groups(set(tpl) - set(c), r):
yield ((c,) + g)
似乎确实产生了所有可能的结果,但它包含一些重复项,当n
相当大时,它们是非常重要的。所以我希望有一种避免重复的算法。
答案 0 :(得分:6)
这个怎么样?
from itertools import combinations
def partitions(s, r):
"""
Generate partitions of the iterable `s` into subsets of size `r`.
>>> list(partitions(set(range(4)), 2))
[((0, 1), (2, 3)), ((0, 2), (1, 3)), ((0, 3), (1, 2))]
"""
s = set(s)
assert(len(s) % r == 0)
if len(s) == 0:
yield ()
return
first = next(iter(s))
rest = s.difference((first,))
for c in combinations(rest, r - 1):
first_subset = (first,) + c
for p in partitions(rest.difference(c), r):
yield (first_subset,) + p
def partitions_with_remainder(s, r):
"""
Generate partitions of the iterable `s` into subsets of size
`r` plus a remainder.
>>> list(partitions_with_remainder(range(4), 2))
[((0, 1, 2, 3),), ((0, 1), (2, 3)), ((0, 2), (1, 3)), ((0, 3), (1, 2))]
>>> list(partitions_with_remainder(range(3), 2))
[((0, 1, 2),), ((1, 2), (0,)), ((0, 2), (1,)), ((0, 1), (2,))]
"""
s = set(s)
for n in xrange(len(s), -1, -r): # n is size of remainder.
if n == 0:
for p in partitions(s, r):
yield p
elif n != r:
for remainder in combinations(s, n):
for p in partitions(s.difference(remainder), r):
yield p + (remainder,)
OP的例子:
>>> pprint(list(partitions_with_remainder(range(1, 6), 2)))
[((1, 2, 3, 4, 5),),
((4, 5), (1, 2, 3)),
((3, 5), (1, 2, 4)),
((3, 4), (1, 2, 5)),
((2, 5), (1, 3, 4)),
((2, 4), (1, 3, 5)),
((2, 3), (1, 4, 5)),
((1, 5), (2, 3, 4)),
((1, 4), (2, 3, 5)),
((1, 3), (2, 4, 5)),
((1, 2), (3, 4, 5)),
((2, 3), (4, 5), (1,)),
((2, 4), (3, 5), (1,)),
((2, 5), (3, 4), (1,)),
((1, 3), (4, 5), (2,)),
((1, 4), (3, 5), (2,)),
((1, 5), (3, 4), (2,)),
((1, 2), (4, 5), (3,)),
((1, 4), (2, 5), (3,)),
((1, 5), (2, 4), (3,)),
((1, 2), (3, 5), (4,)),
((1, 3), (2, 5), (4,)),
((1, 5), (2, 3), (4,)),
((1, 2), (3, 4), (5,)),
((1, 3), (2, 4), (5,)),
((1, 4), (2, 3), (5,))]