Začněte nyníZačněte zdarma

Sestavení váženého grafu

V poslední lekci ses naučil/a, jak implementovat graf v Pythonu.

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)

Tento úkol má dva kroky. V prvním upravíš tento kód tak, aby bylo možné vytvořit vážený graf. K tomu použiješ hash tabulku pro reprezentaci sousedních vrcholů spolu s jejich vahami. Ve druhém kroku sestavíš následující vážený graf:

Representation of a weighted graph.

Toto cvičení je součástí kurzu

Datové struktury a algoritmy v Pythonu

Zobrazit kurz

Interaktivní cvičení na vyzkoušení si v praxi

Vyzkoušejte si toto cvičení dokončením tohoto ukázkového kódu.

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([____, ____])
Upravit a spustit kód