Advertisement
MrPolywhirl

Graph.py

Nov 1st, 2014
384
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.79 KB | None | 0 0
  1. ################################################################################
  2. # DERIVED FROM: http://www.python-course.eu/graphs_python.php
  3. #
  4. # Modified to accept an adjacency matrix.
  5. ################################################################################
  6.  
  7. """ A Python Class
  8. A simple Python graph class, demonstrating the essential
  9. facts and functionalities of graphs.
  10. """
  11.  
  12. class Graph(object):
  13.  
  14.     def __init__(self, matrix_or_dict=[]):
  15.         """ initializes a graph object """
  16.         if isinstance(matrix_or_dict, dict):
  17.             self.__graph_dict = matrix_or_dict
  18.         elif isinstance(matrix_or_dict, list):
  19.             self.__graph_dict = self.__generate_dict(matrix_or_dict)
  20.         else:
  21.             self.__graph_dict = {}
  22.  
  23.     def vertices(self):
  24.         """ returns the vertices of a graph """
  25.         return list(self.__graph_dict.keys())
  26.  
  27.     def edges(self):
  28.         """ returns the edges of a graph """
  29.         return self.__generate_edges()
  30.  
  31.     def add_vertex(self, vertex):
  32.         """ If the vertex "vertex" is not in
  33.            self.__graph_dict, a key "vertex" with an empty
  34.            list as a value is added to the dictionary.
  35.            Otherwise nothing has to be done.
  36.        """
  37.         if vertex not in self.__graph_dict:
  38.             self.__graph_dict[vertex] = []
  39.  
  40.     def add_edge(self, edge):
  41.         """ assumes that edge is of type set, tuple or list;
  42.            between two vertices can be multiple edges!
  43.        """
  44.         edge = set(edge)
  45.         (vertex1, vertex2) = tuple(edge)
  46.         if vertex1 in self.__graph_dict:
  47.             self.__graph_dict[vertex1].append(vertex2)
  48.         else:
  49.             self.__graph_dict[vertex1] = [vertex2]
  50.  
  51.     def __generate_dict(self, matrix):
  52.         _dict = {}
  53.         for i, row in enumerate(matrix):
  54.             _dict[chr(i + 0x61)] = []
  55.             for j, col in enumerate(row):
  56.                 if matrix[i][j] == 1:
  57.                     _dict[chr(i + 0x61)].append(chr(j + 0x61))
  58.         return _dict
  59.  
  60.     def __generate_edges(self):
  61.         """ A static method generating the edges of the
  62.            graph "graph". Edges are represented as sets
  63.            with one (a loop back to the vertex) or two
  64.            vertices
  65.        """
  66.         edges = []
  67.         for vertex in self.__graph_dict:
  68.             for neighbour in self.__graph_dict[vertex]:
  69.                 if {neighbour, vertex} not in edges:
  70.                     edges.append({vertex, neighbour})
  71.         return edges
  72.  
  73.     def __str__(self):
  74.         res = "vertices: "
  75.         for k in self.__graph_dict:
  76.             res += str(k) + " "
  77.         res += "\nedges: "
  78.         for edge in self.__generate_edges():
  79.             res += str(edge) + " "
  80.         return res
  81.  
  82.  
  83. if __name__ == "__main__":
  84.  
  85.     g = { "a" : ["d"],
  86.           "b" : ["c"],
  87.           "c" : ["b", "c", "d", "e"],
  88.           "d" : ["a", "c"],
  89.           "e" : ["c"],
  90.           "f" : []
  91.         }
  92.  
  93.     m = [
  94.         [0, 0, 0, 1, 0, 0],
  95.         [0, 0, 1, 0, 0, 0],
  96.         [0, 1, 1, 1, 1, 0],
  97.         [1, 0, 1, 0, 0, 0],
  98.         [0, 0, 1, 0, 0, 0],
  99.         [0, 0, 0, 0, 0, 0],
  100.     ]
  101.  
  102.     graph = Graph(m)
  103.  
  104.     print("Vertices of graph:")
  105.     print(graph.vertices())
  106.  
  107.     print("Edges of graph:")
  108.     print(graph.edges())
  109.  
  110.     print("Add vertex:")
  111.     graph.add_vertex("z")
  112.  
  113.     print("Vertices of graph:")
  114.     print(graph.vertices())
  115.  
  116.     print("Add an edge:")
  117.     graph.add_edge({"a","z"})
  118.    
  119.     print("Vertices of graph:")
  120.     print(graph.vertices())
  121.  
  122.     print("Edges of graph:")
  123.     print(graph.edges())
  124.  
  125.     print('Adding an edge {"x","y"} with new vertices:')
  126.     graph.add_edge({"x","y"})
  127.     print("Vertices of graph:")
  128.     print(graph.vertices())
  129.     print("Edges of graph:")
  130.     print(graph.edges())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement