将序列划分为唯一对的集合

2023-12-10

我需要一个 of 函数,它可以将序列分成对,然后将它们组合起来,以便组合中的所有元素都是唯一的。我已经尝试了多种使用 python 的 itertools 的方法,但还没有找到解决方案。

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

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

[[1, 2], [3, 4]]
[[1, 3], [2, 4]]
[[1, 4], [2, 3]]

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

[1,2,3,4,5,6]

分为以下 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]]

... 等等。

名为 Maple 的 CAS 以该名称实现了此功能设置分区.

编辑:修复了 wks 指出的一个严重的深夜打字错误,并澄清了输出。


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

Result:

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

[EDIT]@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

Result:

((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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将序列划分为唯一对的集合 的相关文章

随机推荐