example 6.1 page no : 188

In [1]:
#Note : python does not have reference variable.

myScore = 1000;
mikesScore = myScore; #create a reference
print "myScore is: " , myScore
print "mikesScore is: " , mikesScore 
print "Adding 500 to myScore\n";
myScore += 500;
print "myScore is: " , myScore
print "mikesScore is: " , mikesScore
print "Adding 500 to mikesScore";
mikesScore += 500;
print "myScore is: " , myScore 
print "mikesScore is: " , mikesScore
myScore is:  1000
mikesScore is:  1000
Adding 500 to myScore

myScore is:  1500
mikesScore is:  1000
Adding 500 to mikesScore
myScore is:  1500
mikesScore is:  1500

example 6.2 page no : 192

In [2]:
def badSwap(x,y):
    x,y = y,x

def goodSwap(x, y):
    x[0],y[0] = y[0],x[0]

myScore = [1500];
yourScore = [1000];
print "Original values";
print "myScore: " , myScore[0] 
print "yourScore: " , yourScore[0]
print "Calling badSwap()\n";
badSwap(myScore[0], yourScore[0]);
print "myScore: " , myScore[0] 
print "yourScore: " , yourScore[0]
print "Calling goodSwap()\n";
goodSwap(myScore, yourScore);
print "myScore: " , myScore[0] 
print "yourScore: " , yourScore[0] ,
Original values
myScore:  1500
yourScore:  1000
Calling badSwap()

myScore:  1500
yourScore:  1000
Calling goodSwap()

myScore:  1000
yourScore:  1500

example 6.3 page no : 196

In [3]:
def display(vec):
    print "Your items:";
    for i in vec:
        print i

inventory = []
inventory.append("sword");
inventory.append("armor");
inventory.append("shield");
display(inventory);
Your items:
sword
armor
shield

example : 6.4 page no : 199

In [4]:
#returns a reference to a string

def refToElement(vec,i):
    return vec[i]

inventory = []
inventory.append("sword");
inventory.append("armor");
inventory.append("shield");

#displays string that the returned reference refers to
print "Sending the returned reference to cout:"
print refToElement(inventory, 0) 
#assigns one reference to another -- inexpensive assignment
print "Assigning the returned reference to another reference.";
rStr = refToElement(inventory, 1);
print "Sending the new reference to cout:";
print rStr
#copies a string object -- expensive assignment
print "Assigning the returned reference to a string object.";
s = refToElement(inventory, 2);
print "Sending the new string object to cout:";
print s
#altering the string object through a returned reference
print "Altering an object through a returned reference.";
rStr = "Healing Potion";
print "Sending the altered object to cout:";
print inventory[1] 
Sending the returned reference to cout:
sword
Assigning the returned reference to another reference.
Sending the new reference to cout:
armor
Assigning the returned reference to a string object.
Sending the new string object to cout:
shield
Altering an object through a returned reference.
Sending the altered object to cout:
armor

example 6.5 page no : 205

In [2]:
# global constants
X = 'X'
O = 'O'
EMPTY = ' ';
TIE = 'T';
NO_ONE = 'N';

def instructions():
    print "Welcome to the ultimate man-machine showdown: Tic-Tac-Toe.";
    print "--where human brain is pit against silicon processor";
    print "Make your move known by entering a number, 0 - 8. The number";
    print "corresponds to the desired board position, as illustrated:";
    print "0 | 1 | 2";
    print "---------";
    print "3 | 4 | 5\n";   
    print "---------";
    print "6 | 7 | 8\n\n";
    print "Prepare yourself, human. The battle is about to begin.";

def askYesNo(question):
    response =''
    while (response != 'y' and response != 'n'):
        print question , " (y/n): ",
        response = raw_input()
    return response;

def askNumber( question, high, low):
    while True:
        print question , " (" , low , " - " , high , "): ",
        number = int(raw_input())
        if (number > high or number < low):
            pass
        else:
            break
    return number;

def humanPiece():
    global X,O,EMPTY,TIE,NO_ONE
    go_first = askYesNo("Do you require the first move?");
    if (go_first == 'y'):
        print "Then take the first move. You will need it."
        return X;
    else:
        print "Your bravery will be your undoing. . . I will go first.";
        return O;

def opponent( piece):
    global X,O,EMPTY,TIE,NO_ONE
    if (piece == X):
        return O;
    else:
        return X;

def displayBoard( board):
    print "\n\t" , board[0] , " | " , board[1] , " | " , board[2];
    print "\t" , "---------";
    print "\t" , board[3] , " | " , board[4] , " | " , board[5];
    print "\t" , "---------";
    print "\t" , board[6] , " | " , board[7] , " | " , board[8];
    print "\n";

def winner(board):
    global X,O,EMPTY,TIE,NO_ONE
    # all possible winning rows
    WINNING_ROWS = [ [0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
    TOTAL_ROWS = 8;
    # if any winning row has three values that are the same (and not EMPTY),
    # then we have a winner
    for row in range (TOTAL_ROWS):
        if ( (board[WINNING_ROWS[row][0]] != EMPTY) and
            (board[WINNING_ROWS[row][0]] == board[WINNING_ROWS[row][1]]) and
            (board[WINNING_ROWS[row][1]] == board[WINNING_ROWS[row][2]]) ):
            return board[WINNING_ROWS[row][0]];
    # since nobody has won, check for a tie (no empty squares left)
    if EMPTY not in board:
        return TIE;
    return NO_ONE;

def isLegal(move,board):
    global X,O,EMPTY,TIE,NO_ONE
    return (board[move] == EMPTY);

def humanMove(board,human):
    global X,O,EMPTY,TIE,NO_ONE
    move = askNumber("Where will you move?", len(board),0);
    
    while (not isLegal(move, board)):
        print "\nThat square is already occupied, foolish human.\n";
        move = askNumber("Where will you move?", len(board),0);
            
    print "Fine. . .\n";
    return move;

def computerMove(board, computer):
    global X,O,EMPTY,TIE,NO_ONE
    move = 0;
    found = False;
    #if computer can win on next move, that's the move to make
    while (not found and move < len(board)):
        if (isLegal(move, board)):
            board[move] = computer;
            found = winner(board) == computer;
            board[move] = EMPTY;
        if (not found):
            move += 1
    #otherwise, if human can win on next move, that's the move to make
    if (not found):
        move = 0;
        human = opponent(computer);
        while (not found and move < len(board)):
            if (isLegal(move, board)):
                board[move] = human;
                found = winner(board) == human;
                board[move] = EMPTY;
            if (not found):
                move += 1
    #otherwise, moving to the best open square is the move to make
    if (not found):
        move = 0;
        i = 0;
        BEST_MOVES = [4, 0, 2, 6, 8, 1, 3, 5, 7] #pick best open square
        while (not found and i < len(board)):
            move = BEST_MOVES[i];
            if (isLegal(move, board)):
                found = True;
            i += 1
    print "I shall take square number " , move 
    return move;

def announceWinner( winner, computer, human):
    if (winner == computer):
        print winner , "'s won!";
        print "As I predicted, human, I am triumphant once more -- proof";
        print "that computers are superior to humans in all regards.";
    elif (winner == human):
        print winner , "'s won!";
        print "No, no! It cannot be! Somehow you tricked me, human.";
        print "But never again! I, the computer, so swear it!";
    else:
        print "It's a tie.\n";
        print "You were most lucky, human, and somehow managed to tie me.\n";
        print "Celebrate. . . for this is the best you will ever achieve.\n";


NUM_SQUARES = 9;
board = [EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY]
instructions();
human = humanPiece();
computer = opponent(human);
turn = X;
displayBoard(board);
while (winner(board) == NO_ONE):
    if (turn == human):
        move = humanMove(board, human);
        board[move] = human;
    else:
        move = computerMove(board, computer);
        board[move] = computer;
    displayBoard(board);
    turn = opponent(turn);

announceWinner(winner(board), computer, human);
 Welcome to the ultimate man-machine showdown: Tic-Tac-Toe.
--where human brain is pit against silicon processor
Make your move known by entering a number, 0 - 8. The number
corresponds to the desired board position, as illustrated:
0 | 1 | 2
---------
3 | 4 | 5

---------
6 | 7 | 8


Prepare yourself, human. The battle is about to begin.
Do you require the first move?  (y/n): y
 Then take the first move. You will need it.

	   |     |   
	---------
	   |     |   
	---------
	   |     |   


Where will you move?  ( 0  -  9 ): 0
 Fine. . .


	X  |     |   
	---------
	   |     |   
	---------
	   |     |   


I shall take square number  4

	X  |     |   
	---------
	   |  O  |   
	---------
	   |     |   


Where will you move?  ( 0  -  9 ): 2
 Fine. . .


	X  |     |  X
	---------
	   |  O  |   
	---------
	   |     |   


I shall take square number  1

	X  |  O  |  X
	---------
	   |  O  |   
	---------
	   |     |   


Where will you move?  ( 0  -  9 ): 7
 Fine. . .


	X  |  O  |  X
	---------
	   |  O  |   
	---------
	   |  X  |   


I shall take square number  6

	X  |  O  |  X
	---------
	   |  O  |   
	---------
	O  |  X  |   


Where will you move?  ( 0  -  9 ): 5
 Fine. . .


	X  |  O  |  X
	---------
	   |  O  |  X
	---------
	O  |  X  |   


I shall take square number  8

	X  |  O  |  X
	---------
	   |  O  |  X
	---------
	O  |  X  |  O


Where will you move?  ( 0  -  9 ): 3
 Fine. . .


	X  |  O  |  X
	---------
	X  |  O  |  X
	---------
	O  |  X  |  O


It's a tie.

You were most lucky, human, and somehow managed to tie me.

Celebrate. . . for this is the best you will ever achieve.