Python Tic Tac Toe | Competitive Coding Questions

Python Competitive Coding Questions | Tic Tac Toe: This practice is based on Tic Tac Toe in Python programming language. Submitted by Prerana Jain, on April 24, 2020

Question

You will be given a completed board of Tic-Tac-Toe. The cells will be represented by 'X' and 'O'. If there are any empty cells, they will be represented by '#'. 'X' is used by Player 1 and 'O' is used by Player 2. Given the board, print Player 1 if player 1 wins, print Player 2 if player 2 wins, and print "Draw" in case of a Tie. It is guaranteed that all tic-tac-toe boards given in input are valid.

Input

3x3 Tic Tac Toe board. 3 lines containing 3 characters each separated by spaces.

X  O  X
O  X  X
O  O  X

Output

Print who wins in a single line.

    Player 1

Explanation/Solution

In this question we have given 3x3 Tic Tac Toe board and we have to find which player won. The player who wins has the same 3 consecutive symbols like 'X' and 'O'. Both the symbols are represented by the different players like 'X' for player 1 and 'O' for player 2. We can solve this question by making the 3x3 list by using python 3.

To solve this question, we are using Python3.

Python Code

arr = []

# taking input 3 X3 matrix
for i in range(3):
    arr.append(list(input().split()))

if ((arr[0][0] == arr[0][1] and arr[0][1] == arr[0][2] and arr[0][0] == 'X') or
(arr[1][0] == arr[1][1] and arr[1][1] == arr[1][2] and arr[1][0] == 'X') or
(arr[2][0] == arr[2][1] and arr[2][1] == arr[2][2] and arr[2][0] == 'X') or
(arr[0][0] == arr[1][0] and arr[1][0] == arr[2][0] and arr[0][0] == 'X') or
(arr[0][1] == arr[1][1] and arr[1][1] == arr[2][1] and arr[0][1] == 'X') or
(arr[0][2] == arr[1][2] and arr[1][2] == arr[2][2] and arr[0][2] == 'X') or
(arr[0][0] == arr[1][1] and arr[1][1] == arr[2][2] and arr[0][0] == 'X') or
(arr[0][2] == arr[1][1] and arr[1][1] == arr[2][0] and arr[0][2] == 'X')):
    print("Player 1")# player 1 win
elif((arr[0][0] == arr[0][1] and arr[0][1] == arr[0][2] and arr[0][0] == 'O') or
(arr[1][0] == arr[1][1] and arr[1][1] == arr[1][2] and arr[1][0] == 'O') or
(arr[2][0] == arr[2][1] and arr[2][1] == arr[2][2] and arr[2][0] == 'O') or
(arr[0][0] == arr[1][0] and arr[1][0] == arr[2][0] and arr[0][0] == 'O') or
(arr[0][1] == arr[1][1] and arr[1][1] == arr[2][1] and arr[0][1] == 'O') or
(arr[0][2] == arr[1][2] and arr[1][2] == arr[2][2] and arr[0][2] == 'O') or
(arr[0][0] == arr[1][1] and arr[1][1] == arr[2][2] and arr[0][0] == 'O') or
(arr[0][2] == arr[1][1] and arr[1][1] == arr[2][0] and arr[0][2] == 'O')):
    print("Player 2")# player 2 win
else :
    print("Draw")# Match is drawn no body win

Output

RUN 1:
X X X
O O X
O O #
Player 1

RUN 2:
O X O
X O X
O # #
Player 2

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.