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 notasquare matrix in which all the elements of the principal diagonal are ones and all other elements are zeros.
def is_identity(matrix):
'''
function returns true if the matrix is identity matrix or
notasquare matrix in which all the elements of the principal diagonal
are ones and all other elements are zeros
'''
if len(matrix) == 0:
return False
identity = True
for row in matrix:
for el in row:
if el != 1:
identity = False
if identity:
return True
if matrix[0] and len(matrix) == len(matrix[0]):
return False
diagonal_ones = True
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if i == j:
if matrix[i][j] != 1:
diagonal_ones = False
else:
if matrix[i][j] != 0:
diagonal_ones = False
if diagonal_ones:
return True
return False
Comments
Leave a comment