建立加權圖
在上一支影片中,你學到了如何在 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)
這個練習分成兩個步驟。第一步,你要修改上述程式碼,讓它可以用來建立「加權圖」。為了達成這點,你可以用雜湊表來表示相鄰頂點及其權重。第二步,你將建立下列的加權圖:

本練習屬於課程
Data Structures and Algorithms in Python
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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([____, ____])