[구현] 뉴스 클러스터링

기린이·2022년 1월 16일
0

문제

import re
from collections import defaultdict


def make_two(string):  # 2개씩 끊어서 단어 리스트 만들기
    words = []
    for idx in range(len(string)):
        if idx == len(string)-1:
            break
        else:
            w = string[idx] + string[idx+1]
            if not(re.search('[^a-z]', w)):
                words.append(w)
    return words


def solution(str1, str2):
    words1 = make_two(str1.lower())
    words2 = make_two(str2.lower())

    if len(words1) == 0 and len(words2) == 0:
        return 65536

    dic1 = defaultdict(int)
    dic2 = defaultdict(int)

    for w1 in words1:
        dic1[w1] += 1

    for w2 in words2:
        dic2[w2] += 1

    set1 = set(words1)
    set2 = set(words2)

    inter = set1.intersection(set2)
    
    all_inter = 0
    for inter_item in inter:
        if dic1[inter_item] > 1 or dic2[inter_item] > 1:
            inter_val = min(dic1[inter_item], dic2[inter_item])
            all_inter += inter_val

        else:  # str1, str2에서 개수가 1인 경우
            all_inter += 1

    all_union = sum(dic1.values()) + sum(dic2.values()) - all_inter

    return int(all_inter/all_union*65536)

나의 접근

A와 B교집합 원소를 모두 보면서 A, B에서 1개이상등장했다면 중복을 고려한 교집합, 합집합을 구해서 더해준다.

모두 1번 등장했다면 교집합 +1, 합집합 +1

아예 교집합에 속하지 않는 원소의 개수는 합집합에 더해준다.

A집합의 여집합 + B집합의 여집합 + 교집합

=>
집합으로 변환해서 개수를 구하면 안된다.
여집합에도 중복이 존재할 수 있다!!!!

=>
개수를 구하기 쉬운 건
A + B - A와B 교집합이다.

# 원래 코드 
all_union += len(set1 - inter)
all_union += len(set2 - inter)

# 새로운 코드
all_union = sum(dic1.values()) + sum(dic2.values()) - all_inter
profile
중요한 것은 속력이 아니라 방향성, 공부하며 메모를 남기는 공간입니다.

0개의 댓글