class WeightedGraph: def __init__(self): self.vertices = {} def add_vertex(self, vertex): # Set the data

动态 未结 0 81
小小草
小小草 LV1 2023年9月23日 23:40 发表
Here's the completed code: ``` class WeightedGraph: def __init__(self): self.vertices = {} def add_vertex(self, vertex): # Set the data for the vertex self.vertices[vertex] = [] def add_edge(self, source, target, weight): # Set the weight self.vertices[source].append([target, weight]) self.vertices[target].append([source, weight]) ``` In the `WeightedGraph` class, the `__init__()` method initializes the `vertices` attribute to an empty dictionary. The `add_vertex()` method takes a `vertex` parameter and adds it as a key to the `vertices` dictionary with an empty list as its value. The `add_edge()` method takes `source`, `target`, and `weight` parameters and adds an edge between the `source` and `target` vertices with the given `weight`. It does this by appending a list containing the `target` vertex and the `weight` to the list of edges for the `source` vertex in the `vertices` dictionary. It also appends a similar list to the list of edges for the `target` vertex in the `vertices` dictionary, since this is an undirected graph.
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复