Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a matrix is square? (Python)

Tags:

python

matrix

I want to test a 2x2 matrix of [[5,6],[7,8]] to see if it's a square.

I run my code and I'm supposed to get True but I got False instead...

 def square(sq):
     for element in sq:
         if element:
             return False
         return True
like image 898
user2581724 Avatar asked Sep 05 '25 03:09

user2581724


2 Answers

given m is a numpy matrix and you have imported numpy

def square(m):
    return m.shape[0] == m.shape[1]
like image 145
Kasra Avatar answered Sep 07 '25 21:09

Kasra


If you want to check whether a matrix is NxN, you can use:

def isSquare (m): return all (len (row) == len (m) for row in m)

As you said in your comment: if the length of all rows equals the number of rows.

like image 33
Hyperboreus Avatar answered Sep 07 '25 20:09

Hyperboreus