Home > Net >  Identity matrix in python
Identity matrix in python

Time:04-07

We use a server in our university to make our codes, and this one is tho check if a matrix is an identity matrix, so I wrote this code, and in VSCode and Python Tutor it seems right, but on the server it says it is wrong for the list [[0,0],[0,0]] (I've used this exact same list in VSCode and the result was False, but on the server it says that my code is returning "True")

Here´s the code

def eh_identidade(l):
t = len(l) - 1
i = 0
while i < len(l):
    lista = l[i]
    if 1 not in lista:
        return False
    ind = lista.index(1)
    if ind == i:
        i  = 1
        del lista[ind]
        if any(lista) == 1:
            return False
    else:
        return False
return True

CodePudding user response:

You can use numpy to quickly generate an indentity matrix of any size, then you can compare it to your input.

import numpy as np
def is_identity(M):
  M = np.array(M)
  dimension = len(M)
  identity = np.identity(dimension).tolist()
  return (M==identity).all() and M.shape==identity.shape

(To check whether or not it is a square, we can compare the shape of the two matricies.)

CodePudding user response:

If you know the matrix is square, you can just directly compare it with an identity matrix using numpy:

import numpy as np

def is_identity(matrix):
    return np.allclose(matrix, np.eye(len(matrix)))

Note that np.allclose allows you to process an input matrix of floats and get the correct result. If you're not sure it's square (or if it could be ragged), you can check using

def is_identity(matrix):
    nrows = len(matrix)
    if not all(len(row) == nrows for row in matrix):
        return False
    return np.allclose(matrix, np.eye(len(matrix)))
  • Related