-
-
Save imranity/09960ca438a65a9bd10d0254b792f48f to your computer and use it in GitHub Desktop.
Kruskal's Algorithm (Python)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
parent = dict() | |
rank = dict() | |
def make_set(vertice): | |
parent[vertice] = vertice | |
rank[vertice] = 0 | |
def find(vertice): | |
if parent[vertice] != vertice: | |
parent[vertice] = find(parent[vertice]) | |
return parent[vertice] | |
def union(vertice1, vertice2): | |
root1 = find(vertice1) | |
root2 = find(vertice2) | |
if root1 != root2: | |
if rank[root1] > rank[root2]: | |
parent[root2] = root1 | |
else: | |
parent[root1] = root2 | |
if rank[root1] == rank[root2]: rank[root2] += 1 | |
def kruskal(graph): | |
for vertice in graph['vertices']: | |
make_set(vertice) | |
minimum_spanning_tree = set() | |
edges = list(graph['edges']) | |
edges.sort() | |
#print edges | |
for edge in edges: | |
weight, vertice1, vertice2 = edge | |
if find(vertice1) != find(vertice2): | |
union(vertice1, vertice2) | |
minimum_spanning_tree.add(edge) | |
return sorted(minimum_spanning_tree) | |
graph = { | |
'vertices': ['A', 'B', 'C', 'D', 'E', 'F', 'G'], | |
'edges': set([ | |
(7, 'A', 'B'), | |
(5, 'A', 'D'), | |
(7, 'B', 'A'), | |
(8, 'B', 'C'), | |
(9, 'B', 'D'), | |
(7, 'B', 'E'), | |
(8, 'C', 'B'), | |
(5, 'C', 'E'), | |
(5, 'D', 'A'), | |
(9, 'D', 'B'), | |
(7, 'D', 'E'), | |
(6, 'D', 'F'), | |
(7, 'E', 'B'), | |
(5, 'E', 'C'), | |
(15, 'E', 'D'), | |
(8, 'E', 'F'), | |
(9, 'E', 'G'), | |
(6, 'F', 'D'), | |
(8, 'F', 'E'), | |
(11, 'F', 'G'), | |
(9, 'G', 'E'), | |
(11, 'G', 'F'), | |
]) | |
} | |
print kruskal(graph) |
@sinkinnn this was probably written in python 2, so the print syntax is different. using print(kruskal(graph))
should work. if that wasn't the source of the problem try checking your indentation - mine copied weirdly.
Doesn't work on these tests: https://drive.google.com/file/d/1oFMOIOFNEnwvfYml3MHQr-COiwP0a7Aq/view
Also, code should be a bit optimized
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi, is this code working? had some issues to call function in line 66