Search code examples
pythonpython-3.xperformancecounter

Maximum Number of Occurrences of Any Item in Counter object / list


I have a grid filled with different colors (represented by differing integers). I would like to quickly (in one line and least amount of processing time) count the number of occurrences of all the colors and return the highest number of occurrences. Also, I want to ignore zeroes.

Here is my solution (can you think of a better one?):

grid = [[0, 0, 5, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 0, 0, 0], [0, 30, 30, 0, 33, 0, 0, 0, 0, 0, 0, 0, 0], [0, 30, 0, 0, 33, 33, 0, 0, 50, 0, 50, 0, 0], [0, 30, 0, 0, 33, 33, 0, 0, 50, 50, 50, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 0, 0], [0, 0, 0, 0, 0, 0, 0, 88, 88, 88, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 88, 88, 0, 0, 0, 0]]
rows,cols=len(grid),len(grid[0])
ctrSum=Counter()
for row in grid:
    ctrSum += Counter(row)
ctrSum -= Counter({0:(rows*cols)}) # subtract out a ridiculous amount of zeroes to eliminate them all from the counter
return max(ctrSum.values())

Solution

  • Since Pranav types faster than me, here is another potential answer to your problem:

    ans = max(Counter(x for row in grid for x in row if x!=0).values())
    

    I thought about irregular nested lists and this is what can do it:

    unfurl=lambda x: sum(map(unfurl,x),[]) if isinstance(x,list) or isinstance(x, tuple) else [x]
    ans = max(Counter(unfurl(grid)).values())