상세 컨텐츠

본문 제목

[파이썬 알고리즘 인터뷰] 가장 흔한 단어 | 정규표현식 re.sub(), Counter

Coding Test/문제풀이

by yooputer 2023. 5. 31. 09:07

본문

박상길, 『파이썬 알고리즘 인터뷰』를 정리한 내용입니다.

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

 

Most Common Word - LeetCode

Can you solve this real interview question? Most Common Word - Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and tha

leetcode.com


문제 요약

문장이 주어질 때, 금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라.

단, 대소문자는 구분하지 않으며 구두점(마침표, 쉼표)는 무시한다.


핵심 전략

  • 정규표현식을 사용해 숫자 혹은 소문자가 아닌 문자를 공백으로 치환한다.
  • 금지된 단어를 제거한다.
  • Counter를 사용해 단어들의 빈도수를 구한다.

정규표현식

https://docs.python.org/3/library/re.html

 

re — Regular expression operations

Source code: Lib/re/ This module provides regular expression matching operations similar to those found in Perl. Both patterns and strings to be searched can be Unicode strings ( str) as well as 8-...

docs.python.org

정규표현식 [^\w]는 (a~z, A~Z, 0~9, _)에 속하지 않는 문자열의 집합이라는 뜻이다.


소스코드

class Solution:
    def mostCommonWord(self, paragraph: str, banned: [str]) -> str:
        words = [word for word in re.sub(r'[^\w]', ' ', paragraph.lower()).split()
                 if word not in banned]

        return Counter(words).most_common(1)[0][0]

소문자로 변환하고 알파벳만 추출하고 금지된 단어를 필터링하는걸 한줄로 끝내다니... 

가장 빈도수가 높은 단어를 구하는걸 한줄로 끝내다니...

파이썬 지린다...

관련글 더보기