문제

문장이 주어지고 금지된 단어들을 제외하고 가장 많이 등장한 단어을 리턴해라!

예시

input

paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]

output

"ball"

풀이

book풀이1(36ms, 14mb)

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]

전처리

  • list comprehension 사용
  • \w 는 단어 문자를 뜻함. '^'은 not을 의미
  • ^\w -> ' ' : 단어 문자가 아닌 것을 공백으로 치환
  • 소문자로 바꾸고 공백으로 자름.
  • 그 안에서 banned에 없는 단어만 넣음.

딕셔너리

  • Counter는 리스트의 갯수를 딕셔너리로 만들어 줌.
  • most_common(1) = [('ball', 2)]
    가장 많이 있는 리스트의 원소를 나타냄

my풀이1(32ms, 13.9mb)

전처리는 책의 풀이를 가져다 사용

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]
    
        count_dict = {}
        for word in new_words:
            if word in count_dict.keys():
                count_dict[word] += 1
            else:
                count_dict[word] = 1
     	return(max(count_dict, key = lambda x: count_dict[x]))
profile
기록과 정리

0개의 댓글