[Python3] 프로그래머스 베스트앨범(hash)

민갱·2023년 7월 11일

CT

목록 보기
26/35

문제에서의 내용이 리스트가 두개 이상이 Input으로 주어지거나, 키 & 벨류로 풀어야 할 것같다 하면 딕셔너리를 사용해야하고, 해쉬를 사용하야 한다는 느낌은 이제 받을 수 있다.

베스트 앨범

def solution(genres, plays):
    answer = []
    total_d ={}
    temp = []
    #key 1.
    temp = [[genres[i],plays[i],i]for i in range(len(genres))]
    temp = sorted(temp,key=lambda x: (x[0],-x[1],x[2]))
    
    for g in temp:
        if g[0] not in total_d:
            total_d[g[0]] = g[1]
        else:
            total_d[g[0]] += g[1]
    
    #key 2.
    total_d = sorted(total_d.items(), key = lambda x: -x[1])
    # print(total_d.items()) ==> dict_items([('pop', 3100),('classic', 1450)])
    # print(total_d) ==> {'pop': 3100,'classic': 1450}
    
    for i in total_d:
        count =0
        for j in temp:
            if i[0] == j[0]:
                count+=1
                if count >2:
                    break
                else:
                    answer.append(j[2])
                
    return answer

key 1.


 temp = [[genres[i],plays[i],i]for i in range(len(genres))]
 => [['classic', 500, 0], ['pop', 600, 1], ['classic', 150, 2], ['classic', 800, 3], ['pop', 2500, 4]]

 temp = sorted(temp,key=lambda x: (x[0],-x[1],x[2]))
 => [['classic', 800, 3], ['classic', 500, 0], ['classic', 150, 2], ['pop', 2500, 4], ['pop', 600, 1]]
  • i 로 2차 리스트를 만들어 요소를 세개 넣고, 세개의 요소를 기준으로 정렬을 한다.
  • 정렬의 요소 x[0] 으로 장르별로 먼저 묶고, 그 다음 키로 x[1]에 -를 붙여 내림 차순 정렬을 한다. 그 다음 만약 x[0]과 x[1]이 모두 같을 경우를 위해서 x[2]를 오름 차순으로 정렬을 키를 한번더 붙여준다.

key 2.


total_d = sorted(total_d.items(), key = lambda x: -x[1])
# print(total_d.items()) ==> dict_items([('pop', 3100),('classic', 1450)])
# print(total_d) ==> {'pop': 3100,'classic': 1450}
  • total_d 는 {'pop': 3100,'classic': 1450} 이렇게 딕셔너리 인데, 정렬시 total_d.items()라고 넣고 key를 넣어주면 각 dict_items([('pop', 3100),('classic', 1450)]) 안에 리스트 안에 ('pop', 3100),('classic', 1450) 요소로 한개씩 접근해서 정렬을 할 수 있다.
  • 각 요소의 토탈 횟수를 내림 차순 정렬을 하였다.

또 다른 풀이.


def solution(genres, plays):
    answer = []

    dic1 = {}
    dic2 = {}

    for i, (g, p) in enumerate(zip(genres, plays)):
        if g not in dic1:
            dic1[g] = [(i, p)]
        else:
            dic1[g].append((i, p))

        if g not in dic2:
            dic2[g] = p
        else:
            dic2[g] += p
#	print(dic1)
#	=>{'classic': [(0, 500), (2, 150), (3, 800)], 'pop': [(1, 600), (4, 2500)]}

#    print(dic2)
#    =>{'classic': 1450, 'pop': 3100}

    for (k, v) in sorted(dic2.items(), key=lambda x:x[1], reverse=True):
        for (i, p) in sorted(dic1[k], key=lambda x:x[1], reverse=True)[:2]:
            answer.append(i)

    return answer

Note.

  • 딕셔너리에 items() 메서드를 사용해주면 {"key" : value}의 형태를 [(key, value)]의 형태로 만들어 준다.
  • 딕셔너리에도 append가 가능하다.
    • 해당 키에 요소에 이어 append를 한다.
profile
가보자고

0개의 댓글