ton1c - 3 months ago 13
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']
``````

``````>>> n = 3