[파이썬 알고리즘 인터뷰] 가장 흔한 단어
2020. 12. 24. 17:48ㆍ노트/Algorithm : 알고리즘
# 4. 가장 흔한 단어
금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라. 대소문자 구분을 하지 않으며, 구두점(마침표, 수미표 등) 또한 무시한다
* 입력:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
* 출력
"ball"
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
import re
import collections
def common_word(paragraph):
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]
common_word(paragraph)
>>> "hit"
'노트 > Algorithm : 알고리즘' 카테고리의 다른 글
[파이썬 알고리즘 인터뷰] 가장 긴 팰린드롬 부분 문자열 (0) | 2020.12.28 |
---|---|
[파이썬알고리즘 인터뷰] 그룹 애너그램 (0) | 2020.12.25 |
[파이썬 알고리즘 인터뷰] 로그파일 재정렬 (0) | 2020.12.11 |
[파이썬 알고리즘 인터뷰] 문자열 뒤집기 (0) | 2020.11.28 |
[파이썬알고리즘 인터뷰] 유효한 팰린드롬 구하기 (0) | 2020.11.28 |