LEETCODE - Most-Common-Word

import re
import collections
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.defaultdict(int)
    for word in words:
        counts[word] += 1
    return max(counts, key = counts.get)

def mostCommonWord2(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]

# 정규표현식 ^ = NOT, \w = 단어
# most_common()

좋은 웹페이지 즐겨찾기