archive

[leetCode] Most Common Word (Python) 본문

STUDY/알고리즘

[leetCode] Most Common Word (Python)

seonyounggg 2021. 2. 2. 22:38

✏️ 문제

 

Most Common Word - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

✏️ 풀이

문제 조건대로 소문자로 치환하고 특수문자들을 replace함수를 통해 제거해주었다.

testcase 중에 'b,b,b' 같은 형태가 있기 때문에 빈문자열로 치환하면 'bbb'와 같이 한 단어로 인식되기 때문에 공백으로 치환하여 split() 함수에서 다른 단어로 처리되도록 했다.

해당 문자열을 키로 가지고 빈도 수를 값으로 가지는 딕셔너리를 생성하여,

가장 큰 값의 키를 반환하였다.

✏️ 코드

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        # 전처리
        paragraph = paragraph.lower().replace('.',' ').replace(',',' ').replace('!',' ').replace("'",' ').replace(';',' ').replace('?',' ')
        
        count = {}
        for i in paragraph.split():
            if i in banned:
                continue
            elif i in count:
                count[i] = count[i] + 1
            else:
                count[i] = 1
        
        max = ""
        max_cnt = 0
        for i in count:
            if count[i] > max_cnt:
                max_cnt = count[i]
                max = i
                
        return max

✏️ 다른 사람 풀이

class Solution:
    def mostCommonWord(self, 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]

전처리를 좀 더 편하게 하기 위해 정규식을 사용할 수 있다.

\w는 단어 문자를 뜻하고 ^는 not을 뜻한다.

즉, 단어 문자가 아닌 것들은 두번째 인자인 공백으로 대체된다. 이를 소문자로 치환하고 공백을 기준으로 나눈다. 

이 리스트에 대해 리스트 컴프리헨션을 이용해서, banned 리스트에 없는 요소만 words 리스트에 최종적으로 저장한다.

 

앞서 내 코드에서 딕셔너리에 담을 때 key값이 존재하는 지 확인하는 부분을 생략하고 다음과 같이 개선할 수 있다.

counts = collections.defaultdict(int)
for word in words:
	counts[word] += 1
    
return max(counts, key=count.get)

defaultdict를 사용하여 int 기본값인 0이 부여되도록 하고,

value가 max인 key를 얻어오기 위해서 위와 같이 max 함수에 key를 지정하여 얻어올 수 있다.

 

이 때 Counter모듈을 사용하면 좀 더 깔끔하게 처리할 수 있다.

# Count 모듈 사용 예시
>>> import collections
>>> words = ['a', 'a', 'b']
>>> counts = collections.Counter(words)
>>> counts
Counter({'a': 2, 'b': 1})
>>> counts.most_common(1)
[('a', 2)]

most_common(1) 로 빈도 수가 가장 높은 단어/빈도 수를 얻어온다.

이 중 단어를 추출하여 최종적으로 리턴한다.

(Couter클래스에 대해 정리하였다 -> seonyounggg.tistory.com/102)

✏️ 생각

정규식이 은근 쓰임새가 많은 거 같다. 정리해둬야겠다!

Comments