4. Most Common Word

아현·2021년 3월 7일
0

Algorithm

목록 보기
5/400

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


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]
        
  • 데이터 클렌징
    : 입력 값에 대한 전처리 작업

    • 정규식 사용
      \w는 단어문자(word character)를 의미하며, ^은 not을 의미한다

    • 위 코드의 정규식은 단어 문자가 아닌 모든 문자를 공백으로 치환
  • word에는 소문자, 구두점을 제외하고 banned를 제외한 단어 목록이 저장된다.

  • defaultdict() 를 사용해 int를 기본 값으로 부여

    • 키 존재 유무와 상관 없이 즉시 counts[word] += 1을 할 수 있다.
  • 개수를 처리하는 부분은 Counter 모듈을 사용한다.

    • most_common(1) 로 가장 흔하게 등장하는 단어의 첫번째 값을 추출한다.
profile
Studying Computer Science

0개의 댓글