본문 바로가기

Algorithm/파이썬 알고리즘 인터뷰 스터디

[문자열 조작] 04 가장 흔한 단어(Most Common Word)

<LeetCode 문제>

https://leetcode.com/problems/most-common-word/

 

Most Common Word - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하는 문제입니다.

이때, 대소문자 구분을 하지 않으며 구두점(마침표, 쉼표 등)은 무시합니다.

<풀이>

입력값에 대소문자가 섞여있고, 쉽표 등 구두점이 존재하므로 입력값에 대한 전처리 작업이 필요합니다.

정규식을 통해 편리하게 처리할 수 있습니다.

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        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]

 

Counter객체를 통해 개수를 깔끔하게 처리했습니다.

 

defaultdict()를 사용해 개수를 세어줄 수도 있습니다.

딕셔너리 변수에서 값이 가장 큰 키를 가져올 때, max함수에 key를 지정해 argmax를 간접적으로 추출합니다.

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        words =[word for word in re.sub(r'[^\w]',' ',paragraph).lower().split() if word not in banned]
        counts = collections.defaultdict(int)
        for word in words:
            counts[word] += 1
        return max(counts,key=counts.get)

 

<학습내용>

1. 정규식에서 \w는 단어 문자를 뜻하며, ^는 not을 의미한다.
2. 딕셔너리 변수에서 값이 가장 큰 키를 가져올때, max 함수에 key로 get함수를 넣어서 가져온다.
3. defaultdict(int)는 기본값이 0이다. int가 아닌 list와 set은 기본값이 []와 ()이다.
4. Counter객체를 통해 항목의 개수를 셀 수 있다.
5. Counter객체에 most_common(1)로 가장 많이 등장하는 항목을 추출할 수 있다.

<학습이 필요한 내용>

1. 정규식(문자만 남기기, 문자와숫자만 남기기)

 

https://github.com/HoYoungChun/Algorithm_PS/blob/master/String/LC_819.py

 

GitHub - HoYoungChun/Algorithm_PS: Baekjoon Online Judge, Programmers, LeetCode problem solving by Python, C++

Baekjoon Online Judge, Programmers, LeetCode problem solving by Python, C++ - GitHub - HoYoungChun/Algorithm_PS: Baekjoon Online Judge, Programmers, LeetCode problem solving by Python, C++

github.com