Most Common Word

심현덕·2022년 5월 20일
0

코딩 테스트

목록 보기
4/6

Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.

The words in paragraph are case-insensitive and the answer should be returned in lowercase.

  1. lower case로 변환하기( Case sensitivity => 대소구분 x)
  2. 빈도가 가장 많은 Word 를 반환
  3. 단, banned word이면 따른 단어를 반환
코드를 입력하세요
class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        paragraph = paragraph.lower()
        paragraph = re.sub('[^a-z\s]',' ',paragraph)
        col = collections.Counter(paragraph.split()).most_common()
        for i in col:
            if not i[0] in banned:
                return i[0]
            

설명
1. 소문자로 변환.
2. 알파벳과 뛰어쓰기를 제외한 모든 단어를 ' '로 변환(중간에 뛰어쓰기 있어요)
3. counter의 most_common()을 사용해서 리스트 안의 튜플형식으로 변환[(단어, 빈도)...]
4. 반복문을 돌리면서 만약 밴리스트에 단어가 없다면 반환(리스트는 빈도순으로 정렬되기 떄문)

https://docs.python.org/ko/3/library/collections.html#collections.Counter
해당글을 참고!👍

profile
심현덕이에요

0개의 댓글