Chapter 9: More on Functions

Program 9.1, page no. 351

In [1]:
def sum(x, y):
    return x + y
 
def product(x, y):
    return x * y
 
def difference(x, y):
    return x - y

a = 10
b = 5
pfun = sum # points to sum() 
result = pfun(a, b)
print "pfun = sum result = ", result
pfun = product # points to product()
result = pfun(a, b)
print "pfun = product result = ", result
pfun = difference # points to difference()
result = pfun(a, b)
print "pfun = difference result = ", result
pfun = sum result =  15
pfun = product result =  50
pfun = difference result =  5

Program 9.2, page no. 353

In [2]:
def sum(x, y):
    return x + y
 
def product(x, y):
    return x * y
 
def difference(x, y):
    return x - y

a = 10
b = 5
result = 0
pfun = []
pfun.append(sum)
pfun.append(product)
pfun.append(difference)

for i in range(3):
    result = pfun[i](a, b)
    print "result = ", result

result = pfun[1](pfun[0](a, b), pfun[2](a, b))
print "The product of the sum and the difference = ", result
result =  15
result =  50
result =  5
The product of the sum and the difference =  75

Program 9.3, page no. 356

In [3]:
def sum(x, y):
    return x + y
 
def product(x, y):
    return x * y
 
def difference(x, y):
    return x - y
 
def any_function(pfun , x, y):
    return pfun(x, y);

a = 10
b = 5
pf = sum
result = any_function(pf, a, b)
print "result = ", result
result = any_function(product, a, b)
print "result = ", result
print "result = ", any_function(difference, a, b)
result =  15
result =  50
result =  5

Program 9.4, page no. 359

In [4]:
def test1():
    count = 0
    count += 1
    print "test1 count = ", count

def test2():
    count = 0
    count += 1
    print "test2 count = ", count

for i in range(5):
    test1()
    test2()
test1 count =  1
test2 count =  1
test1 count =  1
test2 count =  1
test1 count =  1
test2 count =  1
test1 count =  1
test2 count =  1
test1 count =  1
test2 count =  1

Program 9.5, page no. 361

In [6]:
count = 0

def test1():
    global count
    count += 1
    print "test1 count = ", count

def test2():
    count = 0
    count += 1
    print "test2 count = ", count

for i in range(5):
    test1()
    test2()
test1 count =  1
test2 count =  1
test1 count =  2
test2 count =  1
test1 count =  3
test2 count =  1
test1 count =  4
test2 count =  1
test1 count =  5
test2 count =  1

Program 9.6, page no. 364

In [7]:
def factorial(n):
    if(n < 2):
        return n
    return n*factorial(n - 1)
 
print "Enter an integer value: ",
number = int(raw_input())
print "The factorial of %d is %d "% (number, factorial(number))
Enter an integer value: 5
 The factorial of 5 is 120 

Program 9.7, page no. 368

In [8]:
def average(*arg):
    sum = arg[0] + arg[1]
    count = 2
    for i in arg:
        count += 1
        sum += i
    average = sum/count
    return average
    
v1 = 10.5
v2 = 2.5
num1 = 6
num2 = 5
num3 = 12
num4 = 20
print "Average = %.2f " %(average(v1, 3.5, v2, 4.5, 0.0))
print "Average = %.2f " %(average(1.0, 2.0, 0.0))
print "Average = %.2f " %(average(num2, v2, num1, num4, num3, 0.0))
Average = 5.00 
Average = 1.20 
Average = 6.62 

Program 9.8, page no. 370

In [9]:
import sys

print "Program name: ", sys.argv[0]
for i in range(1, len(sys.argv)):
    print "Argument %d: %s "%(i, sys.argv[i])
Program name:  -c
Argument 1: -f 
Argument 2: /tmp/tmpL28uUI/profile_default/security/kernel-d2752270-d981-4bb2-b2bc-3d505dfa3dd5.json 
Argument 3: --IPKernelApp.parent_appname='ipython-notebook' 
Argument 4: --profile-dir 
Argument 5: /tmp/tmpL28uUI/profile_default 
Argument 6: --parent=1 

Program 9.9, page no. 377

In [1]:
SIZE = 6
comp_c = '@'
player_c = '0'
board = [[0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0]]

moves  = [[False, False, False, False, False, False],
          [False, False, False, False, False, False],
          [False, False, False, False, False, False],
          [False, False, False, False, False, False],
          [False, False, False, False, False, False],
          [False, False, False, False, False, False]]
no_of_moves = 0
invalid_moves = 0
again = 0
next_player = True

def get_score(board, player):
    global comp_c
    global player_c
    return  player_counters(board, player) -  player_counters(board, (comp_c if player == player_c else player_c)) 
 
def player_counters(board,player):
    count = 0;
    for row in range(SIZE):
        for col in range(SIZE):
            if(board[row][col] == player):
                count += 1
    return count;

def computer_move(board,moves, player):
    best_row = 0;
    best_col = 0;
    new_score = 0;
    score = SIZE*SIZE;
    temp_board = []
    temp_moves = []
    for i in range(SIZE):
        a = []
        b = []
        for j in range(SIZE):
            a.append(0)
            b.append(False)
        temp_board.append(a)
        temp_moves.append(b)            
    opponent = comp_c if (player == player_c) else player_c
    for row in range(SIZE):
        for col in range(SIZE):
            if(not moves[row][col]):
                continue;
        temp_board = board
        make_move(temp_board, row, col, player);
        valid_moves(temp_board, temp_moves, opponent);
        new_score = best_move(temp_board, temp_moves, opponent);
        if(new_score < score):
            score = new_score;
            best_row = row;
            best_col = col;
    make_move(board, best_row, best_col, player);

 
def best_move(board, moves, player):
    new_board = []
    for i in range(SIZE):
        a = []
        for j in range(SIZE):
            a.append(0)
        new_board.append(a)
    score = 0;
    new_score = 0;

    for row in range(SIZE):
        for col in range(SIZE):
            if(not moves[row][col]):
                continue;
            new_board = board
            make_move(new_board, row, col, player);
            new_score = get_score(new_board, player);
            if(score < new_score):
                score = new_score;
    return score;


def make_move(board,row,col,player):
    rowdelta = 0;
    coldelta = 0;
    x = 0;
    y = 0;
    if player == player_c:
        opponent = comp_c
    else:
        opponent = player_c        
    
    board[row][col] = player
    for rowdelta in range(-1,2):
        for coldelta in range(-1,2):
            if((row == 0 and rowdelta == -1) or row + rowdelta >= SIZE or(col == 0 and coldelta == -1) or col + coldelta >= SIZE or
(rowdelta == 0 and coldelta == 0)):
                continue;

            if(board[row + rowdelta][col + coldelta] == opponent):
                x = row + rowdelta;
                y = col + coldelta;
 
                while True:
                    x += rowdelta;
                    y += coldelta;
                    if(x >= SIZE or y >= SIZE or board[x][y] == ' '):
                        break;
                    if(board[x][y] == player):
                        x -= rowdelta
                        y -= coldelta
                        while(board[x][y] == opponent):
                            board[x][y] = player;
                            x -= rowdelta
                            y -= coldelta
 
                        break;

def reset_board(board):
    global SIZE
    global player_c
    global comp_c
    for row in range(SIZE):
        for col in range(SIZE):
            board[row][col] = ' '
 
    mid = SIZE/2
    board[mid][mid] = player_c
    board[mid-1][mid-1] = board[mid][mid]
    board[mid][mid - 1] = comp_c
    board[mid-1][mid] = board[mid][mid - 1]

def display(board):
    col_label = 'a'
    print ""
    for col in range(SIZE):
        print "%c" %((chr(ord(col_label) + col))),
    print ""
    for row in range(SIZE):
        print " +",
        for col in range(SIZE):
            print "---+",
        print "\n%2d|" %(row + 1)
         
        for col in range(SIZE):
            print " %c |" %(board[row][col]),
        print ""
    print " +"
    for col in range(SIZE):
        print "---+",
    print ""

def valid_moves(board, moves, player):
    global SIZE
    global player_c
    global comp_c
    rowdelta = 0
    coldelta = 0
    x = 0
    y = 0
    global no_of_moves
    opponent = comp_c if (player == player_c) else player_c
    for row in range(SIZE):
        for col in range(SIZE):
            moves[row][col] = False
    for row in range(SIZE):
        for col in range(SIZE):
            if(board[row][col] != ' '):
                continue
            for rowdelta in range(-1, rowdelta+1):
                for coldelta in range(-1, coldelta+1):
                    if((row == 0 and rowdelta == -1) or row + rowdelta >= SIZE or (col == 0 and coldelta == -1) or col + coldelta >= SIZE or (rowdelta == 0 and coldelta == 0)):
                        continue
                    if(board[row + rowdelta][col + coldelta] == opponent):
                        x = row + rowdelta
                        y = col + coldelta     
                        while(True):
                            x += rowdelta
                            y += coldelta
                            if(x < 0 or x >= SIZE or y < 0 or y >= SIZE or board[x][y] == ' '):
                                break
                            if(board[x][y] == player):
                                moves[row][col] = True
                                no_of_moves += 1
                                break
    return no_of_moves

    
print "REVERSI"
print "You can go first on the first game, then we will take turns."
print "You will be white - (%c)\nI will be black - (%c). " %(player_c, comp_c)
print "Select a square for your move by typing a digit for the row and a letter for the column with no spaces between."
print "Good luck! Press Enter to start."
raw_input()
while(True):
    reset_board(board)
    next_player = not(next_player)
    no_of_moves = 4
    while(True):
        display(board)
        next_player = not next_player
        if(True == next_player):
            if(valid_moves(board, moves, player_c)):
                while(True):
                    print "Please enter your move (row column - no space): ",
                    x = int(raw_input("row: "))
                    y = raw_input("col: ")
                    y = ord(chr(ord(y.lower()) - ord('a')))
                    x -= 1
                    if(y < 0 or y >= SIZE or x >= SIZE or (not moves[x][y])):
                        print "Not a valid move, try again.\n"
                        continue
                    make_move(board, x, y, player_c)
                    no_of_moves += 1
                    break
            else:
                invalid_moves += 1
                if(invalid_moves < 2):
                    print "You have to pass, press return",
                    again = raw_input()
                else:
                    print "\nNeither of us can go, so the game is over. "
        else:
            if(valid_moves(board, moves, comp_c)):
                invalid_moves = 0
                computer_move(board, moves, comp_c)
                no_of_moves += 1
            else:
                invalid_moves += 1
                if(invalid_moves < 2):
                    print "I have to pass, your go "
                else:
                    print "Neither of us can go, so the game is over.",
        display(board)
        print "The final score is: "
        print "Computer %d User %d " %(player_counters(board, comp_c), player_counters(board, player_c))

        print "Do you want to play again (y/n): ",            
        again = raw_input()
        if again == 'y':
            continue;
        else:
            break                                
        if (no_of_moves < SIZE*SIZE and invalid_moves < 2):
            continue
        else:
            break
    if again == 'n':
        break
print "\nGoodbye\n"
REVERSI
You can go first on the first game, then we will take turns.
You will be white - (0)
I will be black - (@). 
Select a square for your move by typing a digit for the row and a letter for the column with no spaces between.
Good luck! Press Enter to start.


a b c d e f 
 + ---+ ---+ ---+ ---+ ---+ ---+ 
 1|
   |    |    |    |    |    | 
 + ---+ ---+ ---+ ---+ ---+ ---+ 
 2|
   |    |    |    |    |    | 
 + ---+ ---+ ---+ ---+ ---+ ---+ 
 3|
   |    |  0 |  @ |    |    | 
 + ---+ ---+ ---+ ---+ ---+ ---+ 
 4|
   |    |  @ |  0 |    |    | 
 + ---+ ---+ ---+ ---+ ---+ ---+ 
 5|
   |    |    |    |    |    | 
 + ---+ ---+ ---+ ---+ ---+ ---+ 
 6|
   |    |    |    |    |    | 
 +
---+ ---+ ---+ ---+ ---+ ---+ 
Please enter your move (row column - no space): row: 3
col: e
 
a b c d e f 
 + ---+ ---+ ---+ ---+ ---+ ---+ 
 1|
   |    |    |    |    |    | 
 + ---+ ---+ ---+ ---+ ---+ ---+ 
 2|
   |    |    |    |    |    | 
 + ---+ ---+ ---+ ---+ ---+ ---+ 
 3|
   |    |  0 |  0 |  0 |    | 
 + ---+ ---+ ---+ ---+ ---+ ---+ 
 4|
   |    |  @ |  0 |    |    | 
 + ---+ ---+ ---+ ---+ ---+ ---+ 
 5|
   |    |    |    |    |    | 
 + ---+ ---+ ---+ ---+ ---+ ---+ 
 6|
   |    |    |    |    |    | 
 +
---+ ---+ ---+ ---+ ---+ ---+ 
The final score is: 
Computer 1 User 4 
Do you want to play again (y/n): n
 
Goodbye