프로그래머스 - 베스트앨범

박영빈·2023년 4월 30일

Programmers

목록 보기
5/43

베스트앨범


설명

노래의 장르를 나타내는 문자열 배열 genres와 노래별 재생 횟수를 나타내는 정수 배열 plays가 주어질 때, 베스트 앨범에 들어갈 노래의 고유 번호를 순서대로 return 하도록 solution 함수를 완성하세요.
1. 속한 노래가 많이 재생된 장르를 먼저 수록합니다.
2. 장르 내에서 많이 재생된 노래를 먼저 수록합니다.
3. 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다.

from collections import Counter

def solution(genres, plays):
    answer = []
    total_plays = {}
    popular_genres = []
    
    for genre in set(genres):
        total_plays[genre] = 0
    for genre, play in zip(genres, plays):
        total_plays[genre] += play
        
    sorted_genres = sorted(total_plays.items(), key = lambda item: item[1], reverse = True)
    for i in sorted_genres:
        popular_genres.append(i[0])
    
    for i in popular_genres:
        genres_plays = list(filter(lambda x: genres[x] == i, range(len(genres))))

        tmp = []
        for j in genres_plays:
            tmp.append(plays[j])

        max_index = plays.index(max(tmp))
        answer.append(max_index)
        plays[max_index] = -1
        tmp[tmp.index(max(tmp))] = -1
        if len(tmp) > 1:
            answer.append(plays.index(max(tmp)))
        
        
    return answer
  • 복잡한 문제였다.
  • 우선 각 장르별 총 재생 횟수를 구한다. 이후 내림차순으로 정렬하여 인기 순 장르를 얻는다.
  • 그 다음 해당 장르 별 인덱스를 구하여 tmp에 저장한다.
  • tmp에서 재생 횟수가 가장 많은 2가지를 구하여 answer에 추가한다.
profile
안녕하세요<br>반가워요<br>안녕히가세요

0개의 댓글