a way of simulating graphe in python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | class Graph:
def __init__(self,name=""):
self.name = name
self.list_neighbor = {}
self.list_node = {}
def add_node(self,node):
self.list_node[node] = True
def add_edge(self,node,nodebis):
try :
self.list_neighbor[node].append(nodebis)
except :
self.list_neighbor[node] = []
self.list_neighbor[node].append(nodebis)
try :
self.list_neighbor[nodebis].append(node)
except :
self.list_neighbor[nodebis] = []
self.list_neighbor[nodebis].append(node)
def neighbors(self,node):
try :
return self.list_neighbor[node]
except :
return []
def nodes(self):
return self.list_node.keys()
def delete_edge(self,node,nodebis):
self.list_neighbor[node].remove(nodebis)
self.list_neighbor[nodebis].remove(node)
def delete_node(self,node):
del self.list_node[node]
try :
for nodebis in self.list_neighbor[node] :
self.list_neighbor[nodebis].remove(node)
del self.list_neighbor[node]
except :
return "error"
if __name__ == "__main__":
G = Graph("test")
G.add_node(1)
G.add_node(2)
G.add_edge(1,2)
print G.neighbors(1)
|
It is just a way to work and uses graph, for the one who want to test and uses graph.
An alternative pure-Python module. While it is good to learn by doing, you'd likely be better served by the excellent NetworkX Python graph library (https://networkx.lanl.gov/wiki) being developed researchers at the Los Alamos National Labs. You can download it from PyPI here http://pypi.python.org/pypi/networkx/