How to Find Minimum Spanning Tree Using Prim’s Algorithm in Python

In this tutorial, we will learn how to program “How to Find a Minimum Spanning Tree Using Prim’s Algorithm in Python.” The main objective is to understand how to find a minimum spanning tree using Prim’s Algorithm. This tutorial will guide you step by step through the process of finding a minimum spanning tree. By the end of this tutorial, you will have a solid understanding of how Prim’s Algorithm works in Python, helping you strengthen your problem-solving abilities and improve your overall coding skills in data structure implementation.

This topic is straightforward and easy to understand. By simply following the instructions provided, you will be able to complete it with ease. The program will guide you step by step through the process of implementing Prim’s Algorithm to find a Minimum Spanning Tree. So, let’s dive into the coding process and start implementing the solution to gain a deeper understanding of graph algorithms in Python.

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. class Graph:
  2.     def __init__(self):
  3.         self.vertices = {}
  4.  
  5.     def add_vertex(self, key):
  6.         vertex = Vertex(key)
  7.         self.vertices[key] = vertex
  8.  
  9.     def get_vertex(self, key):
  10.         return self.vertices[key]
  11.  
  12.     def __contains__(self, key):
  13.         return key in self.vertices
  14.  
  15.     def add_edge(self, src_key, dest_key, weight=1):
  16.         self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
  17.  
  18.     def does_edge_exist(self, src_key, dest_key):
  19.         return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
  20.  
  21.     def display(self):
  22.         print('Vertices:', end=' ')
  23.         for v in self:
  24.             print(v.get_key(), end=' ')
  25.         print()
  26.  
  27.         print('Edges:')
  28.         for v in self:
  29.             for dest in v.get_neighbours():
  30.                 w = v.get_weight(dest)
  31.                 print(f'(src={v.get_key()}, dest={dest.get_key()}, weight={w})')
  32.  
  33.     def __len__(self):
  34.         return len(self.vertices)
  35.  
  36.     def __iter__(self):
  37.         return iter(self.vertices.values())
  38.  
  39.  
  40. class Vertex:
  41.     def __init__(self, key):
  42.         self.key = key
  43.         self.points_to = {}
  44.  
  45.     def get_key(self):
  46.         return self.key
  47.  
  48.     def add_neighbour(self, dest, weight):
  49.         self.points_to[dest] = weight
  50.  
  51.     def get_neighbours(self):
  52.         return self.points_to.keys()
  53.  
  54.     def get_weight(self, dest):
  55.         return self.points_to[dest]
  56.  
  57.     def does_it_point_to(self, dest):
  58.         return dest in self.points_to
  59.  
  60.  
  61. def mst_prim(g):
  62.  
  63.     mst = Graph()
  64.  
  65.     if not g:
  66.         return mst
  67.  
  68.     nearest_neighbour = {}
  69.     smallest_distance = {}
  70.     unvisited = set(g)
  71.  
  72.     u = next(iter(g))
  73.     mst.add_vertex(u.get_key())
  74.     unvisited.remove(u)
  75.  
  76.     for n in u.get_neighbours():
  77.         if n is u:
  78.             continue
  79.         nearest_neighbour[n] = mst.get_vertex(u.get_key())
  80.         smallest_distance[n] = u.get_weight(n)
  81.  
  82.     while smallest_distance:
  83.  
  84.         outside_mst = min(smallest_distance, key=smallest_distance.get)
  85.         inside_mst = nearest_neighbour[outside_mst]
  86.  
  87.         mst.add_vertex(outside_mst.get_key())
  88.  
  89.         mst.add_edge(outside_mst.get_key(), inside_mst.get_key(),
  90.                      smallest_distance[outside_mst])
  91.         mst.add_edge(inside_mst.get_key(), outside_mst.get_key(),
  92.                      smallest_distance[outside_mst])
  93.  
  94.         unvisited.remove(outside_mst)
  95.  
  96.         del smallest_distance[outside_mst]
  97.         del nearest_neighbour[outside_mst]
  98.  
  99.         for n in outside_mst.get_neighbours():
  100.  
  101.             if n in unvisited:
  102.  
  103.                 if n not in smallest_distance:
  104.                     smallest_distance[n] = outside_mst.get_weight(n)
  105.                     nearest_neighbour[n] = mst.get_vertex(outside_mst.get_key())
  106.  
  107.                 else:
  108.                     if smallest_distance[n] > outside_mst.get_weight(n):
  109.                         smallest_distance[n] = outside_mst.get_weight(n)
  110.                         nearest_neighbour[n] = mst.get_vertex(outside_mst.get_key())
  111.  
  112.     return mst
  113.  
  114.  
  115. # MAIN PROGRAM
  116. while True:
  117.  
  118.     print("\n============= Find Minimum Spanning Tree Using Prim’s Algorithm =============\n")
  119.  
  120.     g = Graph()
  121.  
  122.     print("Undirected Graph")
  123.     print("Menu")
  124.     print("add vertex <key>")
  125.     print("add edge <src> <dest> <weight>")
  126.     print("mst")
  127.     print("display")
  128.     print("quit")
  129.  
  130.     while True:
  131.  
  132.         do = input("\nWhat would you like to do? ").split()
  133.  
  134.         if len(do) == 0:
  135.             continue
  136.  
  137.         operation = do[0]
  138.  
  139.         if operation == "add":
  140.  
  141.             suboperation = do[1]
  142.  
  143.             if suboperation == "vertex":
  144.  
  145.                 key = int(do[2])
  146.  
  147.                 if key not in g:
  148.                     g.add_vertex(key)
  149.                 else:
  150.                     print("Vertex already exists.")
  151.  
  152.             elif suboperation == "edge":
  153.  
  154.                 src = int(do[2])
  155.                 dest = int(do[3])
  156.                 weight = int(do[4])
  157.  
  158.                 if src not in g:
  159.                     print(f"Vertex {src} does not exist.")
  160.                 elif dest not in g:
  161.                     print(f"Vertex {dest} does not exist.")
  162.                 else:
  163.  
  164.                     if not g.does_edge_exist(src, dest):
  165.  
  166.                         g.add_edge(src, dest, weight)
  167.                         g.add_edge(dest, src, weight)
  168.  
  169.                     else:
  170.                         print("Edge already exists.")
  171.  
  172.         elif operation == "mst":
  173.  
  174.             mst = mst_prim(g)
  175.  
  176.             print("\nMinimum Spanning Tree:")
  177.             mst.display()
  178.             print()
  179.  
  180.         elif operation == "display":
  181.  
  182.             g.display()
  183.             print()
  184.  
  185.         elif operation == "quit":
  186.             break
  187.  
  188.         else:
  189.             print("Invalid command.")
  190.  
  191.     # Try Again Option
  192.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  193.  
  194.     if opt == "no":
  195.         print("Exiting program...")
  196.         break
  197.     elif opt != "yes":
  198.         print("Invalid choice. Exiting program...")
  199.         break
This Python program implements an undirected weighted graph using `Graph` and `Vertex` classes. Users can add vertices and edges, display the graph, and compute the Minimum Spanning Tree (MST) using Prim’s algorithm, which builds the MST by repeatedly connecting the nearest unvisited vertex with the smallest edge weight. The program features an interactive console menu with input validation, allowing users to manage the graph and view the MST efficiently.

Output:

There you have it we successfully created How to Find Minimum Spanning Tree Using Prim’s Algorithm in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials