Nanny-level hands-on teaching you to use python to realize the nature judgment tutorial of the relationship matrix

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 All the cases are finished, here is the complete demonstration code (remember pip install numpy without numpy library):

import numpy as np


class RelationMatrix():
    def __init__(self):
        self.matrix = None

    def getMatrix(self):
        GUIDANCE = """请以字符串形式输入关系矩阵,输入python列表形式的字符串,如:
            |1,0,1|
            |1,0,0|
            |0,0,0|
            则输入:[[1,0,1],[1,0,0],[0,0,0]]
            输入数据时不要换行!
        """
        print(GUIDANCE)
        self.matrix = np.array(eval(input("请输入关系矩阵:")))
        print(self.matrix)

    def isReflexive(self):
        if (self.matrix.diagonal() == 1).all():
            return True
        else:
            return False

    def isAntiReflexive(self):
        if (self.matrix.diagonal() == 0).all():
            return True
        else:
            return False

    def isSymmetry(self):
        if (self.matrix.T == self.matrix).all():
            return True
        else:
            return False

    def isAntiSymmetric(self):
        matrix = self.matrix.copy()
        np.fill_diagonal(matrix, 0)
        product = matrix * matrix.T
        if np.count_nonzero(product) == 0:
            return True
        else:
            return False

    def isTransitive(self):
        indexes = (np.argwhere(self.matrix == 1)).tolist()
        for i in indexes:
            for j in indexes:
                if ((i[1] == j[0]) and ([i[0], j[1]] not in indexes)):
                    return False
        return True

    def judgeRelationship(self):
        try:
            self.getMatrix()
            if self.isReflexive():
                print("该矩阵是自反的")
            if self.isAntiReflexive():
                print("该矩阵是反自反的")
            if self.isSymmetry():
                print("该矩阵是对称的")
            if self.isAntiSymmetric():
                print("该矩阵是反对称的")
            if self.isTransitive():
                print("该矩阵是传递的")
        except Exception as err:
            print(err)
            print("输入内容不合法,请核对后重试!")



if __name__ == '__main__':
    rm = RelationMatrix()
    rm.judgeRelationship()

Running effect diagram:

 

More numpy usage tutorials: numpy Chinese documentation

If you have any doubts, leave a message to answer

If there is an error, please contact for correction

If there is any infringement, contact to delete

Guess you like

Origin blog.csdn.net/m0_52726759/article/details/121219370