프로그래머스. 뉴스 클러스터링 파이썬 풀이

minan·2021년 6월 29일
0

프로그래머스

목록 보기
84/92

프로그래머스. Level 2. 뉴스 클러스터링 파이썬 풀이

문제링크 https://programmers.co.kr/learn/courses/30/lessons/17677


from collections import Counter

def solution(str1, str2):

    # a = 교집합 개수, b = 합집합 개수
    a, b = 0, 0
    
    # 각각 잘라서 저장할 배열
    array1 = []
    array2 = []
    
    # 대소문자 구분 x
    str1 = str1.lower()
    str2 = str2.lower()
    
    # 두개의 문자가 모두 알파벳이라면 array에 추가
    for i in range(0, len(str1)-1):
        if str1[i].isalpha() and str1[i+1].isalpha():
            array1.append(str1[i]+str1[i+1])
        else:
            continue
    
    # 두개의 문자가 모두 알파벳이라면 array에 추가
    for i in range(0, len(str2)-1):
        if str2[i].isalpha() and str2[i+1].isalpha():
            array2.append(str2[i]+str2[i+1])
        else:
            continue
    
    # 카운터를 이용하여 개수 세기
    count1 = Counter(array1)
    count2 = Counter(array2)

    
    for key in count1.keys():
        # 1번 집합의 키가 2번에도 있다면 교집합
        if key in count2.keys():
            # 교집합 개수 추가
            a += min(count1[key], count2[key])
            # 합집합 개수 추가
            b += max(count1[key], count2[key])
        # 없다면 합집합 개수만 추가
        else:
            b += count1[key]
    
    for key in count2.keys():
        # 2번의 키가 1번에 없다면
        if key not in count1.keys():
            # 합집합 개수 추가
            b += count2[key]
    
    # 두 집합이 모두 공집합이라면 65536 리턴
    if not array1 and not array2:
        return 65536
    else:
        return int((a/b) * 65536)
profile
https://github.com/minhaaan

0개의 댓글