문제 풀이
[python] 뉴스 클러스터링
_tera_
2021. 12. 13. 21:45
https://programmers.co.kr/learn/courses/30/lessons/17677
from collections import Counter
def solution(str1, str2):
answer = 0
str_1 = []
str_2 = []
# 알파벳만 소문자로 2글자씩 담기
for i in range(0,len(str1)):
if len(str1[i:i+2]) >= 2:
if str1[i:i+2].isalpha():
str_1.append(str1[i:i+2].lower())
for i in range(0,len(str2)):
if len(str2[i:i+2]) >= 2:
if str2[i:i+2].isalpha():
str_2.append(str2[i:i+2].lower())
co1 = Counter(str_1)
co2 = Counter(str_2)
# 교집합
inter = list((co1 & co2).elements())
# 합집합
union = list((co1 | co2).elements())
try:
answer = 65536*len(inter)//len(union)
except: # 0으로 나눌 경우 예외 처리
answer = 65536
return answer
Counter의 교집합& 합집합 | 기능을 쓰려고 보니 combinations으로도 &, | 되지 않을까..??!? 하고 하루 종일 combinations 이렇게저렇게 해봤는데 안 돼서 결국 Counter로 돌아왔다 ㅎ value 값만 추출하는 elements() 메소드를 쓰면 빠르게 솎아낼 수 있어서 편하다