Skip to content

Instantly share code, notes, and snippets.

@wcneill
Created September 5, 2019 20:23
Show Gist options
  • Save wcneill/9c66f8dc46471463c47be3de0c0312c1 to your computer and use it in GitHub Desktop.
Save wcneill/9c66f8dc46471463c47be3de0c0312c1 to your computer and use it in GitHub Desktop.
given a 3x3 grid, determine if three identical elements can be found in any given row, column or diagonal.
def all_same(lst):
return all(item == lst[0] for item in lst)
# given an a 3x3 board representing a tic tac to game between player 1
# and player 2, determine if any players have won by checking for
# three in a row in any column, row or diagonal.
if __name__ == '__main__':
grid = [[0, 2, 1],
[2, 1, 2],
[1, 1, 1]]
print(grid)
win = False
while not win:
# check columns for wins
for i in range(3):
column = [row[i] for row in grid]
win = all_same(column)
if win:
print("Player", column[0], "wins by completing column", i + 1)
break
if win: break
# check rows for wins
for j in range(3):
win = all_same(grid[j])
if win:
print('Player', grid[j][0], 'wins by completing row', j + 1)
break
if win: break
# check diagonals for wins
diag1 = [row[i] for i, row in zip(range(3), grid)]
win = all_same(diag1)
if win:
print('Player', diag1[0], 'wins by completing a diagonal!')
break
diag2 = [row[i] for i, row in zip(range(3)[::-1], grid)]
win = all_same(diag2)
if win:
print('Player', diag2[0], 'wins by completing a diagonal!')
break
print('The game is over')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment