[1차] 뉴스 클러스터링

발자·2023년 6월 7일
0

programmers

목록 보기
27/34

문제

def solution(str1, str2):
    # 대문자로 변환
    str1 = str1.upper()
    str2 = str2.upper()
    
    # 두 글자씩 끊기
    str1_dic = dict()
    str2_dic = dict()
    
    # 영문인지 판별 후 추가
    ing = set([s for s in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'])
    for idx in range(len(str1)-1):
        key = str1[idx:idx+2]
        if key[0] not in ing or key[1] not in ing:
            continue
        if key not in str1_dic.keys():
            str1_dic[key] = 1
        else:
            str1_dic[key] += 1
    for idx in range(len(str2)-1):
        key = str2[idx:idx+2]
        if key[0] not in ing or key[1] not in ing:
            continue
        if key not in str2_dic.keys():
            str2_dic[key] = 1
        else:
            str2_dic[key] += 1
    
    # 교집합 A ∩ B
    inter = 0
    # 합집합 A ∪ B
    union = 0
    for key in set(list(str1_dic.keys())+list(str2_dic.keys())):
        if key in str1_dic.keys() and key in str2_dic.keys():
            inter += min(str1_dic[key], str2_dic[key])
            union += max(str1_dic[key], str2_dic[key])
        elif key in str1_dic.keys() and key not in str2_dic.keys():
            union += str1_dic[key]
        else:
            union += str2_dic[key]
    
    # 유사도에 65536을 곱한 후에 소수점 아래를 버리고 정수부만 출력
    if union == 0:
        answer = 1*65536
    else:
        answer = int((inter / union) * 65536)
    return answer

0개의 댓글