leetcode.com/problems/most-common-word/
<문제>
Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.
<예시>
Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." banned = ["hit"]
Output: "ball"
from collections import Counter, defaultdict
import re
def solution_1(paragraph: str, banned: list):
new_paragraph = ''
new_paragraph_list = []
# 전처리 과정
# 문자를 제외한 나머지 제거 (정규식 사용해도 된다)
for ch in paragraph:
if ch.isalpha() or ch == ' ':
new_paragraph += ch.lower()
else:
new_paragraph += " "
# banned에 포함된 단어 제거
for word in new_paragraph.split():
if word not in banned:
new_paragraph_list.append(word)
counter = Counter(new_paragraph_list)
return counter.most_common(1)[0][0]
def solution_2(paragraph: str, banned: list):
paragraph = re.sub('[^a-zA-Z]', ' ', paragraph)
word_count_dict = defaultdict(int)
for word in paragraph.split():
word = word.lower()
if word not in banned:
word_count_dict[word] += 1
word_count_dict = sorted(word_count_dict.items(), key=lambda x:x[1], reverse=True)
return word_count_dict[0][0]
<알게된 것>
* defaultdict
- 인자로 주어진 객체의 기본값을 딕셔너리 value의 초기값으로 지정할 수 있다.
- ex1) defaultdict(int)
- ex2) defaultdict(list)
- 따라서 다음과 같이 word_count_dict[word] += 1 의 코드를 작성할 수 있는 것이다.
- python 기본 딕셔너리 사용하면 key가 존재하지 않으면 따로 key를 삽입하는 과정을 명시해주어야 한다.
* Counter
- 컨테이너 속 값들을 key로, 값들의 개수를 value로 설정한 객체를 생성한다.
- 리스트 내 원소의 개수를 파악할 때 유용하게 사용된다.
- 위의 코드에서도 각 단어의 빈도를 세기 위하여 Counter를 사용하였다.
- most_common 메서드를 사용하면 value 기준 상위 N개의 key를 추출해준다.
* re.sub
- x = re.sub("[^a-zA-Z]", " ", x)
- a~z, A~Z를 제외한 모든 문자를 공백으로 바꾸어 준다.
'다전공_컴퓨터공학 > 알고리즘 문제풀이' 카테고리의 다른 글
[파이썬 알고리즘] 6장 - 문자열 조작 (longest palindrome substring) ⭐ (0) | 2020.11.03 |
---|---|
[파이썬 알고리즘] 6장 - 문자열 조작 (group anagrams) (0) | 2020.11.03 |
[파이썬 알고리즘] 6장 - 문자열 조작 (recorder log files) (0) | 2020.11.02 |
[파이썬 알고리즘] 6장 - 문자열 조작 (valid palindrome) (0) | 2020.11.02 |
[파이썬 알고리즘] 4장 - 자료형 (0) | 2020.10.31 |