ton1c ton1c - 5 months ago 17
Python Question

Create a black and white chessboard in a two dimensional array

Is there a better (and shorter) way of how to create chessboard like array. Requirements for the board are:


  • board can be different size (in my example it's 3x3)

  • bottom left square of the board should always be black

  • black square is presented by
    "B"
    , white square is presented by
    "W"



Code that I have:

def isEven(number):
return number % 2 == 0

board = [["B" for x in range(3)] for x in range(3)]
if isEven(len(board)):
for rowIndex, row in enumerate(board):
if isEven(rowIndex + 1):
for squareIndex, square in enumerate(row):
if isEven(squareIndex + 1):
board[rowIndex][squareIndex] = "W"
else:
for squareIndex, square in enumerate(row):
if not isEven(squareIndex + 1):
board[rowIndex][squareIndex] = "W"
else:
for rowIndex, row in enumerate(board):
if not isEven(rowIndex + 1):
for squareIndex, square in enumerate(row):
if isEven(squareIndex + 1):
board[rowIndex][squareIndex] = "W"
else:
for squareIndex, square in enumerate(row):
if not isEven(squareIndex + 1):
board[rowIndex][squareIndex] = "W"

for row in board:
print row


Output:

['B', 'W', 'B']
['W', 'B', 'W']
['B', 'W', 'B']

DSM DSM
Answer

How about:

>>> n = 3
>>> board = [["BW"[(i+j+n%2+1) % 2] for i in range(n)] for j in range(n)]
>>> print board
[['B', 'W', 'B'], ['W', 'B', 'W'], ['B', 'W', 'B']]
>>> n = 4
>>> board = [["BW"[(i+j+n%2+1) % 2] for i in range(n)] for j in range(n)]
>>> print board
[['W', 'B', 'W', 'B'], ['B', 'W', 'B', 'W'], ['W', 'B', 'W', 'B'], ['B', 'W', 'B', 'W']]