Skip to content

Commit

Permalink
Simplified implementation of Minimum spanning tree using Kruskal’s Al…
Browse files Browse the repository at this point in the history
…gorithm
  • Loading branch information
prawn-cake committed Feb 12, 2018
1 parent 85168d6 commit 9a0538c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ Data structures
================
[![Build Status](https://travis-ci.org/prawn-cake/data_structures.svg?branch=master)](https://travis-ci.org/prawn-cake/data_structures)
[![Coverage Status](https://coveralls.io/repos/github/prawn-cake/data_structures/badge.svg?branch=master)](https://coveralls.io/github/prawn-cake/data_structures?branch=master)
![PythonVersions](https://www.dropbox.com/s/ck0nc28ttga2pw9/python-2.7_3.4-blue.svg?dl=1)

This is a pet project implementing different common and specific data structures in pure python.

Expand All @@ -28,6 +27,7 @@ my implementation is a good start to customize it for your needs.
* [BK-Tree](https://en.wikipedia.org/wiki/BK-tree)
* [Prefix tree](https://en.wikipedia.org/wiki/Trie)
* [Disjoint set](https://en.wikipedia.org/wiki/Disjoint-set_data_structure)
* [Minimum spannin tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree)

## Links

Expand Down
32 changes: 32 additions & 0 deletions structures/mst.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# -*- coding: utf-8 -*-
"""Minimum spanning tree using Kruskal’s Algorithm"""

from structures.disjoint_set import DSet


if __name__ == '__main__':
# Format: (node P, node Q, distance)
# https://he-s3.s3.amazonaws.com/media/uploads/6322896.jpg
g = [
('A', 'B', 1),
('A', 'C', 7),

('B', 'C', 5),
('B', 'D', 4),
('B', 'E', 3),

('C', 'E', 6),
('D', 'E', 2),
]

dset = DSet(['A', 'B', 'C', 'D', 'E'])
mst = []
for p, q, distance in sorted(g, key=lambda item: item[2]):
print('--> %s' % ([p, q, distance]))
if dset.connected(p, q):
print('Cycle detected')
continue
dset.union(p, q)
mst.append((p, q, distance))

assert mst == [('A', 'B', 1), ('D', 'E', 2), ('B', 'E', 3), ('B', 'C', 5)]

1 comment on commit 9a0538c

@prawn-cake
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Solves #2

Please sign in to comment.