Paul Mouzas

home

Tic Tac Toe

09 Apr 2014

This is from the /r/dailyprogrammer at reddit.

The challenge is to find the winning move given input in this format (the first letter in the input indicates whose turn it is):

X
XX-
-XO
OO-

and print out the the board :

X | X | -
- | X | 0
0 | 0 | X

If there is no winning move, you print 'No winning move'. Here is my solution:

board_input = """
O
O-X
-OX
---"""

board = map(lambda x: list(x), board_input.split())
player = board.pop(0)[0]
board = [x for x in board]
win = []

def check(x):
    return x.count('-') == 1 and x.count(player) == 2
    
for i in range(3):
    row = board[i]

    if check(row):
        win = (i, row.index('-'))
        break
    col = zip(*board)[i]
    if check(col):
        win = (i, col.index('-'))
        break

if len(win) == 0:
    left_diag = [board[0][0], board[1][1], board[2][2]]
    if check(left_diag):
        win = (i, left_diag.index('-'))
    right_diag = [board[0][2],board[1][1], board[2][0]]
    if check(right_diag):
        win = (i, right_diag.index('-'))

if win:
    row = win[0]
    col = win[1]
    board[row][col] = player[0]
    for i in range(3):
        print ' | '.join(board[i])
else:
    print 'No winning move.'

Not the most elegant solution, but it works :)