Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. import networkx as nx
  2.  
  3. class City:
  4. def __init__(self, name):
  5. self.name = name
  6.  
  7. def __str__(self):
  8. return self.name
  9.  
  10. def __repr__(self):
  11. return self.name
  12.  
  13. class Route:
  14. def __init__(self, fromCity, toCity, length):
  15. self.fromCity = fromCity
  16. self.toCity = toCity
  17. self.length = length
  18.  
  19. class RoutesManager:
  20.  
  21. def __init__(self):
  22. self.graph = nx.DiGraph()
  23.  
  24. def add_city(self, city):
  25. self.graph.add_node(city)
  26.  
  27. def add_route(self, route):
  28. self.graph.add_edge(route.fromCity, route.toCity, weight = route.length)
  29.  
  30. def shortest_route(self, fromCity, toCity):
  31. return nx.shortest_path(self.graph, fromCity, toCity)
  32.  
  33.  
  34. routesManager = RoutesManager()
  35.  
  36. #Graph: AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7
  37.  
  38. A = City("A")
  39. B = City("B")
  40. C = City("C")
  41. D = City("D")
  42. E = City("E")
  43.  
  44. routesManager.add_route(Route(A, B, 5))
  45. routesManager.add_route(Route(B, C, 4))
  46. routesManager.add_route(Route(C, D, 8))
  47. routesManager.add_route(Route(D, C, 8))
  48. routesManager.add_route(Route(D, E, 6))
  49. routesManager.add_route(Route(A, D, 5))
  50. routesManager.add_route(Route(C, E, 2))
  51. routesManager.add_route(Route(E, B, 3))
  52. routesManager.add_route(Route(A, E, 7))
  53.  
  54. print(routesManager.shortest_route(A, C))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement