본문 바로가기
Algorithm

(leetcode) Most Common Word

by 안자바먹지 2021. 1. 4.
728x90

금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라. 대소문자를 구분하지 않으며 마침표, 쉼표 또한 무시한다.

 

입력

paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."

banned = ["hit"]

 

출력

"ball"

 

 

 

from collections import Counter

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

데이터 클렌징을 위해 정규식을 사용하였다. \w 는 단어 문자를 뜻하고 ^는 not을 의미한다. 

리스트컴프리헨션의 조건절에는 banned에 포함되지 않은 단어만 대상으로 한다.

collections의 Counter 객체를 사용하여 most_common(1)로 가장 흔하게 등장하는 값을 찾는다. (most_common에 인자를 넘기지 않으면 내림차순으로 정렬된 값이 출력된다.)

most_common(1)로 추출한 값은 [('ball', 2)] 이기 때문에 counts.most_common(1)[0][0] 으로 원하는 값을 출력한다.

728x90

'Algorithm' 카테고리의 다른 글

(카카오) 무지의 먹방 라이브 - javascript  (0) 2021.01.05
(leetcode) Group Anagrams  (0) 2021.01.04
(leetcode) Reorder Data in Log Files  (0) 2021.01.04
(leetcode) Valid Palindrome  (0) 2021.01.04
(백준) 10539번 : 수빈이와 수열  (0) 2019.10.07

댓글