파이썬 알고리즘-117 (프로그래머스) 뉴스 클러스터링

jiffydev·2021년 3월 3일
0

Algorithm

목록 보기
124/134

코드

def solution(str1, str2):
    answer = 0
    str1_lst=[]
    str2_lst=[]
    for i in range(len(str1)-1):
        if str1[i:i+2].isalpha():
            str1_lst.append(str1[i:i+2].upper())
    for j in range(len(str2)-1):
        if str2[j:j+2].isalpha():
            str2_lst.append(str2[j:j+2].upper())
    
    intersect=[]
    union=[]
    
    for k in str1_lst:
        if k not in intersect:
            intersect+=[k]*min(str1_lst.count(k),str2_lst.count(k))
            
        if k not in union:
            union+=[k]*max(str1_lst.count(k),str2_lst.count(k))
        
    for k in str2_lst:
        if k not in intersect:
            intersect+=[k]*min(str1_lst.count(k),str2_lst.count(k))
        if k not in union:
            union+=[k]*max(str1_lst.count(k),str2_lst.count(k))
    
    if len(str1_lst)==0 and len(str2_lst)==0:
        answer=1
    else:
        answer=len(intersect)/len(union)
    return int(answer*65536)

다른 사람의 풀이

def solution(str1, str2):

    list1 = [str1[n:n+2].lower() for n in range(len(str1)-1) if str1[n:n+2].isalpha()]
    list2 = [str2[n:n+2].lower() for n in range(len(str2)-1) if str2[n:n+2].isalpha()]
    
    # list1, list2의 합집합을 우선 구한다
    tlist = set(list1) | set(list2)
    res1 = [] #합집합
    res2 = [] #교집합

    # list1, list2가 모두 공집합이 아니라면 == tlist가 있다면
    if tlist:
        for i in tlist:
            res1.extend([i]*max(list1.count(i), list2.count(i)))
            res2.extend([i]*min(list1.count(i), list2.count(i)))

        answer = int(len(res2)/len(res1)*65536)
        return answer

    else:
        return 65536
profile
잘 & 열심히 살고싶은 개발자

0개의 댓글