자료구조와 알고리즘/🥑알고리즘

[알고리즘][문자열 조작] - 4. 가장 흔한 단어

얄루몬 2022. 2. 16. 21:42

 

📖이 포스팅은 '파이썬 알고리즘 인터뷰 - 박상길님'을 보고 작성되었습니다.


😎문제 : https://leetcode.com/problems/most-common-word/submissions/

 

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


[가장 흔한 단어]

리스트 컴프리헨션을 통해 이 문제를 해결했다.

import collections
import re

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]
        count = collections.Counter(words)
        return count.most_common(1)[0][0]

 

  •  words = [word for word in re.sub(r'[^\w]',' ',paragraph)
    • ^ = not
    • \w = word
    • ^\w 문장이 아닌 경우 빈 공백으로 바꾼다는 의미다. 

 

 

 

  • .lower().split()
    • 소문자로 덩어리째를 기준으로 해준다는 의미다

 

  • if word not in banned
    • 위의 조건을 다 만족한 뒤 banned(금지 단어)가 아닌 경우만 words에 넣어준다.

 

  • count = collections.Counter(words)
    • Counter 모듈은 [('단어', 단어 횟수)]로 돌려준다.

 

  • return count.most_common(1)[0][0]
    • most_common(1) = 가장 흔하게 등장하는 단어의 첫 번째 값을 추출해준다.
    • [0][0] 그 값의 키인 단어를 출력해준다.

 

 

 

 

 

[실행 속도 비교]

 

 

[리스트 컴프리헨션이란?]

https://wikidocs.net/22805

 

1) 리스트 컴프리헨션

## 리스트 생성하기 기존에 배운 문법으로 1부터 10까지 정수를 순서대로 가지고 있는 리스트를 생성하는코드는 다음과 같습니다. ``` numbers = [] for ...

wikidocs.net