Certainly, everyone is familiar with tic-tac-toe game. The rules are very simple indeed. Two players take turns marking the cells in a 3 × 3 grid (one player always draws crosses, the other — noughts). The player who succeeds first in placing three of his marks in a horizontal, vertical or diagonal line wins, and the game is finished. The player who draws crosses goes first. If the grid is filled, but neither Xs, nor 0s form the required line, a draw is announced.

You are given a 3 × 3 grid, each grid cell is empty, or occupied by a cross or a nought. You have to find the player (first or second), whose turn is next, or print one of the verdicts below: 
 -  illegal — if the given board layout can't appear during a valid game; -  the first player won — if in the given board layout the first player has just won; -  the second player won — if in the given board layout the second player has just won; -  draw — if the given board layout has just let to a draw.
The input consists of three lines, each of the lines contains characters ".", "X" or "0" (a period, a capital letter X, or a digit zero).
import fileinput

def convert_cell(cell):
    if cell == "X":
        return 1
    if cell == "0":
        return -1
    if cell == ".":
        return 0

grid = []
for idx, line in enumerate(fileinput.input()):
    grid.append([convert_cell(cell) for cell in line.rstrip()])
    if idx == 2:
        break

total_sum = 0
winner = ""
column_sums = [0] * 3
row_sums = [0] * 3
diagonal_sums = [0] * 2
legal = True

def check_win(amount, winner):
    if amount == 3:
        if winner != "":
            return winner, False
        return "first", True
    if amount == -3:
        if winner != "":
            return winner, False
        return "second", True
    return winner, True 

for i in range(len(grid)):
    if not legal:
        break
    for j in range(len(grid[i])):
        cell = grid[i][j]
        if i == j:
            diagonal_sums[0] += cell
        if i == 3 - j:
            diagonal_sums[1] += cell
        row_sums[i] += cell
        column_sums[j] += cell
        total_sum += cell
    winner, legal = check_win(row_sums[i], winner)

if legal:
    for s in column_sums:
        winner, legal = check_win(s, winner)
        if not legal:
            break
    for s in diagonal_sums:
        winner, legal = check_win(s, winner)
        if not legal:
            break

if not legal:
    print("illegal")
elif winner != "":
    print(f"the {winner} player won")
else:
    if 0 not in [cell for row in grid for cell in row]:
        print("draw")
    elif total_sum == 0:
        print("first")
    elif total_sum == 1:
        print("second")
    else:
        print("illegal")
