Guest User

Untitled

a guest
Dec 14th, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. import operator
  2.  
  3. inf = float("inf")
  4.  
  5. a, b, c, e, f, g, p, q, u, v, w, x, y, z = "abcefgpquvwxyz"
  6.  
  7. g = {
  8. (a, b) : 4,
  9. (a, p) : 2,
  10. (a, x) : 3,
  11.  
  12. (b, c) : 1,
  13. (b, e) : 5,
  14. (b, f) : 1,
  15.  
  16. (c, u) : 6,
  17.  
  18. (e, f) : 7,
  19. (e, w) : 4,
  20.  
  21. (f, b) : 12,
  22. (f, g) : 2,
  23. (f, u) : 2,
  24.  
  25. (g, u) : 1,
  26. (g, w) : 9,
  27.  
  28. (p, b) : 2,
  29. (p, c) : 4,
  30. (p, v) : 8,
  31. (p, x) : 3,
  32.  
  33. (q, z) : 1,
  34.  
  35. (u, w) : 1,
  36. (u, y) : 10,
  37.  
  38. (v, x) : 2,
  39. (v, c) : 6,
  40. (v, z) : 3,
  41.  
  42. (w, q) : 4,
  43. (w, y) : 1,
  44.  
  45. (x, z) : 5,
  46.  
  47. (y, q) : 1,
  48.  
  49. (z, x) : 6,
  50. (z, y) : 3
  51. }
  52.  
  53. for source in (v, p, b, q):
  54. q = set([])
  55.  
  56. for a, b in g:
  57. q.add(a)
  58. q.add(b)
  59.  
  60. nodes = sorted(q)
  61. print(",".join(nodes))
  62.  
  63. dist = dict((n, inf) for n in q)
  64. dist[source] = 0
  65.  
  66. while q:
  67. u, _ = sorted(((n, v) for n, v in dist.items() if n in q), key=operator.itemgetter(1))[0]
  68.  
  69. if dist[u] == inf:
  70. break
  71.  
  72. q.remove(u)
  73.  
  74. for v in (v for s, v in g if u is s):
  75. alt = dist[u] + g[u, v]
  76. if alt < dist[v]:
  77. dist[v] = alt
  78.  
  79. print(",".join(str(dist[n]) for n in nodes))
  80.  
  81. print("")
Add Comment
Please, Sign In to add comment