- 
                            
                            알고리즘 인사이드 with 파이썬BOOK 2024. 5. 25. 20:00 알고리즘 인사이드 with 파이썬 "한빛미디어 서평단 <나는리뷰어다> 활동을 위해서 책을 제공 받아 작성된 서평입니다." 유일한 단어 찾기문제정의2개의 문자열이 주어지고, 이 문자열에 출현하는 단어의 빈도를 구하고 정확히 1번만 출현하는 단어들만 모아 리스트로 반환하는 것이 이 문제의 목표입니다. sentence1 = "I have an expensive doll" sentence2 = "I have an adorable doll"["expensive", "adorable"]문제 해결파이썬에서 빈도를 구하려면 먼저 딕셔너리로 사용할 변수를 선언해야 합니다. 이후 두 문장을 단어로 분리(tokenize)합니다. 첫번째 문장은 다음과 같이 분리됩니다. I, have, an, expensive, doll 이제 각 단어의 출현 빈도를 계산합니다. 각 단어가 정확히 1번씩 출현했음을 알 수 있습니다. 단어 빈도 I 1 have 1 an 1 expensive 1 doll 1 같은 방식으로 두번째 문장에서도 단어의 출현 빈도를 계산하여, 첫번째 문장에서 만든 출현 빈도 테이블(딕셔너리)을 갱신합니다. 그러면 1회만 출현한 단어는 2개인 것을 확인할 수 있습니다. 단어 빈도 I 2 have 2 an 2 expensive 1 doll 2 adorable 1 해결 코드import collections sentence1 = "I have an expensive doll" sentence2 = "I have an adorable doll" def find_uncommon_words(): def update_frequency(sentence, freq): for word in sentence.split(): if word not in freq: freq[word] = 0 freq[word] += 1 freq = {} update_frequency(sentence1, freq) update_frequency(sentence2, freq) res = [] for item, num in freq.items(): if 1 == num: res.append(item) return res def find_uncommon_words2(): freq = collections.Counter(sentence1.split()) + collections.Counter(sentence2.split()) return [item for item, num in freq.items() if num == 1] print(["expensive", "adorable"] == find_uncommon_words())find_uncommon_words 함수는 파이썬에서 제공하는 기본 문법만 사용해 구현했고, find_uncommon_words2 함수는 collections의 Counter를 사용해 간단히 구현할 수 있습니다. 728x90'BOOK' 카테고리의 다른 글회의 요약 보고서 작성법 (1) 2024.07.25 부트캠프 QA편 (0) 2024.06.23 Spring DI (3) 2024.04.27 게임 AI를 위한 탐색 알고리즘 입문 (1) 2024.03.23 HTTPS 통신의 암호화, RSA 그리고 양자 컴퓨터 (2) 2024.02.16