def add_edge(self, vertex1, vertex2, cost): exception_message = "" if self.is_edge(vertex1, vertex2): exception_message += "The edge from vertex1 to vertex 2 already exists" if len(exception_message) > 0: raise exceptionGraph(exception_message) self.__dictionaryOut[vertex1].append(vertex2) self.__dictionaryIn[vertex2].append(vertex1) self.__dictionaryCosts[(vertex1, vertex2)] = cost
def remove_vertex(self, vertex): if vertex not in self.parse_keys(): raise exceptionGraph("Vertex doesn't exist") for vertex2 in self.__dictionaryOut[vertex]: self.__dictionaryIn[vertex2].remove(vertex) del self.__dictionaryCosts[(vertex, vertex2)] for vertex2 in self.__dictionaryIn[vertex]: self.__dictionaryOut[vertex2].remove(vertex) del self.__dictionaryCosts[(vertex2, vertex)] del self.__dictionaryOut[vertex] del self.__dictionaryIn[vertex]
def __loadFromFile(self): try: with open(self.__fileName, "r") as file: first_line = file.readline() first_line = first_line.strip().split() vertices, edges = int(first_line[0]), int(first_line[1]) self.__Graph = Graph(vertices) for i in range(edges): line = file.readline() line = line.strip().split() vertex1, vertex2, cost = int(line[0]), int(line[1]), int(line[2]) self.__Graph.add_edge(vertex1, vertex2, cost) print("Graph loaded") except IOError: raise exceptionGraph("Error while reading file")
def add_vertex(self, vertex): if vertex in self.parse_keys(): raise exceptionGraph("This vertex already exists in the graph") self.__dictionaryOut[vertex] = [] self.__dictionaryIn[vertex] = []
def is_edge(self, vertex1, vertex2): try: return vertex2 in self.__dictionaryOut[vertex1] except KeyError: raise exceptionGraph( "No edge between these 2 vertices in the graph")
def parse_in_neighbours(self, vertex): try: return list(self.__dictionaryIn[vertex]) except KeyError: raise exceptionGraph("Inexistent vertex")
def change_edge_cost(self, vertex1, vertex2, cost): if (vertex1, vertex2) in self.__dictionaryCosts: self.__dictionaryCosts[(vertex1, vertex2)] = cost else: raise exceptionGraph("The edge doesn't exist")
def get_in_degree(self, vertex): try: return len(self.__dictionaryIn[vertex]) except KeyError: raise exceptionGraph("The vertex doesn't exist")
def remove_edge(self, vertex1, vertex2): if not self.is_edge(vertex1, vertex2): raise exceptionGraph("This edge doesn't exist") del self.__dictionaryCosts[(vertex1, vertex2)] self.__dictionaryOut[vertex1].remove(vertex2) self.__dictionaryIn[vertex2].remove(vertex1)
def validator_negative_costs(self, matrix): for vertex1 in range(self._vertices): for vertex2 in range(self._vertices): if matrix[vertex1][vertex2] + matrix[vertex2][vertex1] < 0: raise exceptionGraph("It has negative cost cycles!") '''