题目
思路
横竖6种,斜着两种,分别判断是否一致,一致且不为空则返回其值,都不满足则返回平局
我的代码
def checkio(game_result: list) -> str:
result = 'D'
#斜着2种
if game_result[0][0] == game_result[1][1] == game_result[2][2] and game_result[0][0] != '.':
result = game_result[0][0]
return result
if game_result[2][0] == game_result[1][1] == game_result[0][2] and game_result[2][0] != '.':
result = game_result[2][0]
return result
#横竖6种
for i in range(3):
if game_result[i][0] == game_result[i][1] == game_result[i][2] and game_result[i][0] != '.':
result = game_result[i][0]
break
if game_result[0][i] == game_result[1][i] == game_result[2][i] and game_result[0][i] != '.':
result = game_result[0][i]
break
return result
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio([
"X.O",
"XX.",
"XOO"]) == "X", "Xs wins"
assert checkio([
"OO.",
"XOX",
"XOX"]) == "O", "Os wins"
assert checkio([
"OOX",
"XXO",
"OXX"]) == "D", "Draw"
assert checkio([
"O.X",
"XX.",
"XOO"]) == "X", "Xs wins again"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
clear 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'
speedy code
和我的方法一样,分8种场景判断
def checkio(game_result):
for i in range(3):
if (game_result[i][0] in ['O', 'X']) and (game_result[i][0] == game_result[i][1] == game_result[i][2]):
return game_result[i][0]
if (game_result[0][i] in ['O', 'X']) and (game_result[0][i] == game_result[1][i] == game_result[2][i]):
return game_result[0][i]
if (game_result[1][1] in ['O', 'X']) and ((game_result[0][0] == game_result[1][1] == game_result[2][2]) or (game_result[0][2] == game_result[1][1] == game_result[2][0])):
return game_result[1][1]
return "D"