1

需要帮助创建函数 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']
4

1 回答 1

1
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)
于 2012-10-02T04:51:27.963 回答