Answer to Question #165148 in Python for raj

Question #165148

Abhinav and Anjali are playing the Tic-Tac-Toe game. Tic-Tac-Toe is a game played on a grid that's three squares by three squares. Abhinav is O, and Anjali is X. Players take turns putting their marks in empty squares. The first player to get 3 of her marks in a diagonal or horizontal, or vertical row is the winner. When all nine squares are complete, the game is over. If no player has three marks in a row, the game ends in a tie. Write a program to decide the winner in the Tic-Tac-Toe game.Input


The input will be three lines contain O's and X's separated by space.Output


The output should be a single line containing either "Abhinav Wins" or "Anjali Wins" or "Tie".Explanation


For example, if the input is

O X O
O X X
O O X 

as three of O's are in vertical row print "Abhinav Wins".


1
Expert's answer
2021-02-21T19:54:12-0500
O_WINS = "Abhinav Wins"
X_WINS = "Anjali Wins"
TIE = "Tie"


def find_winner(matrix):
    """
    The algorithm is as follows:
    1. compute the sum for all rows, columns and diagonals
    2. if any of the sums is 3,
       it means that this row, column or diagonal had all X's in it,
       which means that Anjali wins. Conversely, if the sum is 0,
       it means that it had all 0's, which means that Abhinav wins.

    :param matrix: binary representation of the tic-tac-toe board
    :return: the winner of the game, or "Tie" if no one wins
    """

    n = len(matrix)
    sum_main_diag = 0
    sum_other_diag = 0
    for i in range(n):
        sum_current_row = 0
        sum_current_column = 0
        for j in range(n):
            sum_current_row += matrix[i][j]
            sum_current_column += matrix[j][i]
        if sum_current_row == n or sum_current_column == n:
            return X_WINS
        if sum_current_row == 0 or sum_current_column == 0:
            return O_WINS
        sum_main_diag += matrix[i][i]
        sum_other_diag += matrix[i][n - 1 - i]

    if sum_main_diag == n or sum_other_diag == n:
        return X_WINS
    if sum_main_diag == 0 or sum_other_diag == 0:
        return O_WINS

    return TIE


if __name__ == "__main__":
    import sys

    # read from standard input
    source = sys.stdin

    # read from a file called 'input.txt' (uncomment the next line)
    # source = open('input.txt', 'r')

    # reading the board state from the input source
    input_matrix = list(map(lambda line: line.split(), source.readlines()))

    # converting the board to a binary form where '0' is 0 and 'X' is 1
    binary_matrix = [list(map(lambda x: 1 if x == 'X' else 0, row)) for row in input_matrix]

    print(find_winner(binary_matrix))
    source.close()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS