python - Create a black and white chessboard in a two dimensional array -
is there better (and shorter) way of how create chessboard array. requirements board are:
- board can different size (in example it's 3x3)
- bottom left square of board should black
- black square presented
"b"
, white square presented"w"
code have:
def iseven(number): return number % 2 == 0 board = [["b" x in range(3)] x in range(3)] if iseven(len(board)): rowindex, row in enumerate(board): if iseven(rowindex + 1): squareindex, square in enumerate(row): if iseven(squareindex + 1): board[rowindex][squareindex] = "w" else: squareindex, square in enumerate(row): if not iseven(squareindex + 1): board[rowindex][squareindex] = "w" else: rowindex, row in enumerate(board): if not iseven(rowindex + 1): squareindex, square in enumerate(row): if iseven(squareindex + 1): board[rowindex][squareindex] = "w" else: squareindex, square in enumerate(row): if not iseven(squareindex + 1): board[rowindex][squareindex] = "w" 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] in range(n)] 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] in range(n)] j in range(n)] >>> print board [['w', 'b', 'w', 'b'], ['b', 'w', 'b', 'w'], ['w', 'b', 'w', 'b'], ['b', 'w', 'b', 'w']]
Comments
Post a Comment