나의 개발일지

[프로그래머스] Lv.3 베스트 앨범 [Python, 파이썬] 본문

프로그래머스

[프로그래머스] Lv.3 베스트 앨범 [Python, 파이썬]

YoonJuHan 2024. 2. 23. 12:06
  • 문제 : https://school.programmers.co.kr/learn/courses/30/lessons/42579
  • 🔑 딕셔너리, 힙
    • music 딕셔너리
      • "장르" : [(-재생 횟수, 고유 번호), (-재생 횟수, 고유 번호)]
      • value의 리스트는 힙이고 재생 횟수를 음수값으로 넣어 최대 힙 구현
    • play 딕셔너리
      • "장르" : 총 재생 횟수
      • 앨범에 먼저 수록할 장르를 구하기 위한 딕셔너리
    • play 딕셔너리를 총 재생 횟수 기준으로 정렬
    • 1번 조건 : 노래가 많이 재생된 장르를 먼저 수록합니다.
      • 정렬한 play 리스트에서 pop()
    • 2번 조건 : 장르 내에서 많이 재생된 노래를 먼저 수록합니다.
      • music["장르"]에서 heappop()
      • 장르 내에 속한 곡이 1개 일 때 처리를 try-except 문으로 처리

 

from collections import defaultdict
from heapq import heappop, heappush

def solution(genres, plays):
    answer = []
    
    music = defaultdict(list)
    play = defaultdict(int)

    for i in range(len(genres)):
        heappush(music[genres[i]], (-plays[i], i))
        play[genres[i]] += plays[i]
    
    play = sorted(list(play.items()), key=lambda x : x[1])
    
    for i in range(len(music)):
        genre = play.pop()[0]
        try:
            answer.append(heappop(music[genre])[1])
            answer.append(heappop(music[genre])[1])
        except:
            continue
        
    return answer
Comments