https://leetcode.com/problems/most-common-word
Most Common Word - LeetCode
Can you solve this real interview question? Most Common Word - 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 tha
leetcode.com
요약 : 금지된 단어를 제외하고, 최빈출 단어 찾기
기본 로직
1. 문장을 단어로 구분하면서 깨끗한 단어(',' 등이 없는)로 만들어 준다.
2. 중복되는 단어의 갯수를 카운트 한다.
3. 금지된 단어를 제외한다.
4. 최빈출 단어를 리턴한다.
코드는 다음과 같다.
# https://leetcode.com/problems/most-common-word/
from collections import Counter
import re
import itertools
def mostCommonWord(paragraph, banned) :
# 공백으로 단어 구분
# 소문자로 바꾼 것을 알파벳 이외의 문자로 split 한다
onlyWord = [re.split('[^a-z]', x.lower()) for x in paragraph.split()]
# 이중배열을 풀어주고 중복 단어의 갯수를 카운트
counter = Counter(itertools.chain(*onlyWord))
# split 때문에 생긴 빈 문자열은 무시해야한다
banned.append('')
# 금지된 단어는 지워준다
for b in banned:
del counter[b]
# 최빈 단어를 리턴한다
return counter.most_common(1)[0][0]
개선한다면…
나중에 for문으로 금지된 단어를 지우는 것이 아닌, 리스트 컴프리헨션에 if 조건을 추가하면 더 코드가 간결해진다.
onlyWord = [re.split('[^a-z]', x.lower())
for x in paragraph.split()
if x not in banned]
Counter와 most_common을 사용하지 않고,
max를 사용하면 더 간결하다
max(list, key = list.count)
⇒ 리스트에서 각 단어의 count를 기준으로 최댓값을 찾기
+++
정규표현식을 쓸 때 문자열 앞에 r을 붙이기
https://docs.python.org/ko/3/howto/regex.html#the-backslash-plague
'알고리즘' 카테고리의 다른 글
[leetcode/python] 42번 Trapping Rain Water (0) | 2023.04.13 |
---|---|
[python/leetcode] 49번 group anagrams 문제 풀이 (0) | 2023.03.03 |
[python/leetcode] 937번 reorder log files 문제 풀이 (0) | 2023.03.03 |
[python/leetcode] 344번 Reverse String 문제 풀이 (0) | 2023.03.02 |
[python/leetcode] 125번 valid-palindrome 문제 풀이 (0) | 2023.03.02 |