题目
设计一个方法,找出任意指定单词在一本书中的出现频率。
你的实现应该支持如下操作:
WordsFrequency(book)构造函数,参数为字符串数组构成的一本书
get(word)查询指定单词在数中出现的频率
示例:
WordsFrequency wordsFrequency = new WordsFrequency({"i", "have", "an", "apple", "he", "have", "a", "pen"});wordsFrequency.get("you"); //返回0,"you"没有出现过wordsFrequency.get("have"); //返回2,"have"出现2次wordsFrequency.get("an"); //返回1wordsFrequency.get("apple"); //返回1wordsFrequency.get("pen"); //返回1
题解
class WordsFrequency:
def __init__(self, book: List[str]):
self.dic = collections.Counter(book)
def get(self, word: str) -> int:
return self.dic[word]
Note
用 Counter库直接出统计列表单词生成字典,直接出结果。
