检查矩阵中的列或对角线是否= x(无Numpy) [英] Check if column or diagonal in matrix = x (Without Numpy)

查看:101
本文介绍了检查矩阵中的列或对角线是否= x(无Numpy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用此代码检查矩阵中是否有一行= x:

I can use this code to check if a row in a matrix = x:

q = [[1,2,1],[1,2,1],[2,1,2]]
answer = [sum(row) for row in q]
for i in range(0, len(q)):
    if answer[i] == 6:
        print "Player 2 won!"
    if answer[i] == 3:
        print "Player 1 won!"
if answer[i] != 6 and 3:
    print "It's a tie!"

如何在不使用Numpy的情况下检查矩阵是否具有对角线或= x的列(如上所示,有数学方法吗?)

How can I check if my matrix has a diagonal or column that = x, without using Numpy (Is there a mathematical way to do it as shown above?)

示例:(X =无关紧要)

Example: (X = something that doesn't matter)

q = [[1,X,X],[1,X,X],[1,X,X]]应打印True

q = [[1,X,X],[X,1,X],[X,X,1]]应打印True(对角线)

q = [[X,X,1],[X,1,X],[1,X,X]]应打印True(对角{Other One})

q = [[X,X,1],[X,1,X],[1,X,X]] Should print True (Diagonal{Other One})

q = [[1,X,X],[X,1,X],[X,1,X]]应打印False

q = [[X,1,X],[X,1,X],[X,1,X]]应打印True(水平)

矩阵应如何具有其获胜条件"

推荐答案

好吧,您可以将获胜条件的枚举转换成元组,成对的元组...在3x3的棋盘世界中工作量不大.

Well you could translate your enumeration of winning conditions into a tuple, of tuple of pairs ... not to much work in a 3x3 board world.

类似下面的内容(拿起示例板)并导致平局,应该让您开始进一步学习Python:

Something like below (taking your sample board) and resulting in a tie should get you started in further learning Python:

#! /usr/bin/env python
"""Check in snaive 3x3 game board world for diagonal,
column, or row all ocupied by one player."""
from __future__ import print_function

players = (1, 2)  # Code for the players
board = [[1, 2, 1],  # Board interpreted as 3 lists rows
         [1, 2, 1],
         [2, 1, 2]]
winning_configs = (  # outer-inner-index pairs that win:
    ((0, 0), (1, 1), (2, 2)),  # TL to BR diagonal
    ((0, 2), (1, 1), (2, 0)),  # TR to BL diagonal
    ((0, 0), (1, 0), (2, 0)),  # L column
    ((0, 1), (1, 1), (2, 1)),  # M column
    ((0, 2), (1, 2), (2, 2)),  # R column
    ((0, 0), (0, 1), (0, 2)),  # L row
    ((1, 0), (1, 1), (1, 2)),  # M row
    ((2, 0), (2, 1), (2, 2)),  # R row
)


def and_the_winner_is(players, board, winning_configs):
    """First one matching rules is returned as winner,
    otherwise None to indicate a tie."""
    for player in players:
        for cfg in winning_configs:
            if all([board[i][j] == player for i, j in cfg]):
                return player
    else:
        return None


def main():
    """Determine the result from board."""
    winner = and_the_winner_is(players, board, winning_configs)

    if winner in players:
        print('Winner is Player({})'.format(winner))
    else:
        print('A tie')


if __name__ == '__main__':
    main()

这篇关于检查矩阵中的列或对角线是否= x(无Numpy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆