proffreda

simple_graph.py

Apr 6th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.83 KB | None | 0 0
  1. """ A Python Class
  2. A simple Python graph class. https://repl.it/GyUb/0
  3. """
  4.  
  5. class Graph(object):
  6.  
  7. def __init__(self, graph_dict=None):
  8. """ initializes a graph object
  9. If no dictionary or None is given,
  10. an empty dictionary will be used
  11. """
  12. if graph_dict == None:
  13. graph_dict = {}
  14. self.__graph_dict = graph_dict
  15.  
  16. def vertices(self):
  17. """ returns the vertices of a graph """
  18. return list(self.__graph_dict.keys())
  19.  
  20. def edges(self):
  21. """ returns the edges of a graph """
  22. return self.__generate_edges()
  23.  
  24. def add_vertex(self, vertex):
  25. """ If the vertex "vertex" is not in
  26. self.__graph_dict, a key "vertex" with an empty
  27. list as a value is added to the dictionary.
  28. Otherwise nothing has to be done.
  29. """
  30. if vertex not in self.__graph_dict:
  31. self.__graph_dict[vertex] = []
  32.  
  33. def add_edge(self, edge):
  34. """ assumes that edge is of type set, tuple or list;
  35. between two vertices can be multiple edges!
  36. """
  37. edge = set(edge)
  38. (vertex1, vertex2) = tuple(edge)
  39. if vertex1 in self.__graph_dict:
  40. self.__graph_dict[vertex1].append(vertex2)
  41. else:
  42. self.__graph_dict[vertex1] = [vertex2]
  43.  
  44. def __generate_edges(self):
  45. """ A static method generating the edges of the
  46. graph "graph". Edges are represented as sets
  47. with one (a loop back to the vertex) or two
  48. vertices
  49. """
  50. edges = []
  51. for vertex in self.__graph_dict:
  52. for neighbour in self.__graph_dict[vertex]:
  53. if {neighbour, vertex} not in edges:
  54. edges.append({vertex, neighbour})
  55. return edges
  56.  
  57. def __str__(self):
  58. res = "vertices: "
  59. for k in self.__graph_dict:
  60. res += str(k) + " "
  61. res += "\nedges: "
  62. for edge in self.__generate_edges():
  63. res += str(edge) + " "
  64. return res
  65.  
  66.  
  67. if __name__ == "__main__":
  68.  
  69. g = { "a" : ["d"],
  70. "b" : ["c"],
  71. "c" : ["b", "c", "d", "e"],
  72. "d" : ["a", "c"],
  73. "e" : ["c"],
  74. "f" : []
  75. }
  76.  
  77.  
  78. graph = Graph(g)
  79.  
  80. print("Vertices of graph:")
  81. print(graph.vertices())
  82.  
  83. print("Edges of graph:")
  84. print(graph.edges())
  85.  
  86. print("Add vertex:")
  87. graph.add_vertex("z")
  88.  
  89. print("Vertices of graph:")
  90. print(graph.vertices())
  91.  
  92. print("Add an edge:")
  93. graph.add_edge({"a","z"})
  94.  
  95. print("Vertices of graph:")
  96. print(graph.vertices())
  97.  
  98. print("Edges of graph:")
  99. print(graph.edges())
  100.  
  101. print('Adding an edge {"x","y"} with new vertices:')
  102. graph.add_edge({"x","y"})
  103. print("Vertices of graph:")
  104. print(graph.vertices())
  105. print("Edges of graph:")
  106. print(graph.edges())
  107.  
  108.  
  109. def dfs(graph, start):
  110. visited, stack = set(), [start]
  111. while stack:
  112. vertex = stack.pop()
  113. if vertex not in visited:
  114. visited.add(vertex)
  115. stack.extend(set(graph.graphdict[vertex]) - visited)
  116. return visited
  117.  
  118. If you start this module standalone, you will get the following result:
  119. $ python3 graph.py
  120. Vertices of graph:
  121. ['a', 'c', 'b', 'e', 'd', 'f']
  122. Edges of graph:
  123. [{'a', 'd'}, {'c', 'b'}, {'c'}, {'c', 'd'}, {'c', 'e'}]
  124. Add vertex:
  125. Vertices of graph:
  126. ['a', 'c', 'b', 'e', 'd', 'f', 'z']
  127. Add an edge:
  128. Vertices of graph:
  129. ['a', 'c', 'b', 'e', 'd', 'f', 'z']
  130. Edges of graph:
  131. [{'a', 'd'}, {'c', 'b'}, {'c'}, {'c', 'd'}, {'c', 'e'}, {'a', 'z'}]
  132. Adding an edge {"x","y"} with new vertices:
  133. Vertices of graph:
  134. ['a', 'c', 'b', 'e', 'd', 'f', 'y', 'z']
  135. Edges of graph:
  136. [{'a', 'd'}, {'c', 'b'}, {'c'}, {'c', 'd'}, {'c', 'e'}, {'a', 'z'}, {'y', 'x'}]
Advertisement
Add Comment
Please, Sign In to add comment