需要帮助来创建函数freqitems(S,p),该函数返回序列S中各项的排序列表,这些序列的出现频率至少为p%,并且没有重复项。示例输出应如下所示:

>>> freqitems([2,2,2,3],50)
[2]
>>> freqitems(5*["alpha"]+["beta"]+3*["gamma"]+7*["delta"], 25)
['alpha', 'delta']
>>> freqitems(5*["alpha"]+["beta"]+3*["gamma"]+7*["delta"], 33)
['delta']

最佳答案

yourlist = 5*["alpha"]+["beta"]+3*["gamma"]+7*["delta"]

def freqitems(sequence, p):
  import collections
  counter = collections.Counter(sequence)
  return sorted([k for k,v in counter.iteritems() if 100.*v/len(sequence) >= p])

print freqitems(yourlist, 25)
print freqitems(yourlist, 33)

09-07 02:58