Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python code efficiency

Tags:

python

matrix

This program tests if a matrix is an identity matrix or not.

I have pasted my code beneath, and would like to know ways in which I can optimize the efficiency of this code. Also I am new to python programming, are there some built in functions that can solve the purpose too?

    def is_identity_matrix(test):
    if (test == []):
        return False
    i = 0
    while (i < len(test)):
        if (len(test[i]) == len(test)):
            j = 0
            while(j < len(test[i])):
                if (j != i):
                    if(test[i][j] != 0):
                        return False
                else:
                    if(test[i][j] != 1):
                        return False
                if(j == (len(test[i]) - 1)):
                    break
                j += 1
            if(i == (len(test) - 1)):
                break
            i += 1
        else:
            return False
    if(i == j and i == (len(test) - 1)):
        return True

# Test Cases:

matrix1 = [[1,0,0,0],
           [0,1,0,0],
           [0,0,1,0],
           [0,0,0,1]]
print is_identity_matrix(matrix1)
#>>>True

matrix2 = [[1,0,0],
           [0,1,0],
           [0,0,0]]

print is_identity_matrix(matrix2)
#>>>False

matrix3 = [[2,0,0],
           [0,2,0],
           [0,0,2]]

print is_identity_matrix(matrix3)
#>>>False

matrix4 = [[1,0,0,0],
           [0,1,1,0],
           [0,0,0,1]]

print is_identity_matrix(matrix4)
#>>>False

matrix5 = [[1,0,0,0,0,0,0,0,0]]

print is_identity_matrix(matrix5)
#>>>False

matrix6 = [[1,0,0,0],  
           [0,1,0,2],  
           [0,0,1,0],  
           [0,0,0,1]]

print is_identity_matrix(matrix6)
#>>>False
like image 373
Abrar Khan Avatar asked Aug 02 '26 08:08

Abrar Khan


2 Answers

def is_identity_matrix(listoflist):
    return all(val == (x == y) 
        for y, row in enumerate(listoflist)  
            for x, val in enumerate(row))

(though, this does not check if the matrix is square, and it returns True for an empty list)

Explanation: Inside all we have a generator expression with nested loops where val loops over each value in the matrix. x == y evaluates to True on the diagonal and False elsewhere. In Python, True == 1 and False == 0, so you can compare val == (x == y). The parentheses are important: val == x == y would be a chained comparison equivalent to val == x and x == y

like image 87
Janne Karila Avatar answered Aug 07 '26 22:08

Janne Karila


I'd use numpy:

(np.array(matrix1) == np.identity(len(matrix1))).all()

Of course, it'd be better if you were storing matrix1 as a numpy array in the first place to avoid the conversion.

like image 31
mgilson Avatar answered Aug 07 '26 21:08

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!