Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize this Python code?

def maxVote(nLabels):
    count = {}
    maxList = []
    maxCount = 0
    for nLabel in nLabels:
        if nLabel in count:
            count[nLabel] += 1
        else:
            count[nLabel] = 1
    #Check if the count is max
        if count[nLabel] > maxCount:
            maxCount = count[nLabel]
            maxList = [nLabel,]
        elif count[nLabel]==maxCount:
            maxList.append(nLabel)
    return random.choice(maxList) 

nLabels contains a list of integers.

The above function returns the integer with highest frequency, if more than one have same frequency then a randomly selected integer from them is returned.

E.g. maxVote([1,3,4,5,5,5,3,12,11]) is 5

like image 279
RandomVector Avatar asked Jul 30 '26 06:07

RandomVector


1 Answers

import random
import collections

def maxvote(nlabels):
  cnt = collections.defaultdict(int)
  for i in nlabels:
    cnt[i] += 1
  maxv = max(cnt.itervalues())
  return random.choice([k for k,v in cnt.iteritems() if v == maxv])

print maxvote([1,3,4,5,5,5,3,3,11])
like image 173
Ignacio Vazquez-Abrams Avatar answered Aug 01 '26 19:08

Ignacio Vazquez-Abrams