Guest User

Untitled

a guest
Feb 25th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.38 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from tkinter import *
  4.  
  5.  
  6. class Container(object):
  7. def __init__(self, mode='queue'):
  8. self.__mode = mode
  9. self.__container = []
  10.  
  11. def get(self):
  12. if self.__mode == 'stack':
  13. return self.__container.pop()
  14. if self.__mode == 'priqueue':
  15. self.__container.sort(key=lambda x: (x['f'], x['id']))
  16. return self.__container.pop(0)
  17.  
  18. def put(self, item):
  19. self.__container.append(item)
  20.  
  21. def empty(self):
  22. return len(self.__container) == 0
  23.  
  24. def contains(self, item):
  25. try:
  26. self.__container.index(item)
  27. except ValueError:
  28. return False
  29. return True
  30.  
  31.  
  32. def xfs(graph, start, end, container):
  33. shortest_path = []
  34. visited_nodes = []
  35.  
  36. container.put(start)
  37. while not container.empty():
  38. curr = container.get()
  39.  
  40. curr['visited'] = True
  41. visited_nodes.append(curr['id'])
  42.  
  43. for succs in curr['successors']:
  44. succs_node = graph[succs['id']]
  45. if not succs_node['visited']:
  46. succs_node['back'] = curr['id']
  47.  
  48. if succs_node is end:
  49. visited_nodes.append(succs_node['id'])
  50.  
  51. while succs_node['back'] is not None:
  52. shortest_path.append(succs_node['id'])
  53. succs_node = graph[succs_node['back']]
  54. shortest_path.append(start['id'])
  55. shortest_path.reverse()
  56. return visited_nodes, shortest_path
  57.  
  58. container.put(succs_node)
  59.  
  60. return visited_nodes, shortest_path
  61.  
  62.  
  63. def search(graph, start, end, container, func):
  64. shortest_path = []
  65. visited_nodes = []
  66.  
  67. start['f'] = func(start['g'], start['h'])
  68. container.put(start)
  69.  
  70. while not container.empty():
  71. curr = container.get()
  72.  
  73. visited_nodes.append(curr['id'])
  74. curr['visited'] = True
  75.  
  76. # Reach the goal
  77. if curr is end:
  78. break
  79.  
  80. # Loop over successors of current node
  81. for succs in curr['successors']:
  82. succs_node = graph[succs['id']]
  83. fn = succs_node['f']
  84. fm = func(curr['g'] + succs['w'], succs_node['h'])
  85.  
  86. if succs_node['visited'] and fm >= fn:
  87. continue
  88.  
  89. if fm < fn:
  90. succs_node['g'] = curr['g'] + succs['w']
  91. succs_node['f'] = fm
  92. succs_node['back'] = curr['id']
  93.  
  94. if not container.contains(succs_node):
  95. container.put(succs_node)
  96.  
  97. if curr is end:
  98. while curr['back'] is not None:
  99. shortest_path.append(curr['id'])
  100. curr = graph[curr['back']]
  101. shortest_path.append(start['id'])
  102. shortest_path.reverse()
  103.  
  104. return visited_nodes, shortest_path
  105.  
  106.  
  107. def problem_1(input_file):
  108. graph = {}
  109. with open(input_file, 'r') as f:
  110. num_nodes = int(f.readline())
  111. start_idx, end_idx = f.readline().strip('\r\n').rstrip(' ').split(' ')
  112.  
  113. for i in range(num_nodes):
  114. graph[i] = {
  115. 'id': i,
  116. 'successors': [],
  117. 'visited': False,
  118. 'back': None,
  119. 'f': 1000000009.,
  120. 'g': 0.
  121. }
  122. for j, w in enumerate(f.readline().strip('\r\n').rstrip(' ').split(' ')):
  123. w = float(w)
  124. if w > 0:
  125. graph[i]['successors'].append({
  126. 'id': j,
  127. 'w': w
  128. })
  129.  
  130. for i, v in enumerate(f.readline().strip('\r\n').rstrip(' ').split(' ')):
  131. graph[i]['h'] = float(v)
  132.  
  133. visited, shortest_path = xfs(graph=graph, start=graph[int(start_idx)], end=graph[int(end_idx)],
  134. container=Container('stack'))
  135. # visited, shortest_path = search(graph=graph, start=graph[int(start_idx)], end=graph[int(end_idx)],
  136. # container=Container('priqueue'),
  137. # func=lambda g, h: g + h)
  138. print(visited)
  139. print(shortest_path)
  140.  
  141.  
  142. class GUI(Frame):
  143. def __init__(self, master=None):
  144. super().__init__(master)
  145.  
  146.  
  147. def problem_2():
  148. master = Tk()
  149. window = GUI(master=master)
  150. window.mainloop()
  151. master.destroy()
  152.  
  153.  
  154. def main():
  155. problem_1(input_file='input.txt')
  156. # problem_2()
  157.  
  158.  
  159. if __name__ == '__main__':
  160. main()
Add Comment
Please, Sign In to add comment