Search-4e.ipynb 76,4 ko
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "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",
   "execution_count": 3,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "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,
    "deletable": true,
    "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,
    "collapsed": false,
    "deletable": true,
    "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,
    "deletable": true,
    "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",
   "execution_count": 4,
   "metadata": {
    "button": false,
    "collapsed": true,
    "deletable": 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,
    "deletable": true,
    "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",
   "execution_count": 5,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['A', 'S', 'F', 'B']"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('A', 'B', romania)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['L', 'T', 'A', 'S', 'F', 'B', 'U', 'V', 'I', 'N']"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('L', 'N', romania)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['N', 'I', 'V', 'U', 'B', 'F', 'S', 'A', 'T', 'L']"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('N', 'L', romania)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['E']"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('E', 'E', romania)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "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. I'll make a local copy of the list of 5-letter words from the [Stanford GraphBase](http://www-cs-faculty.stanford.edu/~uno/sgb.html) project (the `!` indicates that these are shell commands, not Python):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "! [ -e sgb-words.txt ] || curl -O http://www-cs-faculty.stanford.edu/~uno/sgb-words.txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "which\r\n",
      "there\r\n",
      "their\r\n",
      "about\r\n",
      "would\r\n",
      "these\r\n",
      "other\r\n",
      "words\r\n",
      "could\r\n",
      "write\r\n"
     ]
    }
   ],
   "source": [
    "! head sgb-words.txt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "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",
   "execution_count": 11,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5757"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "WORDS = set(open('sgb-words.txt').read().split())\n",
    "len(WORDS)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "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",
   "execution_count": 13,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "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",
   "execution_count": 14,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'cello', 'hallo', 'hells', 'hullo', 'jello'}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "neighboring_words('hello')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'would'}"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "neighboring_words('world')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "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",
   "execution_count": 16,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "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,
    "deletable": true,
    "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",
   "execution_count": 17,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['green', 'greed', 'treed', 'trees', 'treys', 'greys', 'grays', 'grass']"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('green', 'grass', word_neighbors)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "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']"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('smart', 'brain', word_neighbors)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['frown',\n",
       " 'flown',\n",
       " 'flows',\n",
       " 'slows',\n",
       " 'stows',\n",
       " 'stoas',\n",
       " 'stoae',\n",
       " 'stole',\n",
       " 'stile',\n",
       " 'smile']"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "breadth_first('frown', 'smile', word_neighbors)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "button": false,
    "deletable": true,
    "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",
   "execution_count": 18,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "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",
   "execution_count": 19,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "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",
   "execution_count": 20,
   "metadata": {
    "button": false,
    "collapsed": true,
    "deletable": 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,
    "deletable": true,
    "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",
   "execution_count": 21,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "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,
    "deletable": true,
    "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",
   "execution_count": 22,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "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",
    "        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",
   "execution_count": 23,
   "metadata": {
    "button": false,
    "collapsed": true,
    "deletable": 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,
    "deletable": true,
    "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",
   "execution_count": 24,
   "metadata": {
    "button": false,
    "collapsed": false,
    "deletable": true,
    "new_sheet": false,
    "run_control": {
     "read_only": false
    }