Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ################################################################################
- # DERIVED FROM: http://www.python-course.eu/graphs_python.php
- #
- # Modified to accept an adjacency matrix.
- ################################################################################
- """ A Python Class
- A simple Python graph class, demonstrating the essential
- facts and functionalities of graphs.
- """
- class Graph(object):
- def __init__(self, matrix_or_dict=[]):
- """ initializes a graph object """
- if isinstance(matrix_or_dict, dict):
- self.__graph_dict = matrix_or_dict
- elif isinstance(matrix_or_dict, list):
- self.__graph_dict = self.__generate_dict(matrix_or_dict)
- else:
- self.__graph_dict = {}
- def vertices(self):
- """ returns the vertices of a graph """
- return list(self.__graph_dict.keys())
- def edges(self):
- """ returns the edges of a graph """
- return self.__generate_edges()
- def add_vertex(self, vertex):
- """ If the vertex "vertex" is not in
- self.__graph_dict, a key "vertex" with an empty
- list as a value is added to the dictionary.
- Otherwise nothing has to be done.
- """
- if vertex not in self.__graph_dict:
- self.__graph_dict[vertex] = []
- def add_edge(self, edge):
- """ assumes that edge is of type set, tuple or list;
- between two vertices can be multiple edges!
- """
- edge = set(edge)
- (vertex1, vertex2) = tuple(edge)
- if vertex1 in self.__graph_dict:
- self.__graph_dict[vertex1].append(vertex2)
- else:
- self.__graph_dict[vertex1] = [vertex2]
- def __generate_dict(self, matrix):
- _dict = {}
- for i, row in enumerate(matrix):
- _dict[chr(i + 0x61)] = []
- for j, col in enumerate(row):
- if matrix[i][j] == 1:
- _dict[chr(i + 0x61)].append(chr(j + 0x61))
- return _dict
- def __generate_edges(self):
- """ A static method generating the edges of the
- graph "graph". Edges are represented as sets
- with one (a loop back to the vertex) or two
- vertices
- """
- edges = []
- for vertex in self.__graph_dict:
- for neighbour in self.__graph_dict[vertex]:
- if {neighbour, vertex} not in edges:
- edges.append({vertex, neighbour})
- return edges
- 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
- if __name__ == "__main__":
- g = { "a" : ["d"],
- "b" : ["c"],
- "c" : ["b", "c", "d", "e"],
- "d" : ["a", "c"],
- "e" : ["c"],
- "f" : []
- }
- m = [
- [0, 0, 0, 1, 0, 0],
- [0, 0, 1, 0, 0, 0],
- [0, 1, 1, 1, 1, 0],
- [1, 0, 1, 0, 0, 0],
- [0, 0, 1, 0, 0, 0],
- [0, 0, 0, 0, 0, 0],
- ]
- graph = Graph(m)
- print("Vertices of graph:")
- print(graph.vertices())
- print("Edges of graph:")
- print(graph.edges())
- print("Add vertex:")
- graph.add_vertex("z")
- print("Vertices of graph:")
- print(graph.vertices())
- print("Add an edge:")
- graph.add_edge({"a","z"})
- print("Vertices of graph:")
- print(graph.vertices())
- print("Edges of graph:")
- print(graph.edges())
- print('Adding an edge {"x","y"} with new vertices:')
- graph.add_edge({"x","y"})
- print("Vertices of graph:")
- print(graph.vertices())
- print("Edges of graph:")
- print(graph.edges())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement