<--- 리트코드 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 |
'Python' 카테고리의 다른 글
파이썬 알고리즘 인터뷰 - 06. 가장 긴 팰린드롬 부분 문자열 (0) | 2022.01.10 |
---|---|
파이썬 알고리즘 인터뷰 - 05. 그룹 에너그램 (0) | 2022.01.10 |
파이썬 알고리즘 인터뷰 - 03. 로그파일 재정렬 (0) | 2022.01.05 |
파이썬 알고리즘 인터뷰 - 02. 문자열 뒤집기 (0) | 2022.01.05 |
파이썬 알고리즘 인터뷰 - 01. 유효한 팰린드롬 (0) | 2022.01.05 |