BaşlayınÜcretsiz Başlayın

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.

Bu egzersiz

Data Structures and Algorithms in Python

kursunun bir parçasıdır
Kursu Görüntüle

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

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([____, ____])
Kodu Düzenle ve Çalıştır