
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Whether Given Matrix is a Toeplitz Matrix in Python
Suppose we have a matrix M, we have to check whether it is a Toeplitz matrix or not. As we know a matrix is said to be Toeplitz when every diagonal descending from left to right has the same value.
So, if the input is like
7 | 2 | 6 |
3 | 7 | 2 |
5 | 3 | 7 |
then the output will be True.
To solve this, we will follow these steps −
- for each row i except the last one, do
- for each column except the last one, do
- if matrix[i, j] is not same as matrix[i+1, j+1], then
- return False
- if matrix[i, j] is not same as matrix[i+1, j+1], then
- for each column except the last one, do
- return True
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, matrix): for i in range(len(matrix)-1): for j in range(len(matrix[0])-1): if matrix[i][j]!=matrix[i+1][j+1]: return False return True ob = Solution() matrix = [ [7, 2, 6], [3, 7, 2], [5, 3, 7]] print(ob.solve(matrix))
Input
[[7, 2, 6], [3, 7, 2], [5, 3, 7]]
Output
True
Advertisements