How to Implement Graph in Python

In this tutorial, we will learn how to program “How to Implement a Graph in Python.” The main objective is to understand and implement basic graph operations using Python. This tutorial will guide you step by step through the process of creating a graph, adding vertices and edges, and performing common graph manipulations and traversals. By the end of this tutorial, you will have a clear understanding of how graphs work and how to implement them effectively in Python, helping you strengthen your problem-solving abilities and improve your overall coding skills.

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 a graph, helping you clearly understand how vertices and edges work together. So, let’s dive into the coding process and start building your graph using 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 Vertex:
  2.     def __init__(self, key):
  3.         self.key = key
  4.         self.points_to = {}
  5.  
  6.     def get_key(self):
  7.         return self.key
  8.  
  9.     def add_neighbour(self, dest, weight=1):
  10.         self.points_to[dest] = weight
  11.  
  12.     def get_neighbours(self):
  13.         return self.points_to.keys()
  14.  
  15.     def get_weight(self, dest):
  16.         return self.points_to[dest]
  17.  
  18.     def does_it_point_to(self, dest):
  19.         return dest in self.points_to
  20.  
  21.  
  22. class Graph:
  23.     def __init__(self):
  24.         self.vertices = {}
  25.  
  26.     def add_vertex(self, key):
  27.         self.vertices[key] = Vertex(key)
  28.  
  29.     def get_vertex(self, key):
  30.         return self.vertices.get(key)
  31.  
  32.     def __contains__(self, key):
  33.         return key in self.vertices
  34.  
  35.     def add_edge(self, src_key, dest_key, weight=1):
  36.         self.vertices[src_key].add_neighbour(
  37.             self.vertices[dest_key], weight
  38.         )
  39.  
  40.     def does_edge_exist(self, src_key, dest_key):
  41.         return self.vertices[src_key].does_it_point_to(
  42.             self.vertices[dest_key]
  43.         )
  44.  
  45.     def __iter__(self):
  46.         return iter(self.vertices.values())
  47.  
  48.  
  49. # ---------------- MAIN PROGRAM ----------------
  50.  
  51. while True:
  52.     print("\n=============== Implement Graph ===============\n")
  53.  
  54.     g = Graph()
  55.  
  56.     print("****** Menu ******")
  57.     print("=> add vertex <key>")
  58.     print("=> add edge <src> <dest> [weight]")
  59.     print("=> display")
  60.     print("=> quit")
  61.  
  62.     while True:
  63.         do = input("\nWhat would you like to do? ").split()
  64.         if not do:
  65.             continue
  66.  
  67.         operation = do[0].lower()
  68.  
  69.         if operation == "add":
  70.             if len(do) < 3:
  71.                 print("Invalid add command.")
  72.                 continue
  73.  
  74.             suboperation = do[1].lower()
  75.  
  76.             if suboperation == "vertex":
  77.                 key = int(do[2])
  78.                 if key in g:
  79.                     print("Vertex already exists.")
  80.                 else:
  81.                     g.add_vertex(key)
  82.                     print("Vertex added.")
  83.  
  84.             elif suboperation == "edge":
  85.                 if len(do) < 4:
  86.                     print("Usage: add edge <src> <dest> [weight]")
  87.                     continue
  88.  
  89.                 src = int(do[2])
  90.                 dest = int(do[3])
  91.                 weight = int(do[4]) if len(do) == 5 else 1
  92.  
  93.                 if src not in g or dest not in g:
  94.                     print("Source or destination vertex does not exist.")
  95.                 elif g.does_edge_exist(src, dest):
  96.                     print("Edge already exists.")
  97.                 else:
  98.                     g.add_edge(src, dest, weight)
  99.                     print("Edge added.")
  100.  
  101.         elif operation == "display":
  102.             print("\nVertices:")
  103.             for v in g:
  104.                 print(v.get_key(), end=" ")
  105.             print("\n\nEdges:")
  106.             for v in g:
  107.                 for dest in v.get_neighbours():
  108.                     print(
  109.                         f"(src={v.get_key()}, dest={dest.get_key()}, "
  110.                         f"weight={v.get_weight(dest)})"
  111.                     )
  112.  
  113.         elif operation == "quit":
  114.             break
  115.  
  116.         else:
  117.             print("Invalid operation.")
  118.  
  119.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  120.     if opt == "no":
  121.         print("Exiting program...")
  122.         break
  123.     elif opt != "yes":
  124.         print("Invalid choice. Exiting program...")
  125.         break

This program demonstrates how to implement a graph data structure in Python using an adjacency-list representation. It defines a `Vertex` class to represent each node in the graph, where each vertex stores its key and a dictionary of neighboring vertices along with optional edge weights. The `Graph` class manages all vertices, allowing users to add vertices, create directed edges with weights, check whether an edge already exists, and iterate through all vertices.

The interactive main program provides a menu-driven interface where users can dynamically build and explore the graph. Users can add vertices, connect them with weighted edges, and display the current structure of the graph. When displaying, the program lists all vertices first, followed by all edges in the format `(source, destination, weight)`. Input validation ensures that duplicate vertices or edges are not added and that edges are only created between existing vertices. The program runs continuously until the user chooses to quit, making it a clear and practical example of basic graph operations and traversal using object-oriented programming.

Output:

There you have it we successfully created How to Implement Graph 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