I used to like Python but...

gods1child alankarmisra at hotmail.com
Thu Jun 7 15:46:39 EDT 2001


Now I think I'm just plain in love. I wuz reading this book on OOP
concepts which used a classic problem of chess (described below) to
illustrate the power of 'thinking OOP'. It gave a 'pseudocode' for a
possible solution to the problem. Converting the pseudocode to Python
was like typing the darn pseudocode! Man i love this language. Here's
the problem and the code for your amusement and one more reason to
pray for Python becoming king of the hill:

The problem is to place 8 queens on a chess board such that no queen
can attack another. The solution given below takes an 'OOP' approach
where each queen queries its immediate neighbor (the one that came
before) as to where it can place itself in a specific cell. If the
neighbor accepts, it in turn politely asks its neighbor if this new
entrant should be allowed to stand in that cell until someone says
'this means war!' and the poor new entrant starts looking for a new
home. This way the queens find the acceptable solution by talking to
each other instead of Mr Garry Kasparov looking over the chess board
making decisions on behalf of each queen. BTW, i'm not a science grad
so i apologize if this is like the oldest problem in the world

# 8 queens
# The problem is to place 8 queens on a
# chess board such that no queen can attack
# another

class Queen:
    def __init__(self, column, queen):
        self.row = 1
        self.column = column
        self.neighbor = queen

    def findSolution(self):
        while (self.neighbor and \
               self.neighbor.canAttack(self.row, self.column)):
            if(not self.advance()): 
                return 0 
        return 1 

    def advance(self):
        if(self.row < 8): 
            self.row += 1 
            return self.findSolution() 

        if(self.neighbor and not self.neighbor.advance()):
            return 0

        self.row = 1
        return self.findSolution()

    def canAttack(self, testRow, testColumn):
        if self.row == testRow:
            return 1

        columnDifference = testColumn - self.column
        if ((self.row + columnDifference) == testRow) or \
           ((self.row - columnDifference) == testRow):
            return 1

        if self.neighbor:
            return self.neighbor.canAttack(testRow, testColumn)

        return 0 

    def getPosition(self, cells):
        if self.neighbor != None:
            self.neighbor.getPosition(cells)
        cells[self.row-1][self.column-1] = 'X'

lastQueen = None
for i in range(1,9):
    lastQueen = Queen(i, lastQueen)
    lastQueen.findSolution()

cells = []
for i in range(0,8):
    cells.append(list('O'* 8))

lastQueen.getPosition(cells)
print '\n\n'
for i in range(0,8):
    for j in range(0,8):
        print cells[i][j],
    print



More information about the Python-list mailing list