Skip to main content
 首页 » 编程设计

python之遍历所有不相交的对

2024年11月01日8三少

如何遍历 range(n) 中所有不相交的对?

例如,设置 n = 4。那么你将迭代 should be

[((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)) ... 

请您参考如下方法:

你可以这样做:

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)