책읽기

[파이썬 알고리즘 인터뷰][문자열] 가장 흔한 단어 (중요)

pythaac 2021. 7. 16. 13:05
이 글은 "파이썬 알고리즘 인터뷰 (박상길 지음)"을 읽고 주관적으로 요약한 글입니다. 

출처 : https://www.onlybook.co.kr/entry/algorithm-interview

 

문제 정의

  1. 금지 단어 제외
  2. 대소문자 구분하지 않음
  3. 구두점(마침표, 쉼표 등) 무시

 

책에서 구현된 코드

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 같은 표현 기억이 잘 안남
  • 리스트 컴프리헨션 활용
    • 특정 조건의 리스트를 만들고 싶을 때 컴프리헨션을 활용하면 좋을듯
  • dictionary의 key
    • dict[0][0]
      - dictionary의 첫 번째 요소의 key
  • r-string
    • raw string
print("hi\n")
# hi

print(r"hi\n")
# hi\n

 

내가 구현한 코드

import re, collections

def most_common_word(s:str, banned:list[str]) -> str:
    s = s.lower()
    s = re.sub("[^a-z ]", " ", s)
    dict_cnt = collections.Counter(s.split())
    for k, v in dict_cnt.most_common():
        if k not in banned:
            return k
  • regex를 깔끔하게 썼으면 좋겠음
  • s = 이 두 line으로 나눠지는 것이 가독성이 좋은 것인지 고민해볼 필요 있음
  • for문이 지저분함 (key를 뽑기 위해 이런 표현을 해야하는지?)