迭代所有不相交的对

时间:2014-01-15 14:45:42

标签: python

如何迭代来自range(n)

的所有脱节对

例如,设置n = 4.然后你将迭代应该是

  

[((0,1),(2,3)),((0,2),(1,3)),((0,3),(1,2))]

如果n=5,那么你将迭代

[((0,1),(2,3)), ((0,1),(2,4)), ((0,1),(3,4)), ((0,2),(1,3)),((0,2),(1,4)), ((0,3),(1,2)),  ((0,3),(1,4)), ((0,4),(1,2)), ((0,4), (1,3)), ((0,4),(2,3)) ...

2 个答案:

答案 0 :(得分:1)

你可以这样做:

import itertools

n = 4
data = range(n)
for item1 in itertools.combinations(data, 2):
    for item2 in itertools.combinations(data, 2):
        if item1 < item2 and not set(item1) & set(item2):
            print item1, item2

这给出了:

(0, 1) (2, 3)
(0, 2) (1, 3)
(0, 3) (1, 2)

答案 1 :(得分:1)

from itertools import combinations
n = 4
disjoints = [x for x in combinations(map(set, combinations(range(n), 2)), 2) 
    if not x[0] & x[1]]

输出:

[(set([0, 1]), set([2, 3])),
 (set([0, 2]), set([1, 3])),
 (set([0, 3]), set([1, 2]))]