CommencerCommencez gratuitement

Construire un graphe pondéré

Dans la dernière vidéo, vous avez appris à implémenter un graphe en 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)

Cet exercice comporte deux étapes. Dans la première, vous allez modifier ce code pour pouvoir créer un graphe pondéré. Pour cela, vous pouvez utiliser une table de hachage pour représenter les sommets adjacents avec leurs poids. Dans la seconde étape, vous construirez le graphe pondéré suivant :

Representation of a weighted graph.

Cet exercice fait partie du cours

<cours>Structures de données et algorithmes en Python</cours>
Voir le cours

Exercice interactif pratique

Essayez cet exercice en complétant ce code d’exemple.

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([____, ____])
Modifier et exécuter le code