Most Common Word

김_리트리버·2021년 3월 22일
0

[알고리즘]

목록 보기
25/47

정규식, filter, set, Counter , defaultdict, dictionary,

내 풀이

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        
# banned 단어를 제외한 단어들만 모으기 위한 함수 
        def excludeBannedWord(word):
            if word not in banned:
                return True
# 전체 문장에서 단어가 아닌 애들을 띄어쓰기로 바꾸고, 모두 소문자로 변경하고 띄어쓰기 기준으로 
# 분리해서 list 에 넣음 
        words = list(filter(excludeBannedWord, re.sub(
    r'[\W]', ' ', paragraph).lower().split()))
#    wordList 에 중복이 되지 않게 단어들을 list 에 넣음      
        wordSet={}
        wordList = list(set(words))
# wordSet 에 단어를 키로 value 는 0으로 초기화 시킴       
        for word in wordList:
            wordSet[word] = 0
# 전체 단어가 모여있는 words list 에서 각 word 가 wordSet 에 있으면 +1             
        for word in words:
            if(word in wordSet):
                wordSet[word] += 1
# 임의로 아무 단어나 result 에 넣음                
        result = wordList[0]
# 특정 단어가 초기에 설정한 단어보다 숫자가 크면 result 가 대체됨         
        for word in wordSet:
            if(wordSet[word] > wordSet[result]):
                result = word
        
        return result

책 풀이

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        
        def excludeBannedWord(word):
            if word not in banned:
                return True
        
        words = list(filter(excludeBannedWord, re.sub(
    r'[\W]', ' ', paragraph).lower().split()))
        
        # defaultdict class 를 사용해 미리 value 를 int 로 초기화 시킴
				# 원래는 {a:0,b:0,c:0} 으로 초기화 한 후 
				# dictionary 에 접근해야 하지만 
				# defaultdict 로 초기화 시켜놓으면 키 존재유무와 상관없이 키-value 를 할당할 수 있음
				counts = defaultdict(int)
        print(counts.get)

        for word in words:
            

            if(word in word):
                counts[word] += 1

				# counts => 최대값을 구할 iterable 
				# key=counts.get 최대값을 어떤 기준으로 계산할 건지
				# key=counts.get => counts 의 value
        return max(counts,key=counts.get)
class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        
        def excludeBannedWord(word):
            if word not in banned:
                return True
        
        words = list(filter(excludeBannedWord, re.sub(
    r'[\W]', ' ', paragraph).lower().split()))
 
		# words list 에서 가장 많이 나온 순으로 정렬하고 그중에 첫번째 값을 배열로 리턴
		# [(ball,2)] => (ball,2) => ball
        return Counter(words).most_common(1)[0][0]
profile
web-developer

0개의 댓글