将序列划分为多组唯一对

Fre*_*kNS 3 python

我需要一个能够将序列拆分成对的函数,然后将它们组合起来,使得组合中的所有元素都是唯一的.我已经尝试了一些使用python的itertools的方法,但还没有找到解决方案.

为了说明我想要一个能够采用这个序列的函数:[1,2,3,4]

并将其分为以下3种组合:

[[1, 2], [3, 4]]
[[1, 3], [2, 4]]
[[1, 4], [2, 3]]
Run Code Online (Sandbox Code Playgroud)

它也适用于较长的序列,但不必处理奇数长度的序列.例如.

[1,2,3,4,5,6]
Run Code Online (Sandbox Code Playgroud)

分为以下15种组合:

[[1, 2], [3, 4], [5, 6]]
[[1, 2], [3, 5], [4, 6]]
[[1, 2], [3, 6], [4, 5]]
[[1, 3], [2, 4], [5, 6]]
[[1, 3], [2, 5], [4, 6]]
[[1, 3], [2, 6], [4, 5]]
[[1, 4], [2, 3], [5, 6]]
[[1, 4], [2, 5], [3, 6]]
[[1, 4], [2, 6], [3, 5]]
[[1, 5], [2, 3], [4, 6]]
[[1, 5], [2, 4], [3, 6]]
[[1, 5], [2, 6], [3, 4]]
[[1, 6], [2, 3], [4, 5]]
[[1, 6], [2, 4], [3, 5]]
[[1, 6], [2, 5], [3, 4]]
Run Code Online (Sandbox Code Playgroud)

... 等等.

名为Maple的CAS具有以setpartition名称实现的此功能.

编辑:修复了由wks指出的一个关键的深夜打字错误,并澄清了输出.

pil*_*her 5

itertools确实是你的朋友:

from itertools import permutations

def group(iterable, n=2):
    return zip(*([iter(iterable)] * n))

for each in permutations([1, 2, 3, 4, 5, 6]):
    print map(list, group(each))
Run Code Online (Sandbox Code Playgroud)

结果:

[[1, 2], [3, 4], [5, 6]]
[[1, 2], [3, 4], [6, 5]]
[[1, 2], [3, 5], [4, 6]]
[[1, 2], [3, 5], [6, 4]]
[[1, 2], [3, 6], [4, 5]]
[[1, 2], [3, 6], [5, 4]]
[[1, 2], [4, 3], [5, 6]]
[[1, 2], [4, 3], [6, 5]]
[[1, 2], [4, 5], [3, 6]]
...
Run Code Online (Sandbox Code Playgroud)

[编辑] @FrederikNS:在您澄清问题并自己找到答案后,这是我的解决方案:

from itertools import combinations

def setpartition(iterable, n=2):
    iterable = list(iterable)
    partitions = combinations(combinations(iterable, r=n), r=len(iterable) / n)
    for partition in partitions:
        seen = set()
        for group in partition:
            if seen.intersection(group):
                break
            seen.update(group)
        else:
            yield partition

for each in setpartition([1, 2, 3, 4]):
    print each
print
for each in setpartition([1, 2, 3, 4, 5, 6]):
    print each
Run Code Online (Sandbox Code Playgroud)

结果:

((1, 2), (3, 4))
((1, 3), (2, 4))
((1, 4), (2, 3))

((1, 2), (3, 4), (5, 6))
((1, 2), (3, 5), (4, 6))
((1, 2), (3, 6), (4, 5))
((1, 3), (2, 4), (5, 6))
((1, 3), (2, 5), (4, 6))
((1, 3), (2, 6), (4, 5))
((1, 4), (2, 3), (5, 6))
((1, 4), (2, 5), (3, 6))
((1, 4), (2, 6), (3, 5))
((1, 5), (2, 3), (4, 6))
((1, 5), (2, 4), (3, 6))
((1, 5), (2, 6), (3, 4))
((1, 6), (2, 3), (4, 5))
((1, 6), (2, 4), (3, 5))
((1, 6), (2, 5), (3, 4))
Run Code Online (Sandbox Code Playgroud)