[LeetCode][Python3]#819.Most Common Word

Carvin·2020년 7월 24일
0

819. Most Common Word

문제

Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique.

Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.

예시

Input:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
Output: "ball"

풀이

# import re
class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        # paragraph = re.sub(r'[-=+,#/;\?:^$.@*\"※~&%ㆍ!』\\‘|\(\)\[\]\<\>`\'…》]', ' ', paragraph)
        # words = paragraph.lower().split()
        proc_paragraph = ''.join([' '.join(map(lambda x : x if x.isalnum() | x.isspace() else ' ', word)) for word in list(paragraph)])
        words = proc_paragraph.lower().replace('  ',' ').split()
        count = {}
        for word in words:
            if word in banned:
                continue
            count[word] = count.get(word, 0) + 1
            
        res = sorted(count.items(), key = lambda item: item[1], reverse = True)[0][0]
      
        return res

주어진 문장에서 금지된(banned) 단어를 제외하고 가장 빈도수가 높은 단어를 뽑는 문제이다. 먼저, 해야할 것은 문장에 속한 특수문자를 제외하는 것이라고 생각했다. 처음에는 정규표현식 모듈인 re를 사용해서 문제를 해결할 수 있었다.

하지만 어떤 특수문자가 문장에 포함될지 모른다는 것을 고려해야하기 때문에 위와 같이 다른 방법으로 해결해 보았다.

주어진 문장에서 특수문자를 제거하고 다시 문장으로 만드는 과정이 proc_paragraph에 할당하는 과정이다. 여기서 isspace() 공백을 True로 리턴해주는 메소드를 사용한 이유는 문장에서 단어는 공백으로 구분되는 것을 적용해주기 위해서 이고, 특수문자를 ' '를 공백으로 대체해준 것은 'b|b', 'a,b'와 같이 특수문자로 글자를 구분하는 경우가 있기 때문이다.

다음으로 금지된 단어 리스트에 속하지 않는 단어의 빈도수를 구하고, 정렬하여 답을 구할 수 있다.

결과

47 / 47 test cases passed.
Status: Accepted
Runtime: 48 ms
Memory Usage: 13.8 MB

추가

다른 분의 풀이를 보게 되면, ord() 내장함수를 사용해서 특수문자를 제거하는 과정을 볼 수 있었다. 훨씬 깔끔하기도 하고 다른 풀이에도 사용할 수 있겠다 싶었다.

  • ord() : 문자를 아스키코드로 반환해주는 함수이다.
  • chr() : 아스키코드를 문자로 반환해주는 함수이다.

다음은 아스키코드표이다. 한글은 찾지 못했지만 ord(ㄱ) -> 12593, ord(ㅎ) -> 12622 이다.

출처 : https://lsjsj92.tistory.com/201

0개의 댓글