MA0301/exercise11/scripts/Kruskal.py

41 lines
864 B
Python
Raw Normal View History

2021-05-03 01:06:04 +02:00
def kruskal(vs, es):
f = []
sets = [set(v) for v in vs]
find_set = lambda v: [x for x in sets if v in x][0]
def merge_sets_that_contains(u, v):
setv = find_set(v)
newsets = [x for x in sets if v not in x]
newsets = [setv.union(x) if u in x else x for x in newsets]
return newsets
sorted_es = [e for e,w in sorted(es, key=lambda e: e[1])]
for (u, v) in sorted_es:
if find_set(u) != find_set(v):
f += [(u, v)]
sets = merge_sets_that_contains(u,v)
return f
if __name__ == '__main__':
vs = [chr(i) for i in range(ord('a'), ord('h') + 1)]
es = [
(('a', 'b'), 1),
(('b', 'c'), 5),
(('c', 'd'), 3),
(('d', 'a'), 7),
(('e', 'f'), 2),
(('f', 'g'), 6),
(('g', 'h'), 8),
(('h', 'e'), 4),
(('b', 'f'), 10),
(('c', 'e'), 9),
(('d', 'h'), 11)
]
print(kruskal(vs,es))