Tic Tac Toe,有时也称为Xs和Os,是一款由两名玩家(X和O)轮流在3×3网格中标记空格的游戏。在水平、垂直或对角线行(NW-SE和NE-SW)中分别放置三个标记的玩家获胜。
但我们不会玩这个游戏。你将是这次比赛结果的裁判。你会得到一场比赛的结果,你必须决定比赛是以胜利还是平局结束,以及谁将是赢家。如果X玩家赢了,请确保返回“X”,如果O玩家赢了,请返回“O”。如果比赛是平局,则返回“D”。
checkio([
"X.O",
"XX.",
"XOO"]) == "X"
checkio([
"OO.",
"XOX",
"XOX"]) == "O"
checkio([
"OOX",
"XXO",
"OXX"]) == "D"
代码实现:
def checkio(game_result):
els=[list(i) for i in game_result]
for i in range(0,3):
for j in range(0,3):
if (i==0 and els[i][j]+els[i+1][j]+els[i+2][j]=='XXX') or (j==0 and els[i][j]+els[i][j+1]+els[i][j+2]=='XXX') or (els[0][0]+els[1][1]+els[2][2]=='XXX') or (els[2][0]+els[1][1]+els[0][2]=='XXX'):
return 'X'
if (i==0 and els[i][j]+els[i+1][j]+els[i+2][j]=='OOO') or (j==0 and els[i][j]+els[i][j+1]+els[i][j+2]=='OOO') or (els[0][0]+els[1][1]+els[2][2]=='OOO') or (els[2][0]+els[1][1]+els[0][2]=='OOO'):
return 'O'
else:
return 'D'
if __name__ == "__main__":
print("Example:")
print(checkio(["X.O", "XX.", "XOO"]))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio(["X.O", "XX.", "XOO"]) == "X", "X wins"
assert checkio(["OO.", "XOX", "XOX"]) == "O", "O wins"
assert checkio(["OOX", "XXO", "OXX"]) == "D", "Draw"
assert checkio(["O.X", "XX.", "XOO"]) == "X", "X wins again"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
思路分析:
本道题可以看成是二维数组问题,在python中一般用列表来表示数组,而二维数组就是列表里面嵌套列表。所给的函数参数是含字符串的列表,所以先要把参数列表给转化为二维的。该矩阵是3X3的矩阵,而游戏结果无非是X赢或者O赢或者平局,而赢棋就三行三列加两条对角线。用双循环遍历3X3矩阵,3行的情况就是判断j=0,在外循环的遍历下i=1,2,3时,j,j+1,j+2对应的元素是否成一行,同理3列的情况就是i=0,在内循环的遍历下,j=1,2,3时,i,i+1,i+2对应的元素是否成一列,外加两条已经确定好的对角线,即可得到答案。当然本题也有局限,属于3X3的枚举。
Best Code:
def checkio(result):
rows = result
cols = map(''.join, zip(*rows))
diags = map(''.join, zip(*[(r[i], r[2 - i]) for i, r in enumerate(rows)]))
lines = rows + list(cols) + list(diags)
return 'X' if ('XXX' in lines) else 'O' if ('OOO' in lines) else 'D'