IniziaInizia gratis

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.

Questo esercizio fa parte del corso

Data Structures and Algorithms in Python

Visualizza il corso

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

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([____, ____])
Modifica ed esegui il codice