user2581724
user2581724

Reputation: 245

Check if a matrix is square? (Python)

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

Upvotes: 4

Views: 25729

Answers (5)

Kasra
Kasra

Reputation: 910

given m is a numpy matrix and you have imported numpy

def square(m):
    return m.shape[0] == m.shape[1]

Upvotes: 9

Thameem Ansari
Thameem Ansari

Reputation: 1

this should also work.

A is a list with matrix.

if not A:  
    return True  
m = len(A)  
n = len(A[0])  
if m == n:  
    return True  
else:  
    return False

Upvotes: 0

xxyzzy
xxyzzy

Reputation: 588

If your matrix represents two coordinates in a two dimensional space, your example is a square. You would determine this by testing that the difference of x and y values are equal. Code might be:

def square(sq):
    delta_x = sq[1][0] - sq[0][0]
    delta_y = sq[1][1] - sq[0][1]
    return delta_x == delta_y

Upvotes: 0

Bartlomiej Lewandowski
Bartlomiej Lewandowski

Reputation: 11170

You pass a list of lists as a parameter. The example you gave is [[5,6],[7,8]].

Let's step to see what your code does with this input.

for element in sq:
     if element:
         return False
     return True

Let's start with the for loop:

for element in sq:

This loops through your list, so the first iteration your element is [5,6] and the next [7,8].

The next thing that your code does is check if the element is True. A list is true if it's not empty. Therefore on the first iteration your code returns False.

An example input where your code would return True would be [[],[]].

To check if a matrix is square, you want to see if all the list dimensions are the same. Something along these lines:

def square(sq):
    rows = len(sq)
    for row in sq:
        if len(row) != rows:
            return False
    return True

Upvotes: 2

Hyperboreus
Hyperboreus

Reputation: 32429

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.

Upvotes: 8

Related Questions