Aan de slagGa gratis aan de slag

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:

Representation of a weighted graph.

Deze oefening maakt deel uit van de cursus

Data Structures and Algorithms in Python

Cursus bekijken

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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([____, ____])
Code bewerken en uitvoeren