코딩테스트/프로그래머스

[Heap][해시] 베스트 앨범

박소민 2023. 12. 10. 02:33
베스트 앨범
 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

  • 첫 시도
    • 런타임 에러
import heapq

def solution(genres, plays):
    answer = []
    genres_cnt=[]    
    sort_play={}
    for genre in set(genres):
        cnt=0
        tmp=[]
        for idx, gp in enumerate(zip(genres, plays)):
            g,p=gp
            if g!=genre: continue
            cnt+=p
            heapq.heappush(tmp,(-p, idx))
        heapq.heappush(genres_cnt, (-cnt, genre))
        sort_play[genre]=tmp
    
    while genres_cnt:
        genre=heapq.heappop(genres_cnt)[1]
        
        tmp=sort_play[genre]
        for i in range(2):
            x=heapq.heappop(tmp)
            answer.append(x[1])

    return answer

 

 

  • 재시도
    • 예외처리 안해줘서 에러난 거였음
    • for문으로 2개씩 추출하는데 2개 이하일 경우가 있으므로 예외처리 해줘야함
import heapq

def solution(genres, plays):
    answer = []
    genres_cnt=[]    
    sort_play={}
    for genre in set(genres):
        cnt=0
        tmp=[]
        for idx, g in enumerate(genres):
            if g!=genre: continue
            cnt+=plays[idx]
            heapq.heappush(tmp,(-plays[idx], idx))
        heapq.heappush(genres_cnt, (-cnt, genre))
        sort_play[genre]=tmp
    
    while genres_cnt:
        genre=heapq.heappop(genres_cnt)[1]
        
        tmp=sort_play[genre]
        for i in range(2):
            if tmp:
                x=heapq.heappop(tmp)
                answer.append(x[1])

    return answer

 

'코딩테스트 > 프로그래머스' 카테고리의 다른 글

[다익스트라][Heap] 배달  (1) 2023.12.17
[BFS] 무인도 여행  (1) 2023.12.17
[DFS] 타겟 넘버  (0) 2023.12.03
[DP] 정수 삼각형  (1) 2023.12.02
[프로그래머스][조합] 이모티콘 할인행사  (0) 2023.10.15