Tic-Tac-Toe, sometimes also known as Xs and Os, is a game for two players (X and O) who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three respective marks in a horizontal, vertical, or diagonal rows (NW-SE and NE-SW) wins the game.
But we will not be playing this game. You will be the referee for this games results. You are given a result of a game and you must determine if the game ends in a win or a draw as well as who will be the winner. Make sure to return "X" if the X-player wins and "O" if the O-player wins. If the game is a draw, return "D."
A game's result is presented as a list of strings, where "X" and "O" are players' marks and "." is the empty cell.
Input: A game's result. A list of strings (Unicode).
Output: "X", "O" or "D". A string.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
|
checkio([
"X.O" ,
"XX." ,
"XOO" ]) = = "X" , "Xs wins"
checkio([
"OO." ,
"XOX" ,
"XOX" ]) = = "O"
checkio([
"OOX" ,
"XXO" ,
"OXX" ]) = = "D"
|
How it is used: The concepts in this task will help you when iterating data types. They can also used in game algorithms, allowing you to know how to check results.
开始写的略复杂,A了后看下网上高手做的这题代码,真是涨姿势
def checkio(game_result):
r = [[game_result[0][0],game_result[1][1],game_result[2][2]],[game_result[0][2],game_result[1][1],game_result[2][0]]]
for i in range(3):
r.append([x for x in game_result[i]])
r += [[row[i] for row in game_result]]
if ['X','X','X'] in r:
return 'X'
if ['O','O','O'] in r:
return 'O'
return 'D'
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([
u"X.O",
u"XX.",
u"XOO"]) == "X", "Xs wins"
assert checkio([
u"OO.",
u"XOX",
u"XOX"]) == "O", "Os wins"
assert checkio([
u"OOX",
u"XXO",
u"OXX"]) == "D", "Draw"
assert checkio([
u"O.X",
u"XX.",
u"XOO"]) == "X", "Xs wins again"