문제

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

풀이

시도 1

  • 해시는 키-밸류 알고리즘을 이용한다.
    1. 앨범 배열을 play 많은순, 고유번호 낮은순으로 정렬
    1. 앨범 딕셔너리에 저장하여
    1. 장르별 플레이 합을 구한후 정렬해서 가장 높은 2개를 구해서
    1. 인덱스를 리턴한다.
  • 코드실행은 통과지만 제출 테스트에서 통과되지 못했음.
solution.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def solution(genres, plays):
    # 앨범 배열을 play 많은순, 고유번호 낮은순으로 정렬
    album_array = [(genres[i], plays[i], i) for i in range(len(genres))]
    album_array = sorted(album_array, key=lambda x: (x[0], -x[1], x[2]))

    # 앨범 딕셔너리에 저장
    album_dict = {}
    for genre, play, index in album_array:
        if genre not in album_dict.keys():
            album_dict[genre] = [(play, index)]
        else:
            album_dict[genre].append((play, index))

    # 장르별 플레이합을 구하기 위한 배열 선언
    played_total_genre = []
    for genre in album_dict.keys():
        total = 0
        for play, index in album_dict[genre]:
            total += play
        played_total_genre.append([genre, total])
    # 플레이합 기준으로 정렬
    played_total_genre = sorted(played_total_genre, key=lambda x: x[1], reverse=True)

    best_genre = album_dict[played_total_genre[0][0]]
    second_genre = album_dict[played_total_genre[1][0]]
    # 인덱스만 리턴
    return [best_genre[0][1], best_genre[1][1], second_genre[0][1], second_genre[1][1]]

시도2

defaultdict는 키를 지정할때 값을 주지 않으면 디폴트 값을 지정하는 라이브러리

solution.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def solution(genres, plays):
    from collections import defaultdict
    answer = []
    genres_total = defaultdict(int);
    genres_songs = defaultdict(lambda: [])

    # sort를 위해 i 선언 (갯수))
    i = 0
    # 돌면서 존재하지 않으면 defaultdict로 선언된 기본값이 주어짐
    for g, p in zip(genres, plays):
        genres_total[g] += p
        genres_songs[g].append((i,p))
        i += 1

    sorted_genres = sorted(genres_total.items(), key=(lambda x:x[1]), reverse = True)
    # print("genres_songs", genres_songs)
    for g in sorted_genres:
        sorted_g = sorted(genres_songs[g[0]], key=(lambda x: x[1]), reverse=True)
        answer.append(sorted_g[0][0])
        if len(sorted_g) > 1:
            answer.append(sorted_g[1][0])

    return answer

다른사람풀이 1

solution.py
 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[1] for e in sorted(d[g],key= lambda x: (x[0], -x[1]), reverse = True)]
        answer += temp[:min(len(temp),2)]
    return answer

다른사람풀이 2

solution.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def solution(genres, plays):
    answer = []
    dic = {}
    album_list = []
    for i in range(len(genres)):
        dic[genres[i]] = dic.get(genres[i], 0) + plays[i]
        album_list.append(album(genres[i], plays[i], i))

    dic = sorted(dic.items(), key=lambda dic:dic[1], reverse=True)
    album_list = sorted(album_list, reverse=True)



    while len(dic) > 0:
        play_genre = dic.pop(0)
        print(play_genre)
        cnt = 0;
        for ab in album_list:
            if play_genre[0] == ab.genre:
                answer.append(ab.track)
                cnt += 1
            if cnt == 2:
                break

    return answer

class album:
    def __init__(self, genre, play, track):
        self.genre = genre
        self.play = play
        self.track = track

    def __lt__(self, other):
        return self.play < other.play
    def __le__(self, other):
        return self.play <= other.play
    def __gt__(self, other):
        return self.play > other.play
    def __ge__(self, other):
        return self.play >= other.play
    def __eq__(self, other):
        return self.play == other.play
    def __ne__(self, other):
        return self.play != other.play