I have a simple graph and want to create a method “get_edge” that will take two vertices as arguments and return an edge between them if it exists, and None otherwise. Here’s a snippet of what I’ve tried. It doesn’t work because it currently creates an object instead of checking if there is one in existence already. What’s the simplest way to write 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
I suspect you want something like:
I’m assuming your class is derived from
dictor has a__getitem__method that works and will raise aKeyErrorif you ask for a key that doesn’t exist. If you don’t need theprintstatements (that is, they’re just for debugging), you can do away with theevariable and just return the result directly.