{
 "metadata": {
  "name": "ch6"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "heading",
     "level": 3,
     "metadata": {},
     "source": "example 6.1 page no : 188"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''\n// Referencing\n// Demonstrates using references\nNote : python does not have reference variable.\n'''\nmyScore = 1000;\nmikesScore = myScore; #create a reference\nprint \"myScore is: \" , myScore\nprint \"mikesScore is: \" , mikesScore \nprint \"Adding 500 to myScore\\n\";\nmyScore += 500;\nprint \"myScore is: \" , myScore\nprint \"mikesScore is: \" , mikesScore\nprint \"Adding 500 to mikesScore\";\nmikesScore += 500;\nprint \"myScore is: \" , myScore \nprint \"mikesScore is: \" , mikesScore",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "myScore is:  1000\nmikesScore is:  1000\nAdding 500 to myScore\n\nmyScore is:  1500\nmikesScore is:  1000\nAdding 500 to mikesScore\nmyScore is:  1500\nmikesScore is:  1500\n"
      }
     ],
     "prompt_number": 1
    },
    {
     "cell_type": "heading",
     "level": 3,
     "metadata": {},
     "source": "example 6.2 page no : 192"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''\n// Swap\n// Demonstrates passing references to alter argument variables\n'''\ndef badSwap(x,y):\n    x,y = y,x\n\ndef goodSwap(x, y):\n    x[0],y[0] = y[0],x[0]\n\nmyScore = [1500];\nyourScore = [1000];\nprint \"Original values\";\nprint \"myScore: \" , myScore[0] \nprint \"yourScore: \" , yourScore[0]\nprint \"Calling badSwap()\\n\";\nbadSwap(myScore[0], yourScore[0]);\nprint \"myScore: \" , myScore[0] \nprint \"yourScore: \" , yourScore[0]\nprint \"Calling goodSwap()\\n\";\ngoodSwap(myScore, yourScore);\nprint \"myScore: \" , myScore[0] \nprint \"yourScore: \" , yourScore[0] ,",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "Original values\nmyScore:  1500\nyourScore:  1000\nCalling badSwap()\n\nmyScore:  1500\nyourScore:  1000\nCalling goodSwap()\n\nmyScore:  1000\nyourScore:  1500\n"
      }
     ],
     "prompt_number": 2
    },
    {
     "cell_type": "heading",
     "level": 3,
     "metadata": {},
     "source": "example 6.3 page no : 196"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''\n// Inventory Displayer\n// Demonstrates constant references\n'''\n\ndef display(vec):\n    print \"Your items:\";\n    for i in vec:\n        print i\n\ninventory = []\ninventory.append(\"sword\");\ninventory.append(\"armor\");\ninventory.append(\"shield\");\ndisplay(inventory);",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "Your items:\nsword\narmor\nshield\n"
      }
     ],
     "prompt_number": 3
    },
    {
     "cell_type": "heading",
     "level": 3,
     "metadata": {},
     "source": "example : 6.4 page no : 199"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''\n// Inventory Referencer\n// Demonstrates returning a reference\n'''\n#returns a reference to a string\n\ndef refToElement(vec,i):\n    return vec[i]\n\ninventory = []\ninventory.append(\"sword\");\ninventory.append(\"armor\");\ninventory.append(\"shield\");\n\n#displays string that the returned reference refers to\nprint \"Sending the returned reference to cout:\"\nprint refToElement(inventory, 0) \n#assigns one reference to another -- inexpensive assignment\nprint \"Assigning the returned reference to another reference.\";\nrStr = refToElement(inventory, 1);\nprint \"Sending the new reference to cout:\";\nprint rStr\n#copies a string object -- expensive assignment\nprint \"Assigning the returned reference to a string object.\";\ns = refToElement(inventory, 2);\nprint \"Sending the new string object to cout:\";\nprint s\n#altering the string object through a returned reference\nprint \"Altering an object through a returned reference.\";\nrStr = \"Healing Potion\";\nprint \"Sending the altered object to cout:\";\nprint inventory[1] ",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "Sending the returned reference to cout:\nsword\nAssigning the returned reference to another reference.\nSending the new reference to cout:\narmor\nAssigning the returned reference to a string object.\nSending the new string object to cout:\nshield\nAltering an object through a returned reference.\nSending the altered object to cout:\narmor\n"
      }
     ],
     "prompt_number": 4
    },
    {
     "cell_type": "heading",
     "level": 3,
     "metadata": {},
     "source": "example 6.5 page no : 205"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''\nTic-Tac-Toe\nPlays the game of tic-tac-toe against a human opponent\n'''\n\n\n# global constants\nX = 'X'\nO = 'O'\nEMPTY = ' ';\nTIE = 'T';\nNO_ONE = 'N';\n\ndef instructions():\n    print \"Welcome to the ultimate man-machine showdown: Tic-Tac-Toe.\";\n    print \"--where human brain is pit against silicon processor\";\n    print \"Make your move known by entering a number, 0 - 8. The number\";\n    print \"corresponds to the desired board position, as illustrated:\";\n    print \"0 | 1 | 2\";\n    print \"---------\";\n    print \"3 | 4 | 5\\n\";   \n    print \"---------\";\n    print \"6 | 7 | 8\\n\\n\";\n    print \"Prepare yourself, human. The battle is about to begin.\";\n\ndef askYesNo(question):\n    response =''\n    while (response != 'y' and response != 'n'):\n        print question , \" (y/n): \",\n        response = raw_input()\n    return response;\n\ndef askNumber( question, high, low):\n    while True:\n        print question , \" (\" , low , \" - \" , high , \"): \",\n        number = int(raw_input())\n        if (number > high or number < low):\n            pass\n        else:\n            break\n    return number;\n\ndef humanPiece():\n    global X,O,EMPTY,TIE,NO_ONE\n    go_first = askYesNo(\"Do you require the first move?\");\n    if (go_first == 'y'):\n        print \"Then take the first move. You will need it.\"\n        return X;\n    else:\n        print \"Your bravery will be your undoing. . . I will go first.\";\n        return O;\n\ndef opponent( piece):\n    global X,O,EMPTY,TIE,NO_ONE\n    if (piece == X):\n        return O;\n    else:\n        return X;\n\ndef displayBoard( board):\n    print \"\\n\\t\" , board[0] , \" | \" , board[1] , \" | \" , board[2];\n    print \"\\t\" , \"---------\";\n    print \"\\t\" , board[3] , \" | \" , board[4] , \" | \" , board[5];\n    print \"\\t\" , \"---------\";\n    print \"\\t\" , board[6] , \" | \" , board[7] , \" | \" , board[8];\n    print \"\\n\";\n\ndef winner(board):\n    global X,O,EMPTY,TIE,NO_ONE\n    # all possible winning rows\n    WINNING_ROWS = [ [0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[0,4,6]]\n    TOTAL_ROWS = 8;\n    # if any winning row has three values that are the same (and not EMPTY),\n    # then we have a winner\n    for row in range(TOTAL_ROWS):\n        if ( (board[WINNING_ROWS[row][0]] != EMPTY) and\n            (board[WINNING_ROWS[row][0]] == board[WINNING_ROWS[row][1]]) and\n            (board[WINNING_ROWS[row][1]] == board[WINNING_ROWS[row][2]]) ):\n            return board[WINNING_ROWS[row][0]];\n    # since nobody has won, check for a tie (no empty squares left)\n    if EMPTY not in board:\n        return TIE;\n    return NO_ONE;\n\ndef isLegal(move,board):\n    global X,O,EMPTY,TIE,NO_ONE\n    return (board[move] == EMPTY);\n\ndef humanMove(board,human):\n    global X,O,EMPTY,TIE,NO_ONE\n    move = askNumber(\"Where will you move?\", len(board),1);\n    '''\n    while (not isLegal(move, board)):\n        print \"\\nThat square is already occupied, foolish human.\\n\";\n        move = askNumber(\"Where will you move?\", len(board),1);\n        print move\n    '''        \n    print \"Fine. . .\\n\";\n    return move;\n\ndef computerMove(board, computer):\n    global X,O,EMPTY,TIE,NO_ONE\n    move = 0;\n    found = False;\n    #if computer can win on next move, that's the move to make\n    while (not found and move < len(board)):\n        if (isLegal(move, board)):\n            board[move] = computer;\n            found = winner(board) == computer;\n            board[move] = EMPTY;\n        if (not found):\n            move += 1\n    #otherwise, if human can win on next move, that's the move to make\n    if (not found):\n        move = 0;\n        human = opponent(computer);\n        while (not found and move < len(board)):\n            if (isLegal(move, board)):\n                board[move] = human;\n                found = winner(board) == human;\n                board[move] = EMPTY;\n            if (not found):\n                move += 1\n    #otherwise, moving to the best open square is the move to make\n    if (not found):\n        move = 0;\n        i = 0;\n        BEST_MOVES = [4, 0, 2, 6, 8, 1, 3, 5, 7] #pick best open square\n        while (not found and i < len(board)):\n            move = BEST_MOVES[i];\n            if (isLegal(move, board)):\n                found = True;\n            i += 1\n    print \"I shall take square number \" , move \n    return move;\n\ndef announceWinner( winner, computer, human):\n    if (winner == computer):\n        print winner , \"'s won!\";\n        print \"As I predicted, human, I am triumphant once more -- proof\";\n        print \"that computers are superior to humans in all regards.\";\n    elif (winner == human):\n        print winner , \"'s won!\";\n        print \"No, no! It cannot be! Somehow you tricked me, human.\";\n        print \"But never again! I, the computer, so swear it!\";\n    else:\n        print \"It's a tie.\\n\";\n        print \"You were most lucky, human, and somehow managed to tie me.\\n\";\n        print \"Celebrate. . . for this is the best you will ever achieve.\\n\";\n\n\nNUM_SQUARES = 9;\nboard = [EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY]\ninstructions();\nhuman = humanPiece();\ncomputer = opponent(human);\nturn = X;\ndisplayBoard(board);\nwhile (winner(board) == NO_ONE):\n    if (turn == human):\n        move = humanMove(board, human);\n        board[move] = human;\n    else:\n        move = computerMove(board, computer);\n        board[move] = computer;\n    displayBoard(board);\n    turn = opponent(turn);\n\nannounceWinner(winner(board), computer, human);\n\n",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "ename": "StdinNotImplementedError",
       "evalue": "raw_input was called, but this frontend does not support stdin.",
       "output_type": "pyerr",
       "traceback": [
        "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mStdinNotImplementedError\u001b[0m                  Traceback (most recent call last)",
        "\u001b[1;32m<ipython-input-5-47d36ba7f5b7>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m    154\u001b[0m \u001b[0mboard\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m[\u001b[0m\u001b[0mEMPTY\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mEMPTY\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mEMPTY\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mEMPTY\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mEMPTY\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mEMPTY\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mEMPTY\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mEMPTY\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mEMPTY\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    155\u001b[0m \u001b[0minstructions\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m;\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 156\u001b[1;33m \u001b[0mhuman\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mhumanPiece\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m;\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    157\u001b[0m \u001b[0mcomputer\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mopponent\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mhuman\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m;\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    158\u001b[0m \u001b[0mturn\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mX\u001b[0m\u001b[1;33m;\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
        "\u001b[1;32m<ipython-input-5-47d36ba7f5b7>\u001b[0m in \u001b[0;36mhumanPiece\u001b[1;34m()\u001b[0m\n\u001b[0;32m     44\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mhumanPiece\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     45\u001b[0m     \u001b[1;32mglobal\u001b[0m \u001b[0mX\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mO\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mEMPTY\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mTIE\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mNO_ONE\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 46\u001b[1;33m     \u001b[0mgo_first\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0maskYesNo\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Do you require the first move?\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m;\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     47\u001b[0m     \u001b[1;32mif\u001b[0m \u001b[1;33m(\u001b[0m\u001b[0mgo_first\u001b[0m \u001b[1;33m==\u001b[0m \u001b[1;34m'y'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     48\u001b[0m         \u001b[1;32mprint\u001b[0m \u001b[1;34m\"Then take the first move. You will need it.\"\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
        "\u001b[1;32m<ipython-input-5-47d36ba7f5b7>\u001b[0m in \u001b[0;36maskYesNo\u001b[1;34m(question)\u001b[0m\n\u001b[0;32m     29\u001b[0m     \u001b[1;32mwhile\u001b[0m \u001b[1;33m(\u001b[0m\u001b[0mresponse\u001b[0m \u001b[1;33m!=\u001b[0m \u001b[1;34m'y'\u001b[0m \u001b[1;32mand\u001b[0m \u001b[0mresponse\u001b[0m \u001b[1;33m!=\u001b[0m \u001b[1;34m'n'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     30\u001b[0m         \u001b[1;32mprint\u001b[0m \u001b[0mquestion\u001b[0m \u001b[1;33m,\u001b[0m \u001b[1;34m\" (y/n): \"\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 31\u001b[1;33m         \u001b[0mresponse\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mraw_input\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     32\u001b[0m     \u001b[1;32mreturn\u001b[0m \u001b[0mresponse\u001b[0m\u001b[1;33m;\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     33\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
        "\u001b[1;32m/home/jay/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/zmq/ipkernel.pyc\u001b[0m in \u001b[0;36m<lambda>\u001b[1;34m(prompt)\u001b[0m\n\u001b[0;32m    343\u001b[0m             \u001b[0mraw_input\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mlambda\u001b[0m \u001b[0mprompt\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m''\u001b[0m\u001b[1;33m:\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_raw_input\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mprompt\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mident\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mparent\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    344\u001b[0m         \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 345\u001b[1;33m             \u001b[0mraw_input\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mlambda\u001b[0m \u001b[0mprompt\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m''\u001b[0m \u001b[1;33m:\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_no_raw_input\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    346\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    347\u001b[0m         \u001b[1;32mif\u001b[0m \u001b[0mpy3compat\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mPY3\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
        "\u001b[1;32m/home/jay/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/zmq/ipkernel.pyc\u001b[0m in \u001b[0;36m_no_raw_input\u001b[1;34m(self)\u001b[0m\n\u001b[0;32m    686\u001b[0m         \"\"\"Raise StdinNotImplentedError if active frontend doesn't support\n\u001b[0;32m    687\u001b[0m         stdin.\"\"\"\n\u001b[1;32m--> 688\u001b[1;33m         raise StdinNotImplementedError(\"raw_input was called, but this \"\n\u001b[0m\u001b[0;32m    689\u001b[0m                                        \"frontend does not support stdin.\") \n\u001b[0;32m    690\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
        "\u001b[1;31mStdinNotImplementedError\u001b[0m: raw_input was called, but this frontend does not support stdin."
       ]
      },
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "Welcome to the ultimate man-machine showdown: Tic-Tac-Toe.\n--where human brain is pit against silicon processor\nMake your move known by entering a number, 0 - 8. The number\ncorresponds to the desired board position, as illustrated:\n0 | 1 | 2\n---------\n3 | 4 | 5\n\n---------\n6 | 7 | 8\n\n\nPrepare yourself, human. The battle is about to begin.\nDo you require the first move?  (y/n): "
      }
     ],
     "prompt_number": 5
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "",
     "language": "python",
     "metadata": {},
     "outputs": []
    }
   ],
   "metadata": {}
  }
 ]
}