wkovac
wkovac

Reputation: 1

Counting null rows and columns

I trying to find out how many rows and columns in a matrix have all elements equal to zero. I don't know if my solution is the most elegant one so I'd like to know you opinion.

What I did was use two lists that register which are the non null rows and columns and at the end I print the total number of rows and columns minus those on the lists.

What's bothering me the most is the if statements I had to use.

def apenas_zeros(matriz):
    linha = len(matriz)
    coluna = len(matriz[0])

    linha_cheia = []
    coluna_cheia = []
    for i in range(linha):
        for k in range(coluna):
            if matriz[i][k] != 0:
                if i not in linha_cheia and k not in coluna_cheia:
                    linha_cheia.append(i)
                    coluna_cheia.append(k)
                elif k not in coluna_cheia:
                    coluna_cheia.append(k)
                elif i not in linha_cheia:
                    linha_cheia.append(i)
    print ("Linhas nulas:", linha - len(linha_cheia))
    print ("Colunas nulas:", coluna - len(coluna_cheia))  

Upvotes: 0

Views: 148

Answers (1)

Stef
Stef

Reputation: 30669

If matriz is a numpy array, you could simply do

print("Linhas nulas:", sum(~matriz.any(axis=1)))
print("Colunas nulas:", sum(~matriz.any(axis=0))) 

(your code yields the same result)

Explanation:
any is True if any element in the given axis is non-zero. ~ just negates this value, i.e. it's True if all elements are zero. True is 1 and False is 0, so counting the Trues is just doing the sum.


If your matriz is a list of lists you can convert it to a numpy array by:

import numpy as np
matriz = np.array(matriz)


Numpy also has a built-in function count_nonzero for counting non-zeros. Using it comes close to your algorithm:

print("Linhas nulas:", matriz.shape[0] - np.count_nonzero(np.count_nonzero(matriz, axis=1)))
print("Colunas nulas:", matriz.shape[1] - np.count_nonzero(np.count_nonzero(matriz, axis=0))) 

Upvotes: 1

Related Questions