将列表中有相同元素的集合合并(python实现):
问题描述:
假如有一个列表,列表中有许多集合,集合之间可能有重复的元素,设计一个算法,将有相同元素的集合进行合并。代码实现:
list1 = [[1,2], [2,3], [3,4],[8,9]]
intersection_set = list(map(set, list1))
print(intersection_set)
def merge_list(L):
lenth = len(L)
for i in range(1, lenth):
for j in range(i):
if L[i] == {0} or L[j] == {0}:
continue
x = L[i].union(L[j])
y = len(L[i]) + len(L[j])
if len(x) < y:
L[i] = x
L[j] = {0}
return [i for i in L if i != {0}]
alist = [{'a', 'b', 'c', 'f'}, {'e', 'g'}, {1, 2, 3}, {'h', 'g', 'f'}, {5, 6, 7}, {3, 4}]
print(merge_list(alist))
上述算法时间复杂度O(n^2),最终输出结果如下:
[{'b', 'a', 'h', 'c', 'g', 'f', 'e'}, {5, 6, 7}, {1, 2, 3, 4}]