问题描述
我正在研究图形,但 Python 在一件事情上无法正常工作。
我正在像这样编写 removeVertex 函数:
def remove_vertex(self,vertex):
cities = self.adjacencyList[vertex] # Cities is an array ["mexico","japan"]
for city in cities:
self.remove_edge(vertex,city)
self.adjacencyList.pop(vertex,None)
return True
基本上是遍历顶点的邻接列表并删除它的所有边,我的图是未加权且无方向的。
这是我的课程完整代码:
class Graph:
def __init__(self):
self.adjacencyList = {}
def add_vertex(self,name):
if name not in self.adjacencyList.keys():
self.adjacencyList[name] = []
return True
else:
return False
def add_edge(self,vertex_a,vertex_b):
self.adjacencyList[vertex_a].append(vertex_b)
self.adjacencyList[vertex_b].append(vertex_a)
def remove_edge(self,vertex_b):
self.adjacencyList[vertex_a].remove(vertex_b)
self.adjacencyList[vertex_b].remove(vertex_a)
return True
def remove_vertex(self,vertex):
cities = self.adjacencyList[vertex]
for city in cities:
self.remove_edge(vertex,None)
return True
这是我的主要代码:
graph = Graph()
graph.add_vertex("mexico")
graph.add_vertex("china")
graph.add_vertex("japon")
graph.add_edge("mexico","china")
graph.add_edge("japon","mexico")
graph.add_edge("japon","china")
graph.remove_vertex("japon") # This is where the error occurs
因此,当我调用最后一个函数时,类方法 remove vertex 仅删除要删除的顶点中的边,并且它具有连接的第一个城市,例如“墨西哥”,但它不会删除第二个或其他城市,因为循环它在 for x in arr 中中断。
def remove_vertex(self,vertex):
cities = self.adjacencyList[vertex] # Cities is an array ["mexico","japan"]
for city in cities:
self.remove_edge(vertex,city)
self.adjacencyList.pop(vertex,None)
return True
我做错了什么?
解决方法
当你遍历这个 for 循环时:
for city in cities:
self.remove_edge(vertex,city)
您在遍历列表时更改列表 cities
。
Python 从 cities
的第一个元素开始。它从 cities
中删除了“墨西哥”。 Python 然后移动到 cities
的下一个元素。它发现没有第二个元素,所以它退出 for 循环 - 即使它没有遍历其他元素。
您想要做的是复制 self.adjacencyList[vertex]
,并遍历该副本:
def remove_vertex(self,vertex):
cities = self.adjacencyList[vertex].copy()
for city in cities:
self.remove_edge(vertex,city)
self.adjacencyList.pop(vertex,None)
print(self.adjacencyList) # prints {'mexico': ['china'],'china': ['mexico']}
return True