파이썬 알고리즘 인터뷰 문제 4번(리트코드 819번) Most Common Word
https://leetcode.com/problems/most-common-word/
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
clean_text = re.sub("[^a-zA-Z\s]", " ", paragraph)
clean_text = clean_text.lower()
word_list = clean_text.split()
count_dict = dict()
for word in word_list:
if word in count_dict:
count_dict[word] += 1
else:
count_dict[word] = 0
count_list = list(sorted(count_dict.items(), key=lambda item: -item[1]))
for candi, freq in count_list:
if candi not in banned:
return candi
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
cleaned = re.sub(r"[^a-z\s]", " ", paragraph.lower())
for word in dict(sorted(collections.Counter(cleaned.split()).items(), key = lambda item: item[1], reverse = True)):
if word not in banned:
return word
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]
return collections.Counter(words).most_common(1)[0][0]
"a, a, a, a, b,b,b,c, c”re.sub(r"[^a-z\s]", "", paragraph.lower())b,b,b,c가 bbbc가 되어 단어 구분이 되지 않는다. 공백을 주어 단어 구분할 필요가 있다.re.sub(r"[^a-z\s]", " ", paragraph.lower())collections.Counter() , s붙는 것이랑 대문자 C 유의
collections.Counter().most_common(1)[0][0]
dict.items()
re.sub(r”[^\w]”, “ “, praragraph)
collections.Counter()에 대한 글
https://velog.io/@coding_study/collections.Count와-PEP-8