티스토리 뷰

문제: 

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

 


풀이는 리스트 컴프리헨션과 Counter를 이용한다.

 

그렇게 어려운 문제는 아니다. 정규 표현식을 이용하여 단어가 아닌 모든 문자를 공백으로 치환한 뒤에 banned 리스트 내에 있는 단어를 제외한 단어의 리스트를 따로 만들어 주고, 그 개수를 세주기만 하면 끝난다.

 

import collections
import re
from typing import List


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


if __name__ == '__main__':
    paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
    banned = ["hit"]
    print(mostCommonWord(paragraph, banned))

>>>

[('ball', 2)]
ball

 

Count 객체의 mostCommonWord는 [('ball', 2)] 의 형태로 값을 반환하기 때문에 반드시 단어를 특정해줘야 한다.

 

Comments