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:
def get_edge(self, v1, v2):
try:
e = self[v1][v2] # order shouldn't matter
print("edge exists")
return e
except KeyError:
print("edge does not exist")
return None
I'm assuming your class is derived from dict
or has a __getitem__
method that works and will raise a KeyError
if you ask for a key that doesn't exist. If you don't need the print
statements (that is, they're just for debugging), you can do away with the e
variable and just return the result directly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.