Advertisement
Guest User

Untitled

a guest
Mar 28th, 2017
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.18 KB | None | 0 0
  1. class Graph:
  2. """A directed graph, represented as two maps,
  3. one from each vertex to the set of outbound neighbours,
  4. the other from each vertex to the set of inbound neighbours"""
  5.  
  6.  
  7. def __init__(self, n ):
  8. """Creates a graph with n vertices (numbered from 0 to n-1)
  9. and no edges"""
  10. self._out = {}
  11. self._in = {}
  12. self._cost = {}
  13.  
  14. self._costs2 = Cost()
  15.  
  16. for i in range(n):
  17. self._out[i] = []
  18. self._in[i] = []
  19. # self._cost[i] = [0] #as default
  20.  
  21.  
  22. def parseX(self):
  23. """Returns an iterable containing all the vertices"""
  24. return self._out.keys()
  25.  
  26.  
  27.  
  28. def addEdge(self, x, y, c):
  29. """Adds an edge from x to y.
  30. Precondition: there is no edge from x to y
  31.  
  32. preconditions: y not already among the neighbours os x
  33.  
  34. """
  35. if y in self._out[x] and x in self._in[y]:
  36. return
  37. self._out[x].append(y)
  38. self._in[y].append(x)
  39. self._cost[x].append(c)
  40. self._costs2.addCost(x, y, c)
  41.  
  42.  
  43. def removeEdge(self, x, y):
  44. """
  45. Removes an edge from the graph, having the source vertex x and the destination vertex y
  46. :param x: the source
  47. :param y: destination
  48. :return: the graph will be updated with the new actual state
  49. """
  50. if x in self._out.keys():
  51. for yy in self._out[x]:
  52. if yy == y:
  53. self._out[x].remove(y)
  54. self._in[y].remove(x)
  55.  
  56. return True
  57. return False
  58.  
  59. def existsVertex(self, x):
  60. return x in self._in.keys()
  61.  
  62.  
  63. def removeVertex(self, x):
  64. """
  65. the function removes the vertex indicated by the input parameter
  66. :param x: the vertex to be removed
  67. :return: true if it was removed and false otherwise
  68. """
  69. """
  70. first we will remove x from the outbound edges list
  71. and then proceed to removing x from all the lists where it is included
  72. """
  73.  
  74. self._out[x] = [] #initialize it with empty list
  75. self._out.pop(x)
  76. self._in.pop(x)
  77. ok = 0
  78. for a in self._out.keys():
  79. for b in self._out[a]:
  80. if b == x:
  81. ok = 1
  82. self._out[a].remove(x)
  83. self._costs2.removeCost(a, b)
  84. for b in self._in[a]:
  85. if b == x:
  86. ok = 1
  87. self._in[a].remove(x)
  88. self._costs2.removeCost(a, b)
  89. if ok == 1:
  90. return True
  91. return False
  92.  
  93. def isEdge(self,x,y):
  94. """Returns True if there is an edge from x to y, False otherwise"""
  95. return y in self._out[x]
  96.  
  97. def parseOUT(self,x):
  98. """Returns an iterable containing the outbound neighbours of x"""
  99. return self._out[x]
  100.  
  101. def parseIN(self,y):
  102. """Returns an iterable containing the inbound neighbours of x"""
  103. return self._in[y]
  104.  
  105.  
  106. def printOUT(self):
  107. """
  108. prints vertices which have x as source vertex
  109. """
  110. for x in self._out:
  111. print (str(x)+ "-->"+ str(self._out[x]) +"\n")
  112.  
  113. def printIN(self):
  114. """
  115. prints vertices which have y as destination vertex
  116. """
  117. for y in self._in:
  118. print (str(y)+"<-- "+str(self._in[y])+"\n")
  119.  
  120. def getCostVertexes(self, x, y):
  121. """
  122. :param x: source vertex
  123. :param y: destination vertex
  124. :return: -1 if at least one of the vertexes is not in the dictionaries of the graph, which means that the edge does not exist
  125. and otherwise returns the cost of the edge determined by the two vertexes
  126. """
  127. if x not in self._in.keys() or y not in self._in.keys():
  128. return -1
  129. cost = 0
  130. cost = self._costs2.getCost(x, y)
  131. return cost
  132.  
  133. def getfromfile(fname):
  134. """
  135. in:n-number of vertices
  136. m-number of edges
  137. x-source vertex
  138. y-destination vertex
  139. c-cost
  140. out:created graph with n-verices, m-edges according to x,y,c
  141. """
  142. try:
  143. f=open(fname,"r")
  144.  
  145. except IOError:
  146. raise IOError( "Not enough space")
  147. line = f.readline().strip()
  148. t = line.split(" ")
  149. n = int(t[0])
  150. m = int(t[1])
  151. G = Graph(n)
  152. for i in range(m):
  153. line = f.readline().strip()
  154. t = line.split(" ")
  155. x = int(t[0])
  156. y = int(t[1])
  157. c = int(t[2])
  158. G.addEdge(x,y,c)
  159.  
  160. return G
  161.  
  162.  
  163. class Cost:
  164. def __init__(self):
  165. self._dictionary = {}
  166.  
  167. def addCost(self, x, y, cost):
  168. self._dictionary[(x, y)] = cost
  169.  
  170. def getCost(self, x, y):
  171. if (x, y) in self._dictionary.keys():
  172. return self._dictionary[(x, y)]
  173. return 0
  174.  
  175. def removeCost(self, x, y):
  176. """"
  177. removes the cost corresponging to the tuple (x, y)
  178. returns true if the operation was performed and false otherwise
  179. """
  180. if (x, y) not in self._dictionary.keys():
  181. return False
  182. self._dictionary.pop((x, y), None)
  183.  
  184. def test():
  185. G = getfromfile("graf.txt")
  186. print (G.parseX())
  187. G.printOUT()
  188. print ("\n")
  189. G.printIN()
  190.  
  191. def test2():
  192. G = Graph(5)
  193. print( G._cost)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement