Function does not work in all test cases

Asked

Viewed 34 times

0

I need to do a function to check if a matrix is square:

    def eh_quadrada(matriz):
        '''Função que verifica se uma matriz é quadrada.
        list->bool'''
        if len(matriz)==len(matriz[0]):
            return True

        else:
            return False

This code only does not work when the input matrix is empty: [[]].

What I could do when the input was an empty matrix, for this code to work?

1 answer

1


First of all, [[]] is not empty: this is a list that has an element (and this element is an empty list).

Then just check this condition, ie the size of the matrix is 1 and the size of the first element is zero.

Another detail is that it is useless to check only the first row of the matrix. Because if I have something like this:

matriz = [
  [1, 2],
  [3]
]

Your function will return True, because you are not checking from the second line onwards. To make sure that the matrix is square you need to check all lines:

def eh_quadrada(matriz):
    # caso especial de matriz "vazia"
    if len(matriz) == 1 and len(matriz[0]) == 0:
        return True
    # todas as linhas devem ter o mesmo tamanho da matriz 
    return all(len(matriz) == len(linha) for linha in matriz)

all checks whether all elements satisfy the condition (which in this case is the same size as the matrix). If any of them have different size, returns False.

  • Kinda off, but I’ll ask myself. D What have you gone through for all? It’s like a comprehensilist on implicit? This is the first time I’ve seen it. I know that all expecting a iterable, then Python can understand that it is, in fact, a iterable?

  • 1

    @Luizfelipe It is a Generator Expression - is similar to list comprehension (read the link, which explains everything) :-)

  • 1

    @Luizfelipe Related to the subject: https://answall.com/a/193625/112052

Browser other questions tagged

You are not signed in. Login or sign up in order to post.