Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking diagonals in 2d list (Python)

Tags:

python

2d

The initial problem: for a given 3x3 tic tac toe board check if one of the players has won.

The simplest solution I have come up so far is rotating the matrix and summing up each row:

board
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

pr(board)
0 1 2
3 4 5
6 7 8

pr(zip(*board))
0 3 6
1 4 7
2 5 8

0..9 numbers above are just for showing positions on the board, normally they would be filled with 1 for player 1 and -1 for player 2 and 0 for unfilled position. Go row by row and if it sums up to 3 or -3 this is the winning block.

However, diagonals are not checked. Is there some way to extract diagonals from such matrix in elegant + highly performant way? I don't mean using trivial indexes "manually" (0, 1, 2), but rather get diagonal of n x n matrix.

P.S. pr is just a helper function for printing 2d list:

def pr(x):
    for row in x:
        print ' '.join(map(str, row))
like image 798
mrkafk Avatar asked Oct 23 '25 05:10

mrkafk


1 Answers

You can get one diagonal with:

[r[i] for i, r in enumerate(board)]
# [0, 4, 8]

And the opposite diagonal with:

[r[-i-1] for i, r in enumerate(board)]
# [2, 4, 6]
like image 91
David Robinson Avatar answered Oct 25 '25 19:10

David Robinson