Answer to Question #190345 in Python for python

Question #190345

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.


1
Expert's answer
2021-05-11T04:21:08-0400
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

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS