1
votes

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
5
what is your code supposed to do? - Bartlomiej Lewandowski
When is a matrix square? - Hyperboreus
A 2x2 matrix is square by definition, since the number of rows equals the number of columns. - Emmet
@Hyperboreus when the number of rows and the number of columns is the same - Two-Bit Alchemist
Of course not, as soon as you give it something valid with a valid element that comes before any invalid elements, it's going to return false. - Joe

5 Answers

7
votes

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.

2
votes

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
2
votes

given m is a numpy matrix and you have imported numpy

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

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
0
votes

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