kiteday 님의 블로그

[프로그래머스-파이썬] 뉴스클러스터링 본문

코딩테스트

[프로그래머스-파이썬] 뉴스클러스터링

kiteday 2025. 12. 8. 11:38
반응형
SMALL

https://school.programmers.co.kr/learn/courses/30/lessons/17677

 

교집합과 합집합을 만드는 문제이다.

단, 각 요소는 글자여야하며 (공백, 기호 불가능) 대소문자를 구별하지 않는다.

난 합집합 교집합을 위해 re로 글자인지 검색했고 (isalpha를 사용해도 됨. 그치만 re를 더 잘못써서 테스트한 것임.) Counter를 이용해 차집합 연산을 수행했다.

from collections import Counter
import re

def solution(str1, str2):
    answer = 0
    group1 = [str1[i:i+2].lower() for i in range(len(str1)-1) if re.fullmatch(r'[a-zA-Z]{2}', str1[i:i+2]) ]
    group2 = [str2[i:i+2].lower() for i in range(len(str2)-1) if re.fullmatch(r'[a-zA-Z]{2}', str2[i:i+2])]
    
    g1 = Counter(group1)
    g2 = Counter(group2)
    
    union = list((g2+(g1-g2)).elements())
    intersection = list((g1-(g1-g2)).elements())
        
    
    if not union and not intersection:
        answer = 1
    else:
        answer = len(intersection)/len(union)
    return int(answer*65536)
LIST