判断 矩阵对角线元素相等

看题目:

已知矩阵:
_matrix = [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]
在这里插入图片描述

  • 如该矩阵,对角线上的元素相等,则输出 True,否则输出 False

下面上代码

def is_toeplitz_matrix(matrix):
    line_nums = len(matrix)
    per_line_nums = len(matrix[0])
    col = 0
    while col < per_line_nums -1: # 4
        line = 0
        while line < line_nums -1: # 3
            if matrix[line][col] != matrix[line + 1][col + 1]:
                return False
            line += 1
        col += 1

    return True

_matrix = [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]


a = is_toeplitz_matrix(_matrix)
print(a)
print(_matrix)
for i in _matrix:
    print(i)
  • 才用的方法是 线性循环判断结果。
  • 判断方向依次是: 红, 橙, 绿,蓝, 粉红, 黄色。
    在这里插入图片描述

(ps): 初次思考时,并没有想到这样的遍历方式,把问题复杂化了,这是观看别人的代码,借鉴别人的思路。觉得在遍历速度上已经很优化了,不知道还有没有其他的更高效的算法去解决这个问题。

  • 欢迎大家评论

猜你喜欢

转载自blog.csdn.net/pythonstrat/article/details/114406174