如何优化这个Python代码?

Ran*_*tor 2 python algorithm data-structures

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) 
Run Code Online (Sandbox Code Playgroud)

nLabels 包含整数列表.

上面的函数返回具有最高频率的整数,如果多于一个具有相同的频率,则返回从它们中随机选择的整数.

例如maxVote([1,3,4,5,5,5,3,12,11])5

Ign*_*ams 6

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])
Run Code Online (Sandbox Code Playgroud)

  • 排序是"O(n log n)"; 你只需要最大值,即'O(n)`:) (3认同)

Sil*_*ost 5

在Python 3.1或未来的2.7中,您将能够使用Counter:

>>> from collections import Counter
>>> Counter([1,3,4,5,5,5,3,12,11]).most_common(1)
[(5, 3)]
Run Code Online (Sandbox Code Playgroud)

如果您无法访问这些版本的Python,您可以:

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i in nLabels:
    d[i] += 1


>>> max(d, key=lambda x: d[x])
5
Run Code Online (Sandbox Code Playgroud)