search-4e.ipynb 258 ko
Newer Older
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "*Note: This is not yet ready, but shows the direction I'm leaning in for Fourth Edition Search.*\n",
    "\n",
    "# State-Space Search\n",
    "\n",
    "This notebook describes several state-space search algorithms, and how they can be used to solve a variety of problems. We start with a simple algorithm and a simple domain: finding a route from city to city.  Later we will explore other algorithms and domains.\n",
    "\n",
    "## The Route-Finding Domain\n",
    "\n",
    "Like all state-space search problems, in a route-finding problem you will be given:\n",
    "- A start state (for example, `'A'` for the city Arad).\n",
    "- A goal state (for example, `'B'` for the city Bucharest).\n",
    "- Actions that can change state (for example, driving from `'A'` to `'S'`).\n",
    "\n",
    "You will be asked to find:\n",
    "- A path from the start state, through intermediate states, to the goal state.\n",
    "\n",
    "We'll use this map:\n",
    "\n",
    "<img src=\"http://robotics.cs.tamu.edu/dshell/cs625/images/map.jpg\" height=\"366\" width=\"603\">\n",
    "\n",
    "A state-space search problem can be represented by a *graph*, where the vertexes of the graph are the states of the problem (in this case, cities) and the edges of the graph are the actions (in this case, driving along a road).\n",
    "\n",
    "We'll represent a city by its single initial letter. \n",
    "We'll represent the graph of connections as a `dict` that maps each city to a list of the neighboring cities (connected by a road). For now we don't explicitly represent the actions, nor the distances\n",
    "between cities."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "romania = {\n",
    " 'A': ['Z', 'T', 'S'],\n",
    " 'B': ['F', 'P', 'G', 'U'],\n",
    " 'C': ['D', 'R', 'P'],\n",
    " 'D': ['M', 'C'],\n",
    " 'E': ['H'],\n",
    " 'F': ['S', 'B'],\n",
    " 'G': ['B'],\n",
    " 'H': ['U', 'E'],\n",
    " 'I': ['N', 'V'],\n",
    " 'L': ['T', 'M'],\n",
    " 'M': ['L', 'D'],\n",
    " 'N': ['I'],\n",
    " 'O': ['Z', 'S'],\n",
    " 'P': ['R', 'C', 'B'],\n",
    " 'R': ['S', 'C', 'P'],\n",
    " 'S': ['A', 'O', 'F', 'R'],\n",
    " 'T': ['A', 'L'],\n",
    " 'U': ['B', 'V', 'H'],\n",
    " 'V': ['U', 'I'],\n",
    " 'Z': ['O', 'A']}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Suppose we want to get from `A` to `B`. Where can we go from the start state, `A`?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Z', 'T', 'S']"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "romania['A']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We see that from `A` we can get to any of the three cities `['Z', 'T', 'S']`. Which should we choose?  *We don't know.* That's the whole point of *search*: we don't know which immediate action is best, so we'll have to explore, until we find a *path* that leads to the goal. \n",
    "\n",
    "How do we explore? We'll start with a simple algorithm that will get us from `A` to `B`. We'll keep a *frontier*&mdash;a collection of not-yet-explored states&mdash;and expand the frontier outward until it reaches the goal. To be more precise:\n",
    "\n",
    "- Initially, the only state in the frontier is the start state, `'A'`.\n",
    "- Until we reach the goal, or run out of states in the frontier to explore, do the following:\n",
    "  - Remove the first state from the frontier. Call it `s`.\n",
    "  - If `s` is the goal, we're done. Return the path to `s`.\n",
    "  - Otherwise, consider all the neighboring states of `s`. For each one:\n",
    "    - If we have not previously explored the state, add it to the end of the frontier.\n",
    "    - Also keep track of the previous state that led to this new neighboring state; we'll need this to reconstruct the path to the goal, and to keep us from re-visiting previously explored states.\n",
    "    \n",
    "# A Simple Search Algorithm: `breadth_first`\n",
    "    \n",
    "The function `breadth_first` implements this strategy:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "collapsed": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "from collections import deque # Doubly-ended queue: pop from left, append to right.\n",
    "\n",
    "def breadth_first(start, goal, neighbors):\n",
    "    \"Find a shortest sequence of states from start to the goal.\"\n",
    "    frontier = deque([start]) # A queue of states\n",
    "    previous = {start: None}  # start has no previous state; other states will\n",
    "    while frontier:\n",
    "        s = frontier.popleft()\n",
    "        if s == goal:\n",
    "            return path(previous, s)\n",
    "        for s2 in neighbors[s]:\n",
    "            if s2 not in previous:\n",
    "                frontier.append(s2)\n",
    "                previous[s2] = s\n",
    "                \n",
    "def path(previous, s): \n",
    "    \"Return a list of states that lead to state s, according to the previous dict.\"\n",
    "    return [] if (s is None) else path(previous, previous[s]) + [s]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "A couple of things to note: \n",
    "\n",
    "1. We always add new states to the end of the frontier queue. That means that all the states that are adjacent to the start state will come first in the queue, then all the states that are two steps away, then three steps, etc.\n",
    "That's what we mean by *breadth-first* search.\n",
    "2. We recover the path to an `end` state by following the trail of `previous[end]` pointers, all the way back to `start`.\n",
    "The dict `previous` is a map of `{state: previous_state}`. \n",
    "3. When we finally get an `s` that is the goal state, we know we have found a shortest path, because any other state in the queue must correspond to a path that is as long or longer.\n",
    "3. Note that `previous`  contains all the states that are currently in `frontier` as well as all the states that were in `frontier` in the past.\n",
    "4. If no path to the goal is found, then `breadth_first` returns `None`. If a path is found, it returns the sequence of states on the path.\n",
    "\n",
    "Some examples:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['A', 'S', 'F', 'B']"
      ]
     },
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('A', 'B', romania)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['L', 'T', 'A', 'S', 'F', 'B', 'U', 'V', 'I', 'N']"
      ]
     },
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('L', 'N', romania)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['N', 'I', 'V', 'U', 'B', 'F', 'S', 'A', 'T', 'L']"
      ]
     },
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('N', 'L', romania)"
   ]
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['E']"
      ]
     },
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('E', 'E', romania)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Now let's try a different  kind of problem that can be solved with the same search function.\n",
    "\n",
    "## Word Ladders Problem\n",
    "\n",
    "A *word ladder* problem is this: given a start word and a goal word, find the shortest way to transform the start word into the goal word by changing one letter at a time, such that each change results in a word. For example starting with `green` we can reach `grass` in 7 steps:\n",
    "\n",
    "`green` &rarr; `greed` &rarr; `treed` &rarr; `trees` &rarr; `tress` &rarr; `cress` &rarr; `crass` &rarr; `grass`\n",
    "\n",
    "We will need a dictionary of words. We'll use 5-letter words from the [Stanford GraphBase](http://www-cs-faculty.stanford.edu/~uno/sgb.html) project for this purpose. Let's get that file from aimadata."
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "from search import *\n",
    "sgb_words = open_data(\"EN-text/sgb-words.txt\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "We can assign `WORDS` to be the set of all the words in this file:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5757"
      ]
     },
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "WORDS = set(sgb_words.read().split())\n",
    "len(WORDS)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "And define `neighboring_words` to return the set of all words that are a one-letter change away from a given `word`:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def neighboring_words(word):\n",
    "    \"All words that are one letter away from this word.\"\n",
    "    neighbors = {word[:i] + c + word[i+1:]\n",
    "                 for i in range(len(word))\n",
    "                 for c in 'abcdefghijklmnopqrstuvwxyz'\n",
    "                 if c != word[i]}\n",
    "    return neighbors & WORDS"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For example:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'cello', 'hallo', 'hells', 'hullo', 'jello'}"
      ]
     },
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "neighboring_words('hello')"
   ]
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'would'}"
      ]
     },
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "neighboring_words('world')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Now we can create  `word_neighbors` as a dict of `{word: {neighboring_word, ...}}`: "
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "word_neighbors = {word: neighboring_words(word)\n",
    "                  for word in WORDS}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "Now the `breadth_first` function can be used to solve a word ladder problem:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['green', 'greed', 'treed', 'trees', 'treys', 'trays', 'grays', 'grass']"
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('green', 'grass', word_neighbors)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['smart',\n",
       " 'start',\n",
       " 'stars',\n",
       " 'sears',\n",
       " 'bears',\n",
       " 'beans',\n",
       " 'brans',\n",
       " 'brand',\n",
       " 'braid',\n",
       " 'brain']"
      ]
     },
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('smart', 'brain', word_neighbors)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['frown',\n",
       " 'flown',\n",
       " 'flows',\n",
       " 'slows',\n",
       " 'slots',\n",
       " 'slits',\n",
       " 'spits',\n",
       " 'spite',\n",
       " 'smite',\n",
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('frown', 'smile', word_neighbors)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# More General Search Algorithms\n",
    "\n",
    "Now we'll embelish the `breadth_first` algorithm to make a family of search algorithms with more capabilities:\n",
    "\n",
    "1. We distinguish between an *action* and the *result* of an action.\n",
    "3. We allow different measures of the cost of a solution (not just the number of steps in the sequence).\n",
    "4. We search through the state space in an order that is more likely to lead to an optimal solution quickly.\n",
    "\n",
    "Here's how we do these things:\n",
    "\n",
    "1. Instead of having a graph of neighboring states, we instead have an object of type *Problem*. A Problem\n",
    "has one method, `Problem.actions(state)` to return a collection of the actions that are allowed in a state,\n",
    "and another method, `Problem.result(state, action)` that says what happens when you take an action.\n",
    "2. We keep a set, `explored` of states that have already been explored. We also have a class, `Frontier`, that makes it efficient to ask if a state is on the frontier.\n",
    "3. Each action has a cost associated with it (in fact, the cost can vary with both the state and the action).\n",
    "4. The `Frontier` class acts as a priority queue, allowing the \"best\" state to be explored next.\n",
    "We represent a sequence of actions and resulting states as a linked list of `Node` objects.\n",
    "\n",
    "The algorithm `breadth_first_search` is basically the same  as `breadth_first`, but using our new conventions:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def breadth_first_search(problem):\n",
    "    \"Search for goal; paths with least number of steps first.\"\n",
    "    if problem.is_goal(problem.initial): \n",
    "        return Node(problem.initial)\n",
    "    frontier = FrontierQ(Node(problem.initial), LIFO=False)\n",
    "    explored = set()\n",
    "    while frontier:\n",
    "        node = frontier.pop()\n",
    "        explored.add(node.state)\n",
    "        for action in problem.actions(node.state):\n",
    "            child = node.child(problem, action)\n",
    "            if child.state not in explored and child.state not in frontier:\n",
    "                if problem.is_goal(child.state):\n",
    "                    return child\n",
    "                frontier.add(child)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next is `uniform_cost_search`, in which each step can have a different cost, and we still consider first one os the states with minimum cost so far."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def uniform_cost_search(problem, costfn=lambda node: node.path_cost):\n",
    "    frontier = FrontierPQ(Node(problem.initial), costfn)\n",
    "    explored = set()\n",
    "    while frontier:\n",
    "        node = frontier.pop()\n",
    "        if problem.is_goal(node.state):\n",
    "            return node\n",
    "        explored.add(node.state)\n",
    "        for action in problem.actions(node.state):\n",
    "            child = node.child(problem, action)\n",
    "            if child.state not in explored and child not in frontier:\n",
    "                frontier.add(child)\n",
    "            elif child in frontier and frontier.cost[child] < child.path_cost:\n",
    "                frontier.replace(child)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, `astar_search`  in which the cost includes an estimate of the distance to the goal as well as the distance travelled so far."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "collapsed": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "def astar_search(problem, heuristic):\n",
    "    costfn = lambda node: node.path_cost + heuristic(node.state)\n",
    "    return uniform_cost_search(problem, costfn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Search Tree Nodes\n",
    "\n",
    "The solution to a search problem is now a linked list of `Node`s, where each `Node`\n",
    "includes a `state` and the `path_cost` of getting to the state. In addition, for every `Node` except for the first (root) `Node`, there is a previous `Node` (indicating the state that lead to this `Node`) and an `action` (indicating the action taken to get here)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "class Node(object):\n",
    "    \"\"\"A node in a search tree. A search tree is spanning tree over states.\n",
    "    A Node contains a state, the previous node in the tree, the action that\n",
    "    takes us from the previous state to this state, and the path cost to get to \n",
    "    this state. If a state is arrived at by two paths, then there are two nodes \n",
    "    with the same state.\"\"\"\n",
    "\n",
    "    def __init__(self, state, previous=None, action=None, step_cost=1):\n",
    "        \"Create a search tree Node, derived from a previous Node by an action.\"\n",
    "        self.state     = state\n",
    "        self.previous  = previous\n",
    "        self.action    = action\n",
    "        self.path_cost = 0 if previous is None else (previous.path_cost + step_cost)\n",
    "\n",
    "    def __repr__(self): return \"<Node {}: {}>\".format(self.state, self.path_cost)\n",
    "    \n",
    "    def __lt__(self, other): return self.path_cost < other.path_cost\n",
    "    \n",
    "    def child(self, problem, action):\n",
    "        \"The Node you get by taking an action from this Node.\"\n",
    "        result = problem.result(self.state, action)\n",
    "        return Node(result, self, action, \n",
    "                    problem.step_cost(self.state, action, result))    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Frontiers\n",
    "\n",
    "A frontier is a collection of Nodes that acts like both a Queue and a Set. A frontier, `f`, supports these operations:\n",
    "\n",
    "* `f.add(node)`: Add a node to the Frontier.\n",
    "\n",
    "* `f.pop()`: Remove and return the \"best\" node from the frontier.\n",
    "\n",
    "* `f.replace(node)`: add this node and remove a previous node with the same state.\n",
    "\n",
    "* `state in f`: Test if some node in the frontier has arrived at state.\n",
    "\n",
    "* `f[state]`: returns the node corresponding to this state in frontier.\n",
    "\n",
    "* `len(f)`: The number of Nodes in the frontier. When the frontier is empty, `f` is *false*.\n",
    "\n",
    "We provide two kinds of frontiers: One for \"regular\" queues, either first-in-first-out (for breadth-first search) or last-in-first-out (for depth-first search), and one for priority queues, where you can specify what cost function on nodes you are trying to minimize."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "from collections import OrderedDict\n",
    "import heapq\n",
    "\n",
    "class FrontierQ(OrderedDict):\n",
    "    \"A Frontier that supports FIFO or LIFO Queue ordering.\"\n",
    "    \n",
    "    def __init__(self, initial, LIFO=False):\n",
    "        \"\"\"Initialize Frontier with an initial Node.\n",
    "        If LIFO is True, pop from the end first; otherwise from front first.\"\"\"\n",
Rishav1's avatar
Rishav1 a validé
    "        super(FrontierQ, self).__init__()\n",
    "        self.LIFO = LIFO\n",
    "        self.add(initial)\n",
    "    \n",
    "    def add(self, node):\n",
    "        \"Add a node to the frontier.\"\n",
    "        self[node.state] = node\n",
    "        \n",
    "    def pop(self):\n",
    "        \"Remove and return the next Node in the frontier.\"\n",
    "        (state, node) = self.popitem(self.LIFO)\n",
    "        return node\n",
    "    \n",
    "    def replace(self, node):\n",
    "        \"Make this node replace the nold node with the same state.\"\n",
    "        del self[node.state]\n",
    "        self.add(node)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "collapsed": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "class FrontierPQ:\n",
    "    \"A Frontier ordered by a cost function; a Priority Queue.\"\n",
    "    \n",
    "    def __init__(self, initial, costfn=lambda node: node.path_cost):\n",
    "        \"Initialize Frontier with an initial Node, and specify a cost function.\"\n",
    "        self.heap   = []\n",
    "        self.states = {}\n",
    "        self.costfn = costfn\n",
    "        self.add(initial)\n",
    "    \n",
    "    def add(self, node):\n",
    "        \"Add node to the frontier.\"\n",
    "        cost = self.costfn(node)\n",
    "        heapq.heappush(self.heap, (cost, node))\n",
    "        self.states[node.state] = node\n",
    "        \n",
    "    def pop(self):\n",
    "        \"Remove and return the Node with minimum cost.\"\n",
    "        (cost, node) = heapq.heappop(self.heap)\n",
    "        self.states.pop(node.state, None) # remove state\n",
    "        return node\n",
    "    \n",
    "    def replace(self, node):\n",
    "        \"Make this node replace a previous node with the same state.\"\n",
    "        if node.state not in self:\n",
    "            raise ValueError('{} not there to replace'.format(node.state))\n",
    "        for (i, (cost, old_node)) in enumerate(self.heap):\n",
    "            if old_node.state == node.state:\n",
    "                self.heap[i] = (self.costfn(node), node)\n",
    "                heapq._siftdown(self.heap, 0, i)\n",
    "                return\n",
    "\n",
    "    def __contains__(self, state): return state in self.states\n",
    "    \n",
    "    def __len__(self): return len(self.heap)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Search Problems\n",
    "\n",
    "`Problem` is the abstract class for all search problems. You can define your own class of problems as a subclass of `Problem`. You will need to override the `actions` and  `result` method to describe how your problem works. You will also have to either override `is_goal` or pass a collection of goal states to the initialization method.  If actions have different costs, you should override the `step_cost` method. "
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "class Problem(object):\n",
    "    \"\"\"The abstract class for a search problem.\"\"\"\n",
    "\n",
    "    def __init__(self, initial=None, goals=(), **additional_keywords):\n",
    "        \"\"\"Provide an initial state and optional goal states.\n",
    "        A subclass can have additional keyword arguments.\"\"\"\n",
    "        self.initial = initial  # The initial state of the problem.\n",
    "        self.goals = goals      # A collection of possibe goal states.\n",
    "        self.__dict__.update(**additional_keywords)\n",
    "\n",
    "    def actions(self, state):\n",
    "        \"Return a list of actions executable in this state.\"\n",
    "        raise NotImplementedError # Override this!\n",
    "\n",
    "    def result(self, state, action):\n",
    "        \"The state that results from executing this action in this state.\"\n",
    "        raise NotImplementedError # Override this!\n",
    "\n",
    "    def is_goal(self, state):\n",
    "        \"True if the state is a goal.\" \n",
    "        return state in self.goals # Optionally override this!\n",
    "\n",
    "    def step_cost(self, state, action, result=None):\n",
    "        \"The cost of taking this action from this state.\"\n",
    "        return 1 # Override this if actions have different costs        "
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def action_sequence(node):\n",
    "    \"The sequence of actions to get to this node.\"\n",
    "    actions = []\n",
    "    while node.previous:\n",
    "        actions.append(node.action)\n",
    "        node = node.previous\n",
    "    return actions[::-1]\n",
    "\n",
    "def state_sequence(node):\n",
    "    \"The sequence of states to get to this node.\"\n",
    "    states = [node.state]\n",
    "    while node.previous:\n",
    "        node = node.previous\n",
    "        states.append(node.state)\n",
    "    return states[::-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "source": [
    "# Two Location Vacuum World"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "button": false,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },