Lv2. 뉴스 클러스터링

Hello·2022년 8월 1일

코딩테스트 연습 > [1차] 뉴스 클러스터링

1. 풀이 설명

  1. 두 글자씩 끊어서 다중집합의 원소로 만든다.

  2. validation 체크 후(영문만 유효) 소문자로 변경한다.

  3. {문자 : 개수} 를 저장할 수 있는 Counter를 사용하여 저장하고, 차집합/대칭차 를 계산한다.

2. 나의 풀이

python

import collections

def solution(str1, str2):
    list1 = []
    list2 = []
    
    for i in range(0, len(str1)-1):
        if str1[i:i+2].isalpha():
            list1.append(str1[i:i+2].lower())
    
    for i in range(0, len(str2)-1):
        if str2[i:i+2].isalpha():
            list2.append(str2[i:i+2].lower())
    
    counter1 = collections.Counter(list1)
    counter2 = collections.Counter(list2)
        
    union = counter1 | counter2
    intersection = counter1 & counter2
    
    union_size = len(list(union.elements()))
    intersecion_size = len(list(intersection.elements()))

    if union_size == 0:
        return 65536
    else:
        return int((intersecion_size/union_size) * 65536)

kotlin

3. 배운점

python

  1. collections.Counter() 연산 (참고 블로그)
counter1 = {'aa': 2}
counter2 = {'aa': 3}
  • 합집합
result = counter1 + counter2 # {'aa': 5}
  • 교집합
result = counter1 & counter2 # {'aa': 2}
    
  • 대칭차
result = counter1 | counter2 # {'aa': 3}
  • 결과 리스트로 보기
list(result.elements()))
  1. 개선된 코드
# asis
for i in range(0, len(str1)-1):
    if str1[i:i+2].isalpha():
        list1.append(str1[i:i+2].lower())

# tobe
list1 = [str1[i:i+2].lower() for i in range(len(str1)-1) if str1[i:i+2].isalpha()]
profile
안녕하세요 :)

0개의 댓글