Guest User

Untitled

a guest
Jun 25th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. # собираем граф из массива
  2. def build_graph(arr, fin):
  3. graph = {}
  4. for node in arr:
  5. if not graph.get(node[0]):
  6. graph[node[0]] = {}
  7. graph[node[0]][node[1]] = node[2]
  8. graph[fin] = {}
  9. return graph
  10.  
  11. # первоначальное состояние переменных
  12. # costs - общая стоимость перехода в эту ноду
  13. # parents - сопоставление нод и родителей
  14. def fill_initial_state(graph, start, fin):
  15. costs = {}
  16. parents = {}
  17. for node in graph[start].keys():
  18. costs[node] = graph[start][node]
  19. parents[node] = start
  20. costs[fin] = 0
  21. parents[fin] = None
  22. return (costs, parents)
  23.  
  24. # поиск максимальнойной стоимости для следующего шага
  25. def find_highest_cost(costs, processed):
  26. highest_cost = 0
  27. highest_cost_node = None
  28. for node in costs:
  29. cost = costs[node]
  30. if cost > highest_cost and node not in processed:
  31. highest_cost = cost
  32. highest_cost_node = node
  33. return highest_cost_node
  34.  
  35. # массив нод проделанного пути
  36. def get_path(parents, start, fin):
  37. paths = [fin]
  38. value = parents[fin]
  39.  
  40. while value != start:
  41. paths.append(value)
  42. value = parents[value]
  43. paths.append(start)
  44. return paths[::-1]
  45.  
  46. # Используем алгоритм Дейскры для поиска пути с минимальной стоимостью
  47. def solve(graph, start, fin):
  48. graph = build_graph(data, fin)
  49. processed = []
  50. (costs, parents) = fill_initial_state(graph, start, fin)
  51. node = find_highest_cost(costs, processed)
  52. while node is not None:
  53. cost = costs[node]
  54. neighbors = graph[node]
  55. for n in neighbors.keys():
  56. new_cost = cost + neighbors[n]
  57. if costs[n] < new_cost:
  58. costs[n] = new_cost
  59. parents[n] = node
  60. processed.append(node)
  61. node = find_highest_cost(costs, processed)
  62. path = get_path(parents, start, fin)
  63.  
  64. return (costs[fin] / (len(path) - 1), path)
  65. data = [
  66. [1, 2, 98],
  67. [1, 3, 50],
  68. [1, 4, 20],
  69. [2, 4, 99],
  70. [3, 4, 70]
  71. ]
  72.  
  73. (probability, path) = solve(data, 1, 4)
  74. print("probability: ", probability, " path: ", path)
Add Comment
Please, Sign In to add comment