Xs and Os Referee

Xs and Os Referee

 1 def checkio(game_result):

 2     winner = 'D'

 3 

 4     for row in game_result: 5 if row[0] == row[1] == row[2] and row[0] != '.': 6 winner = row[0] 7 8 for col in range(0, 3): 9 if game_result[0][col] == game_result[1][col] == game_result[2][col] and game_result[0][col] != '.': 10 winner = game_result[0][col] 11 12 if game_result[0][0] == game_result[1][1] == game_result[2][2] and game_result[0][0] != '.': 13 winner = game_result[0][0] 14 15 if game_result[0][2] == game_result[1][1] == game_result[2][0] and game_result[0][2] != '.': 16 winner = game_result[0][2] 17 18 return winner

此题的结论是python支持形如此等模式的判断: row[0] == row[1] == row[2], 即支持连等

再来看看大神代码

 

1 def checkio(result):

2     rows = result 3 cols = map(''.join, zip(*rows)) 4 diags = map(''.join, zip(*[(r[i], r[2 - i]) for i, r in enumerate(rows)])) 5 lines = rows + list(cols) + list(diags) 6 7 return 'X' if ('XXX' in lines) else 'O' if ('OOO' in lines) else 'D'

 

zip函数可将两个数组柔和在一起,如学生姓名name = ['bob', 'jenny'], 成绩grade = [80, 90], zip(name, grade) = [('bob', 80), ('jenny', 90)], 在函数调用中使用*list/tuple的方式表示将list/tuple分开,作为位置参数传递给对应函数(前提是对应函数支持不定个数的位置参数), 如test = ["XXX", "OOO", "..."], zip(*test) = [('X', 'O', '.'), ('X', 'O', '.'), ('X', 'O', '.')]

map函数接受两个参数, 第一个为函数名, 第二个为可迭代对象, 如array = [1, 2, 3], map(str, array) = ['1', '2', '3'], 即对第二个对象应用第一函数

你可能感兴趣的:(OS)