【问题标题】:Iterate over all disjoint pairs of pairs迭代所有不相交的对
【发布时间】:2014-01-15 14:45:42
【问题描述】:

如何遍历来自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)) ...

【问题讨论】:

标签: python


【解决方案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)

【讨论】:

  • 我会使用if not set(item1) &amp; set(item2) 来避免创建额外的set
  • 谢谢,但是这种方法效率很低,不是吗?我的意思是它创建了很多它不使用的对。
  • @marshall:n 能有多大?
  • 嗯,对于n = 1000,有大约 2490 亿对可以从输入中构建。但是,对于任何给定的配对,大多数其他配对都是有效的组合。例如,对于(0, 1),只有包含01 的对是无效的,所有其他的都可以与(0, 1) 组合得到一个有效的对。因此,尽管算法会跳过那些无效对,但大多数比较的对都是有效的。请注意,item1 &lt; item2 还消除了许多之前已经查看过的对。
  • 对。输出大小应该是 124,251,374,250,所以我想你只浪费了一半的时间。
【解决方案2】:
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]))]

【讨论】:

    猜你喜欢
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2023-02-22
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多