Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. #!/usr/bin/env python
  2. from collections import deque
  3.  
  4. """
  5. Dijkstra's Shorted Path Algorithm
  6.  
  7. 1. Assign every node an initial value (zero for source, infinity for everything else).
  8.  
  9. 2. Create a set for visited and unvisited nodes. Add source to visited set.
  10.  
  11. 3. Use breadth first search to check all nodes adjacent to the source.
  12. Compare current node values to source node + source -> new node edge. Assign
  13. the node the smaller value.
  14.  
  15. 4. Mark the current node as visited and remove it from the unvisited set.
  16.  
  17. 5. Stop if the destination node has been marked visited or when the remaining
  18. unvited nodes are marked infinity.
  19.  
  20. 6. Otherwise select the unvisited node with the smallest assigned distance
  21. and as source and repeat from step 3.
  22. """
  23.  
  24. def search(graph, source, nodeDistances):
  25. nodeDistances[source] = 0
  26. queue = deque([source])
  27. while len(queue) != 0:
  28. n = queue.popleft()
  29. for m in graph[n]:
  30. # Iterate each node connected to n
  31. if m and nodeDistances[m[0]] > nodeDistances[n] + m[1] :
  32. # Compare current m score and update if n + n-m edge is shorter
  33. nodeDistances[m[0]] = nodeDistances[n] + m[1]
  34. # add m to search queue
  35. queue.extend([m[0]])
  36.  
  37. return nodeDistances
  38.  
  39.  
  40. def createGraph(filename):
  41. """ Generate edge list from text file """
  42. file = open(filename, 'r')
  43. # Map each line of test data to a line in the data list:
  44. data = map(lambda x: x.rstrip().split('\t'), file)
  45. # Map data to a dict with index 0 of each line as key and
  46. # the remaining elemts as a list of tuples
  47. data = { int(x[0]): [(int(y.split(',')[0]), int(y.split(',')[1])) for y in x[1:]] for x in data}
  48. return data
  49.  
  50. def createDistanceDict(graph):
  51. """ instantiate nodeDistances dict """
  52. nodeDistances = { x: float("infinity") for x in graph.keys() }
  53. return nodeDistances
  54.  
  55.  
  56. nodeDistances = {
  57. 1: 0,
  58. 2: float("infinity"),
  59. 3: float("infinity"),
  60. 4: float("infinity"),
  61. 5: float("infinity"),
  62. 6: float("infinity"),
  63. 7: float("infinity"),
  64. 8: float("infinity"),
  65. }
  66. graph = {
  67. 1: [(2,1),(8,2)],
  68. 2: [(1,1),(3,1)],
  69. 3: [(2,1),(4,1)],
  70. 4: [(3,1),(5,1)],
  71. 5: [(4,1),(6,1)],
  72. 6: [(5,1),(7,1)],
  73. 7: [(6,1),(8,1)],
  74. 8: [(7,1),(1,2)],
  75. }
  76.  
  77. if __name__ == '__main__':
  78. #graph = createGraph('djikstra_test.txt')
  79. #nodeDistances = createDistanceDict(graph)
  80. print search(graph, 1, nodeDistances)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement