Write a function called is_identity that takes a 2D list(matrix) of 3x3 as a parameter and return true or false if the matrix is identity matrix or not a square matrix in which all the elements of the principal diagonal are ones and all other elements are zeros.
def is_identity(matrix):
# checking if a matrix is one
if all([all(i) for i in matrix]):
return False
# checking if a matrix is square
if len(matrix)==len(matrix[0]):
return True
# replacing the elements of the main diagonal of the matrix with 0
#if they are equal to 1
for i in range(min(len(matrix),len(matrix[0]))):
if matrix[i][i] == 1:
matrix[i][i] = 0
else:
matrix[i][i] = 1
# checking that all elements of the modified matrix are equal to 0
if not any([any(i) for i in matrix]):
return False
return True
Comments
Leave a comment