Home > Back-end >  Return an element with the maximum number of occurrences in a given matrix
Return an element with the maximum number of occurrences in a given matrix

Time:02-04

I have written a function that takes a matrix and finds an element with the greatest number of occurrences in the matrix. If more than one such element exists, my function returns the list of all of them.

For example, if the input is:

matrix = [[0, 5, 1, 1, 0],
         [0, 2, 2, 2, 0],
         [1, 2, 4, 3, 1]]

The result will be [0, 1, 2]

My code is as follows:

def max_repeat_elem(matrix):
    from itertools import chain

    if not matrix:
        return None

    flatten_m = list(chain.from_iterable(matrix))
    diction = {}
    for i in flatten_m:
        occur = flatten_m.count(i)
        if occur not in diction:
            diction[occur] = [i]
        else:
            if i not in diction.get(occur):
                diction[occur].append(i)

    return diction.get(max(diction.keys()))

I think my code can be less costly than it is now. E.g. with a repeated element, the count function is called several times. How do I make the whole function less costly (even by using other data structures)?

CodePudding user response:

You can use Counter for that, e.g.:

matrix = [[0, 5, 1, 1, 0],
         [0, 2, 2, 2, 0],
         [1, 2, 4, 3, 1]]

import itertools
from collections import Counter

counts = Counter(itertools.chain.from_iterable(matrix))
[val for val, count in counts.items() if count == max(counts.values())]
  • Related