Building a weighted graph
In the last video, you learned how to implement a graph in Python.
class Graph:
def __init__(self):
self.vertices = {}
def add_vertex(self, vertex):
self.vertices[vertex] = []
def add_edge(self, source, target):
self.vertices[source].append(target)
This exercise has two steps. In the first one, you will modify this code so that it can be used to create a weighted graph. To do this, you can use a hash table to represent the adjacent vertices with their weights. In the second step, you will build the following weighted graph:
This exercise is part of the course
Data Structures and Algorithms in Python
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
class WeightedGraph:
def __init__(self):
self.vertices = {}
def add_vertex(self, vertex):
# Set the data for the vertex
self.vertices[____] = []
def add_edge(self, source, target, weight):
# Set the weight
self.vertices[____].append([____, ____])