在二维表检查对角线(蟒蛇) [英] checking diagonals in 2d list (Python)
问题描述
最初的问题:对于给定的3x3的井字板检查,如果一个玩家赢得了
我来了迄今最简单的办法是旋转矩阵,总结各行:
板
[0,1,2],[3,4,5〕,〔6,7,8]]
PR(板)
0 1 2
3 4 5
6 7 8
PR(邮政编码(*板))
0 3 6
1 4 7
2 5 8
0..9数字上面只为表现出对董事会职位,通常他们会装满1,供玩家1和-1的球员2和0的空缺职位。去逐行,如果它总结为3或-3,这是获胜的块。
不过,对角线不检查。有没有一些方法来提取这种矩阵对角线优雅+具有高性能的方式?我的意思不是用平凡索引手动(0,1,2),而是获得对角n阶矩阵。
P.S。 PR只是一个辅助功能,打印二维列表:
高清PR(X):
对于排在X:
打印''。加入(图(STR,行))
与数幻方的游戏领域
2 | 9 | 4
7 | 5 | 3
6 | 1 | 8
现在经过三年移动总结和检查总和是15 - >赢家。你要检查这个每一个球员。当然,你有4招和第5手(只有开始游戏的玩家)
后复查这是我在我的第一个Java类解决了这个问题。
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))
Number your game field with a magic square
2|9|4
7|5|3
6|1|8
Now sum up after three moves and check if the sum is 15 --> Winner. You have to check this for every player. Surely you have to recheck after 4th move and 5th move (only the player that started the game)
This is how I solved this problem in my first Java class.
这篇关于在二维表检查对角线(蟒蛇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!