给定相关数字列表,合并相关列表以创建不相交的集合

jer*_*use 2 python list-comprehension

鉴于:

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

输出:

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

解释:

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

我写了一个糟糕的算法:

Case 1: both numbers in pair are new (never seen before):
    Make a new set with these two numbers
Case 2: one of the number in pair is new, other is already a part of some set:
    Merge the new number in other's set
Case 3: both the numbers belong to some set:
    Union the second set into first. Destroy the second set.
Run Code Online (Sandbox Code Playgroud)

这个算法有没有更Pythonic(奇特)的解决方案?

tob*_*s_k 5

为此,您可以使用Unionfind 算法。首先,我们使用字典从对中创建一棵树:

leaders = collections.defaultdict(lambda: None)
Run Code Online (Sandbox Code Playgroud)

现在我们使用两个函数 -unionfind- 来填充该树:

def find(x):
    l = leaders[x]
    if l is not None:
        l = find(l)
        leaders[x] = l
        return l
    return x

def union(x, y):
    lx, ly = find(x), find(y)
    if lx != ly:
        leaders[lx] = ly
Run Code Online (Sandbox Code Playgroud)

只需迭代所有对并将它们放入树中即可。

for a, b in [(1,2),(3,4),(5,6),(3,7),(5,7)]:
    union(a, b)
Run Code Online (Sandbox Code Playgroud)

然后它看起来像这样:{1: 2, 2: None, 3: 4, 4: 7, 5: 6, 6: 7, 7: None}

在此输入图像描述

最后,我们按各自的“领导者”对数字进行分组,即返回的内容find

groups = collections.defaultdict(set)
for x in leaders:
    groups[find(x)].add(x)
Run Code Online (Sandbox Code Playgroud)

现在groups.values()[set([1, 2]), set([3, 4, 5, 6, 7])]

复杂度应该约为O(nlogn)