[LeetCode] 819 Most Common Word

kimwoody·2021년 10월 6일
0

문제

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

예제

  • 입력
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
  • 출력
"ball"

내 풀이

from typing import List
import re

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
    	# paragraph를 소문자로 바꿔주고 문자가 아닌 것들은 공백으로 replace한다
        # 그 결과를 split()해서 list_s 변수에 넣어준다
        list_s = re.sub('[^a-z ]', ' ', paragraph.lower()).split()
        dict_s = dict()
        
        # list_s 요소들의 중복을 제거한 후 각 요소를 key값으로 사용하는 dict를 만든다
        for ele in set(list_s):
            dict_s[ele] = 0
        # list_s를 순회하며 금지된 단어가 아니고 dict_s에 요소가 있으면 count를 올려준다
        for i in list_s:
            if i not in banned and i in dict_s:
                dict_s[i] += 1

        dict_max = max(dict_s, key=dict_s.get)

        return dict_max

나는 주어진 문자열에 대해서 대소문자 구분을 없애고 특수문자를 제거한 후에 list 자료형으로 바꿨다.
그 후에 리스트에서 중복을 제거하고 dict 자료형을 이용해서 각 단어의 개수를 파악했다. 그리고 가장 많이 나오는 단어를 return하는 방식으로 코드를 작성했다.

풀이1 - 리스트 컴프리헨션, Counter 객체 사용

from typing import List
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]
        print(words)
        
        counts = collections.Counter(words)
        print(counts)
        
        return counts.most_common(1)[0][0]

책에 나온 풀이를 보면 내 코드와 흐름은 비슷하다.
먼저 주어진 문자열을 리스트 컴프리헨션을 이용해서 대소문자구문 없애기, 특수문자 제거, 금지단어 제거를 한번에 진행했다.
그리고 Counter 객체를 사용해서 단어의 빈도수를 구하는 방식이다.


내 코드와 흐름은 비슷하지만 리스트 컴프리헨션과 Counter 객체의 사용으로 코드도 훨씬 깔끔하고 짧아진 모습이다.
다음엔 리스트 컴프리헨션과 collection과 Counter에 대해서 공부를 해봐야겠다.

0개의 댓글