How to Implement Bellman Ford Algorithm in Python
In this tutorial, we will learn "How to implement the Bellman-Ford Algorithm in Python". The main objective is to understand and implement the algorithm effectively. This guide will walk you step by step through the process, making it easy to follow and apply. By the end of this tutorial, you will have a solid understanding of how the Bellman-Ford 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 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 the Bellman-Ford Algorithm. So, let’s dive into the coding process and start implementing the solution to gain a deeper understanding of Python programming.
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.- class Graph:
- def __init__(self):
- self.vertices = {}
- def add_vertex(self, key):
- vertex = Vertex(key)
- self.vertices[key] = vertex
- def get_vertex(self, key):
- return self.vertices[key]
- def __contains__(self, key):
- return key in self.vertices
- def add_edge(self, src_key, dest_key, weight=1):
- self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
- def does_edge_exist(self, src_key, dest_key):
- return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
- def __len__(self):
- return len(self.vertices)
- def __iter__(self):
- return iter(self.vertices.values())
- class Vertex:
- def __init__(self, key):
- self.key = key
- self.points_to = {}
- def get_key(self):
- return self.key
- def add_neighbour(self, dest, weight):
- self.points_to[dest] = weight
- def get_neighbours(self):
- return self.points_to.keys()
- def get_weight(self, dest):
- return self.points_to[dest]
- def does_it_point_to(self, dest):
- return dest in self.points_to
- def bellman_ford(g, source):
- distance = dict.fromkeys(g, float('inf'))
- distance[source] = 0
- # Relax edges |V|-1 times
- for _ in range(len(g) - 1):
- for v in g:
- for n in v.get_neighbours():
- distance[n] = min(distance[n], distance[v] + v.get_weight(n))
- # Check for negative weight cycles
- for v in g:
- for n in v.get_neighbours():
- if distance[v] + v.get_weight(n) < distance[n]:
- print("Graph contains a negative weight cycle!")
- return None
- return distance
- # MAIN PROGRAM
- g = Graph()
- while True:
- print("\n========= Bellman-Ford Algorithm =========")
- print("Menu")
- print("add vertex <key>")
- print("add edge <src> <dest> <weight>")
- print("bellman-ford <source vertex key>")
- print("display")
- print("quit")
- do = input('What would you like to do? ').split()
- if not do:
- continue
- operation = do[0]
- if operation == 'add':
- suboperation = do[1]
- if suboperation == 'vertex':
- key = int(do[2])
- if key not in g:
- g.add_vertex(key)
- else:
- print('Vertex already exists.')
- elif suboperation == 'edge':
- src = int(do[2])
- dest = int(do[3])
- weight = int(do[4])
- if src not in g:
- print(f'Vertex {src} does not exist.')
- elif dest not in g:
- print(f'Vertex {dest} does not exist.')
- else:
- if not g.does_edge_exist(src, dest):
- g.add_edge(src, dest, weight)
- else:
- print('Edge already exists.')
- elif operation == 'bellman-ford':
- key = int(do[1])
- source = g.get_vertex(key)
- distance = bellman_ford(g, source)
- if distance:
- print(f'Distances from {key}:')
- for v in distance:
- print(f'Distance to {v.get_key()}: {distance[v]}')
- elif operation == 'display':
- print('Vertices:', end=' ')
- for v in g:
- print(v.get_key(), end=' ')
- print()
- print('Edges:')
- for v in g:
- for dest in v.get_neighbours():
- w = v.get_weight(dest)
- print(f'(src={v.get_key()}, dest={dest.get_key()}, weight={w})')
- elif operation == 'quit':
- print("Exiting program...")
- break
- else:
- print("Invalid command.")
- # Try Again Option
- opt = input("\nDo you want to continue? (yes/no): ").strip().lower()
- if opt == "no":
- print("Exiting program...")
- break
- elif opt != "yes":
- print("Invalid choice. Exiting program...")
- break
This Python program provides an interactive implementation of the Bellman-Ford algorithm for finding shortest paths in a weighted graph, including support for negative edge weights. It defines two classes: `Graph`, which manages the overall graph structure and vertices, and `Vertex`, which represents individual vertices and their edges with weights. The `bellman_ford` function calculates the shortest distances from a specified source vertex to all other vertices, repeatedly relaxing edges and checking for negative weight cycles. Through a text-based menu, users can add vertices and edges, display the graph, compute shortest paths from a chosen source, and exit the program. The system validates input to prevent duplicate vertices or edges and provides clear distance outputs for all vertices reachable from the source.
Output:
There you have it we successfully created How to Implement Bellman Ford 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