1 回答
TA贡献1779条经验 获得超6个赞
我会做这样的事情:
def most_frequent(words, limit):
frequencies = words.items()
inverse = {}
for word, frequency in frequencies:
inverse.setdefault(frequency, []).append(word)
result = {}
remaining = limit
for frequency in sorted(inverse.keys(), reverse=True):
if len(inverse[frequency]) <= remaining:
result.update({word: frequency for word in inverse[frequency]})
remaining -= len(inverse[frequency])
else:
break
return result
print(most_frequent({'cat': 3, 'dog': 3, 'pig': 3, 'bee': 3, 'rat': 1}, 4))
print(most_frequent({'cat': 3, 'dog': 3, 'pig': 3, 'bee': 2, 'rat': 2}, 4))
print(most_frequent({'cat': 3, 'dog': 3, 'pig': 3, 'bee': 3, 'rat': 1}, 3))
输出
{'bee': 3, 'dog': 3, 'pig': 3, 'cat': 3}
{'dog': 3, 'pig': 3, 'cat': 3}
{}
这个想法是创建一个倒排字典(inverse),其中键是频率,值是具有该频率的单词列表,然后您可以按非升序迭代频率,并将单词列表添加到最终结果中如果剩余预算允许。
添加回答
举报