Is there a better (and shorter) way of how to create chessboard like array. Requirements for the board are:
"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']
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']]
Here is an itertools
solution:
from itertools import cycle
N = 4
colors = cycle(["W","B"])
row_A = [colors.next() for _ in xrange(N)]
if not N%2: colors.next()
row_B = [colors.next() for _ in xrange(N)]
rows = cycle([row_A, row_B])
board = [rows.next() for _ in xrange(N)]
For N=4
this gives
['W', 'B', 'W', 'B']
['B', 'W', 'B', 'W']
['W', 'B', 'W', 'B']
['B', 'W', 'B', 'W']
This should be extensible to multiple colors (say a board that goes "B", "W", "G") if you make sure to add each new row and cycle to the list of rows.
Kind of a hack but
print [["B" if abs(n - row) % 2 == 0 else "W" for n in xrange(3)] for row in xrange(3)][::-1]
This seems like requirements creep or something =)
def make_board(n):
''' returns an empty list for n <= 0 '''
return [["B" if abs(c - r) % 2 == 0 else "W" for c in xrange(n)] for r in xrange(n)][::-1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With