Kestable

CS188 searches by pyTony

May 7th, 2014
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. def genericSearch(problem, fringe, h=nullHeuristic):
  2.     """
  3.    Generic Search in search tree
  4.  
  5.    Your search algorithm needs to return a list of actions that reaches
  6.    the goal.  Make sure to implement a graph search algorithm © pyTony
  7.    """
  8.     start = problem.getStartState()
  9.     closed = set()
  10.     fringe.push(((0, 0, start), []))
  11.     while not fringe.isEmpty():
  12.         (costHere, _, state), directions = fringe.pop()
  13.         if problem.isGoalState(state):
  14.             return directions
  15.         if state not in closed:
  16.             closed.add(state)
  17.             for node, direction, cost in problem.getSuccessors(state):
  18.                 fringe.push(((costHere + cost, h(node, problem), node),
  19.                             directions + [direction]))
  20.  
  21.  
  22. def depthFirstSearch(problem):
  23.     """
  24.    Search the deepest nodes in the search tree first
  25.    """
  26.     return genericSearch(problem, util.Stack())
  27.  
  28. def breadthFirstSearch(problem):
  29.     """
  30.    Search the shallowest nodes in the search tree first.
  31.    """
  32.     return genericSearch(problem, util.Queue())
  33.  
  34. def cost(((c, h, n), direction)):
  35.     return c + h
  36.  
  37. def uniformCostSearch(problem):
  38.     """
  39.    Search the node of least total cost first.
  40.    """
  41.     return genericSearch(problem, util.PriorityQueueWithFunction(cost))
  42.  
  43. def aStarSearch(problem, heuristic=nullHeuristic):
  44.     """
  45.    Search the node that has the lowest combined cost and heuristic first.
  46.    """
  47.     return genericSearch(problem, util.PriorityQueueWithFunction(cost), heuristic)
Advertisement
Add Comment
Please, Sign In to add comment