How to optimize this Python code?
Posted
by RandomVector
on Stack Overflow
See other posts from Stack Overflow
or by RandomVector
Published on 2010-05-26T16:55:11Z
Indexed on
2010/05/26
17:11 UTC
Read the original article
Hit count: 227
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
© Stack Overflow or respective owner