Python
파이썬 알고리즘 인터뷰 - 04. 가장 흔한 단어
s코딩초보s
2022. 1. 10. 22:04
<--- 리트코드 819. Most Common Word --->
# 문제: 금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라. 대소문자 구분을 하지 않으며, 구두점(마침표, 쉼표 등) 또한 무시한다.
입력
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." banned = ["hit"] |
출력
"ball" |
# 풀이
1. 리스트 컴프리헨션, Counter 객체 사용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import collections
import re
def most_common_word(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]
paragraph = input()
banned = input()
print(most_common_word(paragraph, banned))
|
cs |