티스토리 뷰

반응형


#. Problem


* The copyright in this matter is in Programmers


스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다.


1. 속한 노래가 많이 재생된 장르를 먼저 수록합니다.

2. 장르 내에서 많이 재생된 노래를 먼저 수록합니다.

3. 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다.


노래의 장르를 나타내는 문자열 배열 genres와 노래별 재생 횟수를 나타내는 정수 배열 plays가 주어질 때, 베스트 앨범에 들어갈 노래의 고유 번호를 순서대로 return 하도록 solution 함수를 완성하세요.


#. Resolution Process

  1. Read and understand problem

  2. Redefine the problem + abstract

    - plays가 가장 높은 장르를 먼저 수록 (장르별로 두 개)

    - 단, 장르가 같은 경우 plays가 더 높은 노래를 먼저, 

          plays가 같은 경우 고유 번호가 낮은 노래를 먼저 수록

  3. Create solution plan (select Algorithm, Data structure)

  4. Prove the plan (check performance time and usage memory)

  5. Carry out the plan

  6. Look back on the plan and find a way to improve it


#. Solve

  1. plays가 가장 높은 장르순으로 정렬하여 배열에 저장

  2. dictionary에 {장르 : [plays, 고유번호]}를 저장

  3. 각 key에서 2개의 곡씩 수록. 2곡 미만일 경우 1곡만 수록


#. Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from collections import defaultdict
 
def solution(genres, plays):
    play_count_by_senres = defaultdict(int)
    songs_in_genres = defaultdict(list)
 
    for song_id, genre, play in zip(range(0,len(genres)), genres, plays):
        play_count_by_senres[genre] += play
        songs_in_genres[genre].append((-play, song_id))
 
    genre_in_order = sorted(play_count_by_senres.keys(), key=lambda g:play_count_by_senres[g],reverse=True)
 
    answer = []
    for genre in genre_in_order:
        answer.extend([id for play, id in sorted(songs_in_genres[genre])[:2]])
 
    return answer
cs

- (4~5) collections.defaultdict 메서드를 사용하여 default dictionary를 생성

  (7~9) 장르별 곡들의 play 수를 더하여 play_count_by_senres dictionary에 저장

          play 수와 고유번호를 songs_in_genres의 해당되는 장르에 append하여 저장 (play가 음수인 이유는 정렬 시 가장 play가 높은 곡이 첫 번째 요소로 정렬될 수 있는 편리함을 이용) ex. {'classic': [(-500, 0), (-150, 2), (-800, 3)], 'pop': [(-600, 1), (-2500, 4)]})

  (11) play_count_by_senres dictionary의 key를 정렬하는데 옵션으로 해당 key의 value를 비교하여 정렬(key 옵션은 어떤 값을 기준으로 정렬을 할지 설정)

  (14~15) genre_in_order list에서 play 수가 높은 장르부터 songs_in_genres dictionary를 탐색하여 answer list에 extend하여 결과를 출력

            (단, 장르당 최대 2곡씩 수록하고 songs_in_genres dictionary에서 해당 genre에 해당하는 곡들을 정렬해주어야 함)


#. Other code

1
2
3
4
5
6
7
8
9
10
def solution(genres, plays):
    answer = []
    d = {e:[] for e in set(genres)}
    for e in zip(genres, plays, range(len(plays))):
        d[e[0]].append([e[1] , e[2]])
    genreSort =sorted(list(d.keys()), key= lambda x: sum( map(lambda y: y[0],d[x])), reverse = True)
    for g in genreSort:
        temp = [e[1for e in sorted(d[g],key= lambda x: (x[0], -x[1]), reverse = True)]
        answer += temp[:min(len(temp),2)]
    return answer
cs

  - 

반응형
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday