Advertisement
ZlatniotOdBaba

IDA

May 22nd, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1.  
  2. def best_first_graph_search(problem, f, limit, new_limit):
  3.     """Search the nodes with the lowest f scores first.
  4.    You specify the function f(node) that you want to minimize; for example,
  5. if f is a heuristic estimate to the goal, then we have greedy best
  6. first search; if f is node.depth then we have breadth-first search.
  7.    There is a subtlety: the line "f = memoize(f, 'f')" means that the f
  8. values will be cached on the nodes as they are computed. So after doing
  9. a best first search you can examine the f values of the path returned."""
  10.  
  11.     f = memoize(f, 'f')
  12.  
  13. node = Node(problem.initial)
  14. ifproblem.goal_test(node.state):
  15. return node
  16. frontier = PriorityQueue(min, f)
  17. frontier.append(node)
  18. explored = set()
  19. while frontier:
  20. limits = set()
  21. node = frontier.pop()
  22. ifproblem.goal_test(node.state):
  23. return node
  24. explored.add(node.state)
  25. print(node.state, node.path_cost)
  26. for child in node.expand(problem):
  27. limits.add(child.path_cost)
  28. ifproblem.goal_test(node.state):
  29. return node
  30. ifchild.state not in explored and child not in frontier:
  31. frontier.append(child)
  32. print(child, child.path_cost)
  33.  
  34. elif child in frontier:
  35. incumbent = frontier[child]
  36. if f(child) < f(incumbent):
  37. del frontier[incumbent]
  38. frontier.append(child)
  39. new_limit=min(limits)
  40. if limit <new_limit:
  41. limit = new_limit
  42. new_limit = infinity
  43. best_first_graph_search(problem, f, limit, new_limit)
  44.  
  45.  
  46.  
  47.  
  48. return None
  49.  
  50.  
  51. def idaastar_search(problem, h=None):
  52.     "A* search is best-first graph search with f(n) = g(n)+h(n)."
  53.     h = memoize(h or problem.h, 'h')
  54.     limit = 0
  55.     new_limit = infinity
  56.     return best_first_graph_search(problem, lambda n: n.path_cost + h(n),limit, new_limit)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement