大家好,我正在编写这个脚本,我需要更新一个字典words,其中最常用的单词仅限于limit.
from typing import List, Dict, TextIO, Tuple
def most_frequent(words: Dict[str, int], limit: int) -> None:
new_dict = {}
new_list = []
#I decided to create a list for easier sort
for w in words:
new_list.append((keys, words.get(w)))
new_list.sort(key=sorting, reverse=True)
#key=sorting: used to sort by the value of the key from big to small
for n_w in new_list:
if len(new_dict) < limit:
new_dict[n_w[0]] = n_w[1]
#this part add the words to a new dictionary up to the value of limit
words = new_dict
print(words)
#print just to check my result, I know it's supposed to return None
这是问题所在,我需要实现以下测试用例,其中:len(words) <= limit,如果添加了最常用的单词并导致结果,len(words) > limit则不添加任何单词;如果最后一个单词不是唯一的并且与下一个单词具有相同的值,则也不会添加任何一个。
>>> most_frequent({'cat': 3, 'dog': 3, 'pig': 3, 'bee': 3, 'rat': 1}, 4)
{'cat': 3, 'dog': 3, 'pig': 3, 'bee': 3}
#This one passes
>>> most_frequent({'cat': 3, 'dog': 3, 'pig': 3, 'bee': 2, 'rat': 2}, 4)
{'cat': 3, 'dog': 3, 'pig': 3}
#what I get {'cat': 3, 'dog': 3, 'pig': 3, 'bee': 2}, 'bee' doesn't get added because is tied with 'rat'
>>> most_frequent({'cat': 3, 'dog': 3, 'pig': 3, 'bee': 3, 'rat': 1}, 3)
{}
#what I get {'cat': 3, 'dog': 3, 'pig': 3}, none of them are added because there are 4 with high frequency but if they get added words > limit and it can't be
我觉得我现在使用的方法对于我需要的东西效率不高,而且我陷入了最后两种情况。我不允许使用模块,我应该使用什么方法?或者至少我可以在这里改进什么以获得我需要的东西?
哆啦的时光机
相关分类