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 thatall
expecting a iterable, then Python can understand that it is, in fact, a iterable?– Luiz Felipe
@Luizfelipe It is a Generator Expression - is similar to list comprehension (read the link, which explains everything) :-)
– hkotsubo
@Luizfelipe Related to the subject: https://answall.com/a/193625/112052
– hkotsubo