Skip to content

Instantly share code, notes, and snippets.

@hayderimran7
Forked from msAzhar/kruskal.py
Created February 21, 2017 07:17
Show Gist options
  • Save hayderimran7/09960ca438a65a9bd10d0254b792f48f to your computer and use it in GitHub Desktop.
Save hayderimran7/09960ca438a65a9bd10d0254b792f48f to your computer and use it in GitHub Desktop.
Kruskal's Algorithm (Python)
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)
@jcammmmm
Copy link

You probably mispelled line 55, the weight should be 7 in order to keep the sense of the graph...

@yiyu0x
Copy link

yiyu0x commented Apr 7, 2018

maybe line 27,28 not in the for-loop , the code will be more efficiency

@sinkinnn
Copy link

sinkinnn commented Feb 9, 2019

hi, is this code working? had some issues to call function in line 66

@yubber
Copy link

yubber commented Apr 13, 2019

@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.

@LeshenDeaf
Copy link

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