[알고리즘] 가장 흔한 단어

June·2021년 1월 16일
0

알고리즘

목록 보기
14/260

가장 흔한 단어

내 풀이

def mostCommonWord(paragraph: str, banned: List[str]) ->str:
    word_dict = collections.defaultdict(int)
    for word in str(paragraph.lower().split()).split(","):
        word = re.sub('[^a-z0-9]', '', word)
        if len(word) > 0:
            word_dict[word] +=1

    max_count, max_word = -1, None
    for key, value in word_dict.items():
        if key not in banned and value > max_count:
            max_count = value
            max_word = key

    return max_word

처음에는 그냥 공백을 기준으로 split하고, 정규식을 이용해서 alphanumeric한 것만 딕셔너리에 담고, 그 딕셔너리에서 가장 큰 value를 찾을 때마다 max_word 를 갱신하려했다. 하지만 문제에서 print(mostCommonWord("a, a, a, a, b,b,b,c, c", ["a"]))
와 같은 반례가 존재했다. 따라서 공백을 기준으로 스플릿하고, 또 쉼표를 기준으로 스플릿했다. 그러니 '' 빈 문자열이 들어가는 문제가 생겼고, 빈 문자열이 아닐 때 사전에 추가하게 수정했다.

책 풀이

def mostCommonWord(paragraph: str, banned: List[str]) ->str:
    words = [word for word in re.sub(r'[^\w]', ' ', paragraph).lower().split() if word not in banned]

    counts = collections.Counter(words)
    return counts.most_common(1)[0][0]

정규식에서 ''로 대체하는 것이 아니라 ' '로 대체하였다. 이러면 공백을 기준으로 split하면 없어진다. 정규식에서 \w는 단어 문자를 의미한다.

counts = collections.Counter(words)
return counts.most_common(1)[0][0]

words에서 가장 흔하게 등장하는 단어의 첫 번째 값을 most_common(1)으로 추출한다. 문제의 입력값에서는 [('ball',2)]가 되며, 이 값의 [0][0]을 추출해서 최종적으로 첫 번째 인덱스의 키를 추출하게 된다.

0개의 댓글