금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라.
대소문자 구분을 하지 않으며, 구두점 또한 무시한다.
import collections
def mostCommonWord(paragraph, banned):
symbols = ["?", "'", ",", ";", ".", "!"]
for symbol in symbols:
paragraph = paragraph.replace(symbol, " ")
words = [x.lower() for x in paragraph.split()]
ret = []
for word in words:
for symbol in symbols:
word = word.replace(symbol, " ")
ret.append(word)
ret = [x for x in ret if x.lower() not in banned]
cnt = collections.Counter(ret)
return cnt.most_common(1)[0][0]
mostCommonWord("Bob. hIt, baLl", ["bob", "hit"])
['bob', 'hit', 'ball']
'ball'
02/08/2021 21:14 Accepted 44 ms 14.2 MB python3
import re
def mostCommonWord(paragraph, banned):
words = [word for word in re.sub(r'[^\w]', ' ', paragraph)
.lower().split()
if word not in banned]
counts = collections.Counter(words)
return counts.most_common(1)[0][0]
mostCommonWord("Bob. hIt, baLl", ["bob", "hit"])
'ball'
Accepted 32 ms 14.4 MB python3