有没有更好(和更短)的方法来创建棋盘状数组。董事会的要求是:
"B"
表示,白色方块由"W"
表示我拥有的代码:
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
输出:
['B', 'W', 'B']
['W', 'B', 'W']
['B', 'W', 'B']
这里有一个^{} 解决方案:
对于
N=4
来说如果您确定要将每一个新行和循环添加到行列表中,那么这应该可以扩展到多个颜色(比如一个板变成“B”、“W”、“G”)。
怎么样:
有点怪,但是
这看起来像是需求爬行或类似的东西=)
相关问题 更多 >
编程相关推荐