How to count occurrences of a number in a matrix?

Asked

Viewed 36 times

0

I need to do a function that counts how many times a number appears in a matrix, example:

ocorrencias(9,[[9,7,6,9,8,8]])

Must return 2

My code:

def ocorrencias(numero,matriz):
    cont = 0
    for elemento in matriz:
        if elemento == num:
            cont += 1
    return cont

I am getting an error giving error when there is more than one list in the matrix.

  • 1

    Marcos, you’re almost there. I don’t want to solve your exercise for you and harm your learning, but the answer to your problem lies in your own question. When you have more than one list in the matrix, each "element" of your matrix is a list. You first need to iterate each of the lists and then, for each list, you need to iterate each element. That is, you need two nested loops to solve your problem.

  • Got it here! Brigadeo

  • Mark, feel free to post your own reply.

  • Post your answer that in sequence we will post optimized versions.

No answers

Browser other questions tagged

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