Most Common Word LeetCode solution in Python

1
class Solution:
2
import string
3
from collections import Counter
4

5
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
6
# sunday morning hangover solution haha
7

8
# calling this twice seems unnecesary but whatevs
9
# replace "," with " " (apparently translate() is much quicker than replace)
10
para = paragraph.translate(str.maketrans(",", " "))
11
# strip out rest of punctuation and make it lower case
12
para = para.translate(str.maketrans(" ", " ", string.punctuation)).lower()
13
# split on the sapces
14
para = para.split()
15
# staple counter function
16
para_count = Counter(para)
17
# loop thru banned words, if they're in para_count pop the off
18
for word in banned:
19
if word in para_count:
20
para_count.pop(word)
21
# return val from most common
22
return para_count.most_common(1)[0][0]

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0