Determine that the diagonal elements of the matrix are equal

Look at the topic:

Known matrix:
_matrix = [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]
Insert picture description here

  • If the elements on the diagonal of the matrix are equal , the output is True , otherwise the output is False

The code below

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)
  • The only method used is to judge the result in a linear loop.
  • The judgment directions are: red, orange, green, blue, pink, and yellow.
    Insert picture description here

(Ps): When I first thought about it, I didn't think of such a traversal method to complicate the problem. This is to watch other people's code and learn from other people's ideas. I feel that the traversal speed has been optimized. I don't know if there are other more efficient algorithms to solve this problem.

  • Everyone is welcome to comment

Guess you like

Origin blog.csdn.net/pythonstrat/article/details/114406174