How do I delete an edge from a graph in Python
我在读ThinkComplexity的书,我对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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | class Graph(dict): def __init__(self, vs=[], es=[]): """ :param vs: list of vertices/nodes in the graph :param es: list of edges/connection for the nodes :return: Object graph """ for v in vs: self.add_vertex(v) #also node for e in es: self.add_edge(e) #arc/edge/line def add_vertex(self, v): """ :param v: Add the node/vertex to the graph :return: Nothing just add """ self[v] = {} def add_edge(self, e): """ :param e: Add arc/edge/line to the graph here is in both directions as it is undirected graph, if there is a arc already replace it :return: Nothing just add """ v, w = e self[v][w] = e self[w][v] = e def get_edge(self, v1, v2): try: if self != None: if self[v1][v2] == self[v2][v1]: print 'got it' return True except: return None def remove_edge(self, e, e2): try: if self != None: del self[e][e2] del self[e2][e] print 'deleted ', e[0], e[1] return True except: return None def vertices(self): #get the list of nodes nodes = [] for node in self.keys(): nodes.append(node.label) print nodes, ' ' return nodes def edges(self): list_edges = [] count = 0 for node in self: for edges in self[node]: count += 1 print self[node].values(), count list_edges.append(self[node].values()) return list_edges def out_vertices(self, v): #nodes connected to this node connected = [] for node in v.keys(): connected.append(node) print node, 'this node is connected to', v.keys() return connected def out_edges(self, v): list_out_edges = [] for ed in v.values(): print ed, 'edges from to' list_out_edges.append(ed) return list_out_edges class Vertex(object): #nodes fro the graph def __init__(self, label=''): self.label = label def __repr__(self): return 'Vertex/Node(%s)' % repr(self.label) __str__= __repr__ class Edge(tuple): def __new__(cls, e1, e2): return tuple.__new__(cls, (e1, e2)) def __repr__(self): return 'Edge(%s---%s) <-undirected' % (repr(self[0]), repr(self[1])) __str__ = __repr__ |
在第24章。编写一个名为remove_edge的方法,该方法获取一条边并从图形中删除对它的所有引用。
我已经完成了get-edge()代码,但是不删除,我不知道该怎么做,有什么帮助吗??这将是Bayes网络的一个起点,所以我想了解一下Python和图形。谢谢
这样地:
1 2 3 4 5 6 7 8 9 10 11 | def remove_edge(g, e, e2): try: if g != None: del g[e][e2] del g[e2][e] print 'deleted ', e[0], e[1] return True except: return None |
字典中的键可以是对象,而不仅仅是str.并且需要双向执行,因为它是无向的