Monday, 15 March 2010

How to check if edge exists between two vertices of graph, in Python? -



How to check if edge exists between two vertices of graph, in Python? -

i have simple graph , want create method "get_edge" take 2 vertices arguments , homecoming border between them if exists, , none otherwise. here's snippet of i've tried. doesn't work because creates object instead of checking if there 1 in existence already. what's simplest way write get_edge()?

def add_edge(self, e): """adds , border graph adding entry in both directions. if there border connecting these vertices, new border 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 not exist' homecoming none

i suspect want like:

def get_edge(self, v1, v2): try: e = self[v1][v2] # order shouldn't matter print("edge exists") homecoming e except keyerror: print("edge not exist") homecoming none

i'm assuming class derived dict or has __getitem__ method works , raise keyerror if inquire key doesn't exist. if don't need print statements (that is, they're debugging), can away e variable , homecoming result directly.

python graph

No comments:

Post a Comment