Solution
from collections import defaultdict
from typing import List
class Solution:
# ๊ฐ์ฅ ๋ง์ ๋จ์ด๋ฅผ ์ถ๋ ฅํ๋ ๋ฌธ์
# ๋์ banned์ ํฌํจ๋์ด ์๋ ๋จ์ด๋ค์ ์ ์ธํจ
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
count_dic = defaultdict(int)
split_paragraph = paragraph.replace('!', ' ').replace('?', ' ').replace("'", ' ').replace(',', ' ').replace(
';', ' ').replace(".", ' ').lower().split()
# ๋งต ๋ง๋ค๊ธฐ
for s in split_paragraph:
count_dic[s] += 1
while True:
max_key = max(count_dic, key=count_dic.get)
# ๊ธ์ง ๋จ์ด๊ฐ ํฌํจ์ด ์ ๋์ด ์์ผ๋ฉด -> ๊ทธ๋ฅ ๋ฆฌํด
if max_key not in banned:
return max_key
# ๊ธ์ง ๋จ์ด์ ํฌํจ๋ผ ์์ผ๋จผ -> ๋ค์ while๋ฌธ ๋๋ฉด์ ๋์
๋๋ฆฌ ์ ๊ฑฐ
count_dic.pop(max_key)
print(Solution().mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"]))
Another Solution
- r์ raw string์ ์๋ฏธํฉ๋๋ค. ์ด๋ ๋ฌธ์์ด์์ ๋ฐฑ์ฌ๋์๋ฅผ ์ผ๋ฐ ๋ฌธ์๋ก ์ฒ๋ฆฌํ๋๋ก ์ง์ํ๋๋ฐ ์ฌ์ฉ๋ฉ๋๋ค.
- ์๋ฅผ ๋ค์ด,
\\
๋์ \
๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค. ์ด ๊ฒฝ์ฐ r'[^\w]'
๋ [^\w]
์ ๋์ผํฉ๋๋ค.
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
words = [word for word re.sub(r'[^\w]', ' ', paragraph)
.lower().split() if word not in banned]
counts = collections.Counter(words)
# (1): ๊ฐ์ฅ ์ฒซ๋ฒ์งธ max๊ฐ -> [0]: ์ฒซ๋ฒ์งธ ํํ -> [0]: ์ฒซ๋ฒ์งธ ์์
return counts.most_common(1)[0][0]
Leave a comment