优化下列代码from collections import defaultdict class Graph: def __init__(self, vertices): self.V = vertices self.graph = [] def add_edge(self, u, v, w): self.graph.append([u, v, w]) def find(self, parent, i): if parent[i] == i: return i return self.find(parent, parent[i]) def union(self, parent, rank, x, y): xroot = self.find(parent, x) yroot = self.find(parent, y) if rank[xroot] < rank[yroot]: parent[xroot] = yroot elif rank[xroot] > rank[yroot]: parent[yroot] = xroot else: parent[yroot] = xroot rank[xroot] += 1 def kruskal_mst(self): result = [] i = 0 e = 0 self.graph = sorted(self.graph, key=lambda item: item[2]) parent = [] rank = [] for node in range(self.V): parent.append(node) rank.append(0) while e < self.V - 1: u, v, w = self.graph[i] i = i + 1 x = self.find(parent, u) y = self.find(parent, v) if x != y: e = e + 1 result.append([u, v, w]) self.union(parent, rank, x, y) print("Following are the edges in the constructed MST") for u, v, weight in result: print("{0} - {1}: {2}".format(u, v, weight)) g = Graph(5) g.add_edge(0, 1, 10) g.add_edge(0, 2, 6) g.add_edge(0, 3, 5) g.add_edge(1, 3, 15) g.add_edge(2, 3, 4) g.kruskal_mst()
时间: 2024-02-15 09:28:41 浏览: 157
代码优化方式
以下是对代码的优化建议:
1. 将图的边列表存储为 defaultdict(list) 对象,这样可以更方便地添加边和查找边。
2. 将 find 和 union 方法改为静态方法,这样就不需要在类实例化之后再调用。
3. 使用 Python 自带的 zip 函数来遍历边列表,可以使代码更加简洁。
4. 将 print 输出改为返回结果,这样可以使代码更加可复用和灵活。
综上所述,以下是优化后的代码:
```python
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v, w):
self.graph[u].append((v, w))
self.graph[v].append((u, w))
@staticmethod
def find(parent, i):
if parent[i] == i:
return i
return Graph.find(parent, parent[i])
@staticmethod
def union(parent, rank, x, y):
xroot = Graph.find(parent, x)
yroot = Graph.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def kruskal_mst(self):
result = []
i = 0
e = 0
parent = [i for i in range(self.V)]
rank = [0] * self.V
edges = sorted((w, u, v) for u in self.graph for v, w in self.graph[u])
while e < self.V - 1:
w, u, v = edges[i]
i += 1
x = Graph.find(parent, u)
y = Graph.find(parent, v)
if x != y:
e += 1
result.append((u, v, w))
Graph.union(parent, rank, x, y)
return result
```
使用示例:
```python
g = Graph(5)
g.add_edge(0, 1, 10)
g.add_edge(0, 2, 6)
g.add_edge(0, 3, 5)
g.add_edge(1, 3, 15)
g.add_edge(2, 3, 4)
mst = g.kruskal_mst()
print("Following are the edges in the constructed MST")
for u, v, weight in mst:
print("{0} - {1}: {2}".format(u, v, weight))
```
阅读全文