Advertisement
Guest User

Untitled

a guest
Nov 30th, 2015
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. (a, b, c, d, e, f, g, h, i, j, k, z) = range(12)
  2.  
  3. names = {a : 'a', b : 'b', c : 'c', d : 'd', e : 'e', f : 'f', g : 'g',\
  4. h : 'h', i : 'i', j : 'j', k : 'k', z : 'z'}
  5.  
  6. cities = {'a' : a, 'b' : b, 'c' : c, 'd' : d, 'e' : e, 'f' : f, 'g' : g,\
  7. 'h' : h, 'i' : i, 'j' : j, 'k' : k, 'z' : z}
  8.  
  9. # a, b, c, d, e, f, g, h, i, j, k, z
  10. ways = ((0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0), # a
  11. (2, 0, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0), # b
  12. (3, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 0), # c
  13. (0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0), # d
  14. (0, 3, 1, 0, 0, 4, 2, 0, 0, 0, 0, 0), # e
  15. (0, 0, 0, 1, 4, 0, 0, 3, 2, 0, 0, 0), # f
  16. (0, 0, 2, 0, 2, 0, 0, 0, 0, 1, 0, 0), # g
  17. (0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3), # h
  18. (0, 0, 0, 0, 0, 2, 0, 0, 0, 5, 0, 2), # i
  19. (0, 0, 0, 0, 0, 0, 1, 0, 5, 0, 3, 0), # j
  20. (0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 3), # k
  21. (0, 0, 0, 0, 0, 0, 0, 3, 2, 0, 3, 0)) # z
  22.  
  23. def shortest_path(start, finish):
  24. def neighbors(dists):
  25. return filter(lambda x: dists[x] != 0, range(len(dists)))
  26.  
  27. def cost(path):
  28. if len(path) == 1:
  29. return 0
  30.  
  31. return ways[path[0]][path[1]] + cost(path[1:])
  32.  
  33. def go_wide(paths):
  34. if len(paths) == 0:
  35. return None
  36.  
  37. path = paths[0]
  38. city = path[-1]
  39. if city == finish:
  40. return path
  41.  
  42. children = filter(lambda c: c not in path, neighbors(ways[city]))
  43. next = map(lambda c: path + [c], children)
  44.  
  45. return go_wide(sorted(paths[1:] + next, lambda x, y: cost(x) - cost(y)))
  46.  
  47. return go_wide([[start]])
  48.  
  49. start = cities[raw_input("from ")]
  50. finish = cities[raw_input("to ")]
  51. print map(lambda a: names[a], shortest_path(start, finish))
  52. raw_input()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement