我有一个简单的图,想要创建一个方法“get_edge”,它将两个顶点作为参数,如果存在则返回它们之间的边,否则返回 None。这是我尝试过的一个片段。它不起作用,因为它当前创建一个对象,而不是检查是否已经存在一个对象。编写 get_edge() 的最简单方法是什么?
def add_edge(self, e): """Adds and edge to the graph by adding an entry in both directions. If there is already an edge connecting these Vertices, the new edge replaces it. """ v, w = e self[v][w] = e self[w][v] = e def get_edge(self, v1, v2): try: Edge(v1, v2) print 'Edge exists' except: print 'Edge does not exist' return None