Union find implementation using Python
问题 So here's what I want to do: I have a list that contains several equivalence relations: l = [[1, 2], [2, 3], [4, 5], [6, 7], [1, 7]] And I want to union the sets that share one element. Here is a sample implementation: def union(lis): lis = [set(e) for e in lis] res = [] while True: for i in range(len(lis)): a = lis[i] if res == []: res.append(a) else: pointer = 0 while pointer < len(res): if a & res[pointer] != set([]) : res[pointer] = res[pointer].union(a) break pointer +=1 if pointer ==