베스트앨범(python)

이민호·2021년 3월 10일

나의 풀이

  1. (genres, plays, number)로 묶는 리스트를 만든다.
  2. genres와 plays를 기준으로 내림차순 정렬한다.
  3. genres별 plays의 합을 비교한 후, plays합의 크기에따라 genres별로 내림차순 정렬한다.
  4. genres별 plays의 1위와 2위를 구하여 answer에 넣어준다.
def solution(genres, plays):
    from collections import defaultdict
    songs = []
    cnt = 0
    answer = []
    /
    # songs[]에 genres,plays,고유번호를 넣는다.
    for x, y in zip(genres, plays):
        songs.append([x, y, cnt])
        cnt += 1
    /
    # genres를 기준으로 정렬하되 plays를 순서대로 내림차순 정렬한다.
    songs.sort(key=lambda x: (x[0], x[1]), reverse=True)
    # default dic을 이용해 각 장르마다 plays의 합을 구한다.
    songs_dict = defaultdict(int)
    for k in songs:
        songs_dict[k[0]] += k[1]
    # plays를 기준으로 내림차순으로 장르를 구한다.
    dict_sort = sorted(songs_dict.items(), key=lambda x: x[1], reverse=True)
    /
    # genres에서 만든 요소들을 temp에 넣은 후 2개의 number만을 answer에 입력시킨다.
    for z in dict_sort:
        temp = []
        temp = [x for x in songs if x[0] == z[0]]
        if len(temp) >= 2:
            answer.extend([temp[0][2], temp[1][2]])
        else:
            answer.append(temp[0][2])
    return answer

너무 코드가 긴것같다...
특히 temp에서 answer에 number를 효과적으로 넣는 방법을 알아보아야 겠다.

profile
life is fun

0개의 댓글