Skip to content

Commit ed1af00

Browse files
committed
Most Common Word
1 parent aea3928 commit ed1af00

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Most Common Word.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Given a paragraph and a list of banned words, return the most frequent word that is not in the
2+
# list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
3+
#
4+
# Words in the list of banned words are given in lowercase, and free of punctuation.
5+
# Words in the paragraph are not case sensitive. The answer is in lowercase.
6+
7+
# Input:
8+
# paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
9+
# banned = ["hit"]
10+
# Output: "ball"
11+
# Explanation:
12+
# "hit" occurs 3 times, but it is a banned word.
13+
# "ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
14+
# Note that words in the paragraph are not case sensitive,
15+
# that punctuation is ignored (even if adjacent to words, such as "ball,"),
16+
# and that "hit" isn't the answer even though it occurs more because it is banned.
17+
18+
import collections
19+
20+
21+
class Solution:
22+
def mostCommonWord(self, paragraph, banned):
23+
for c in "!?',;.":
24+
paragraph = paragraph.replace(c, " ")
25+
dict = collections.Counter(paragraph.lower().split())
26+
27+
ans = ""
28+
num = 0
29+
for word in dict:
30+
if dict[word] > num and word not in banned:
31+
ans = word
32+
num = dict[word]
33+
34+
return ans

0 commit comments

Comments
 (0)