chyam

[프로그래머스 Lv3, python] - 베스트앨범 본문

프로그래머스/LV3

[프로그래머스 Lv3, python] - 베스트앨범

chyam_eun 2026. 5. 4. 14:11

https://school.programmers.co.kr/learn/courses/30/lessons/42579

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

# 내가 작성한 코드
def solution(genres, plays):
    answer = []
    cnt_dict = {}
    idx_dict = {}
    for g in range(len(genres)): # (재생수,번호)로 저장
        if genres[g] not in cnt_dict:
            cnt_dict[genres[g]] = plays[g]
            idx_dict[genres[g]] = [[plays[g],g]]
        else:
            cnt_dict[genres[g]] += plays[g]
            idx_dict[genres[g]].append([plays[g],g])

    while cnt_dict:
        max_total = 0
        max_g = ''
        for g in cnt_dict:
            if max_total < cnt_dict[g]: # 젤 큰거 
                max_total = cnt_dict[g]
                max_g = g
        del cnt_dict[max_g] # 젤 큰거 삭제
        idx_dict[max_g].sort(key=lambda x:[-x[0],x[1]]) # 정렬
        
        answer.append(idx_dict[max_g][0][1])
        if len(idx_dict[max_g]) > 1:
            answer.append(idx_dict[max_g][1][1])
    return answer
# 다른코드
def solution(genres, plays):
    answer = []
    cnt_dict = {}
    idx_dict = {}
    
    # 장르별 정리
    for i in range(len(genres)):
        g = genres[i]
        
        cnt_dict[g] = cnt_dict.get(g, 0) + plays[i]
        idx_dict.setdefault(g, []).append((plays[i], i))
    
    # 장르를 총 재생수 기준 정렬
    sorted_genres = sorted(cnt_dict, key=lambda x: -cnt_dict[x])
    
    # 각 장르에서 상위 2개 추출
    for g in sorted_genres:
        songs = sorted(idx_dict[g], key=lambda x: (-x[0], x[1]))
        
        answer.append(songs[0][1])
        if len(songs) > 1:
            answer.append(songs[1][1])
    
    return answer