Find if given matrix is Toeplitz or not | Python3 program to check whether given matrix is a Toeplitz matrix or not ; Function to check if all elements present in descending diagonal starting from position ( i , j ) in the matrix are all same or not ; mismatch found ; we only reach here when all elements in given diagonal are same ; Function to check whether given matrix is a Toeplitz matrix or not ; do for each element in first row ; check descending diagonal starting from position ( 0 , j ) in the matrix ; do for each element in first column ; check descending diagonal starting from position ( i , 0 ) in the matrix ; we only reach here when each descending diagonal from left to right is same ; Driver Code ; Function call
N = 5 NEW_LINE M = 4 NEW_LINE def checkDiagonal ( mat , i , j ) : NEW_LINE INDENT res = mat [ i ] [ j ] NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE while ( i < N and j < M ) : NEW_LINE INDENT if ( mat [ i ] [ j ] != res ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def isToeplitz ( mat ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if not ( checkDiagonal ( mat , 0 , j ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT if not ( checkDiagonal ( mat , i , 0 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 6 , 7 , 8 , 9 ] , [ 4 , 6 , 7 , 8 ] , [ 1 , 4 , 6 , 7 ] , [ 0 , 1 , 4 , 6 ] , [ 2 , 0 , 1 , 4 ] ] NEW_LINE if ( isToeplitz ( mat ) ) : NEW_LINE INDENT print ( " Matrix ▁ is ▁ a ▁ Toeplitz " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Matrix ▁ is ▁ not ▁ a ▁ Toeplitz " ) NEW_LINE DEDENT DEDENT