How to check how many times the number 2 appears inside a matrix?

Asked

Viewed 74 times

-1

My goal in this algorithm is to find how many times the number 2 appears within an 8x3 matrix.

My result so far is like this:

from collections import Counter
import time
import numpy as np

m = int(input('Quantas linas? '))
n = int(input('Quantas colunas? '))

input("Será aceito somente números entre -20 e 10.\n ... \nPrecione a tecla ENTER para continuar!\n")
time.sleep(2)

matrizA = list()
for c in range(1, m + 1):
    linha = list()
    for i in range(1, n + 1):
        while True:
            try:
                valor = int(input(f'Digite o {i}º elemento da {c}ª linha: '))
                break
            except ValueError:
                print('\033[31mValor INVÁLIDO! Digite apenas valores inteiros!\033[m')
        linha.append(valor)
    matrizA.append(linha)

matriz = np.array(matrizA)
print(f'\033[32mA matriz gerada é:\n{matriz}\033[m')

c = Counter(matrizA)
print(c[2])

I managed to make the matrix and tried to use the import Counter to return the result of the repetition of the number 2 inside the matrix. However the result did not come out as I wanted.

3 answers

2

Your matrizA is actually a list of lists: it is a list in which each element is another list (and those yes have numbers).

Then just go through the "lines" (actually the lists), and then go through the elements of each line and see if the value is 2:

cont = 0
for linha in matrizA:
    for num in linha:
        if num == 2:
            cont += 1

But to get the count of a single element you can also use the method count:

cont = 0
for linha in matrizA:
    cont += linha.count(2)

And finally, you can use sum (adding a series of values) together with a Generator Expression, much more succinct and pythonic:

cont = sum(linha.count(2) for linha in matrizA)

1

You can use the library numpy, for example:

np.count_nonzero(matriz == 2)         

0

I don’t know much about Python libraries, but if your goal is just to find out how many times a certain number appears within an array, you can create the function below;

def Repete(matriz, identificador):
    repetiu = 0
    for indice in range(0, len(matriz)):
        repetiu+=1 if matriz[indice] == identificador else repetiu

    return repetiu

I hope it helped somehow.

Browser other questions tagged

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