Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.
The words in paragraph are case-insensitive and the answer should be returned in lowercase.
import re
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
#List words in paragraph, replacing punctuation with ' ' and all lower case
paragraph = re.subn("[.,!?;']", ' ', paragraph.lower())[0].split(' ')
#Remove any '' or words in banned from paragraph list
paragraph = list(filter(lambda x: x not in banned + [''], paragraph))
#Return most common word in filtered list
return Counter(paragraph).most_common(1)[0][0]
Top comments (0)