classGraph(object): def__init__(self,graph_dict=None): if graph_dict ==None: graph_dict ={} self._graph_dict = graph_dict defedges(self,vertice): return self._graph_dict[vertice]defall_vertices(self): returnset(self._graph_dict.keys()) defall_edges(self):return self.__generate_edges() defadd_vertex(self,vertex): if vertex notin self._graph_dict: self._graph_dict[vertex]= [] defadd_edge(self,edge): edge =set(edge) vertex1, vertex2 =tuple(edge)for x, y in [(vertex1, vertex2), (vertex2, vertex1)]:if x in self._graph_dict: self._graph_dict[x].add(y)else: self._graph_dict[x]= [y] def__generate_edges(self): edges = []for vertex in self._graph_dict:for neighbour in self._graph_dict[vertex]:if{neighbour, vertex}notin edges: edges.append({vertex, neighbour})return edgesdef__iter__(self): self._iter_obj =iter(self._graph_dict)return self._iter_objdef__next__(self):returnnext(self._iter_obj) def__str__(self): res ="vertices: "for k in self._graph_dict: res +=str(k)+" " res +="\nedges: "for edge in self.__generate_edges(): res +=str(edge)+" "return res
我们想玩一下我们的图表。我们从迭代图表开始。迭代意味着迭代顶点。
g ={"a":{"d"},"b":{"c"},"c":{"b","c","d","e"},"d":{"a","c"},"e":{"c"},"f":{}} graph =Graph(g) for vertice in graph:print(f"Edges of vertice {vertice}: ", graph.edges(vertice))
输出:
Edges of vertice a:{'d'} Edges of vertice b:{'c'} Edges of vertice c:{'c','d','b','e'} Edges of vertice d:{'c','a'} Edges of vertice e:{'c'} Edges of vertice f:{}