การสร้าง Weighted Graph
ในวิดีโอที่ผ่านมา คุณได้เรียนรู้วิธีการ implement กราฟใน 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)
แบบฝึกหัดนี้แบ่งออกเป็นสองขั้นตอน ขั้นตอนแรก ให้แก้ไขโค้ดนี้เพื่อรองรับการสร้าง weighted graph โดยใช้ hash table แทนเวอร์เทกซ์ที่อยู่ติดกันพร้อมกับน้ำหนักของแต่ละเส้นเชื่อม ขั้นตอนที่สอง ให้สร้าง weighted graph ตามภาพด้านล่าง:

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
โครงสร้างข้อมูลและอัลกอริทึมใน 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([____, ____])