문제 : https://programmers.co.kr/learn/courses/30/lessons/42579
코딩테스트 연습 - 베스트앨범
스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다. 속한 노래가 ��
programmers.co.kr
▶ 딕셔너리 value값으로 정렬 하기 : https://kkamikoon.tistory.com/138
[Python] 딕셔너리 정렬하기
파이썬 딕셔너리에 입력된 key 값과 value 값들을 정렬해야 할 때가 있습니다. 그럴 때 해결할 수 있는 방법을 사용해보려고 합니다. 각각 Key를 이용한 방법과 Value를 이용한 방법이 있습니다. 딕셔
kkamikoon.tistory.com
→ 딕셔너리를 정렬하는 순간 리스트 형태로 바뀐다.
▶ 코드
# 장르별로 두개씩 모아 베스트 앨범을 출시
import operator
def solution(genres, plays):
ans = []
dic = {}
for a, b in zip(genres, plays):
if a in dic.keys():
dic[a] += b
else:
dic[a] = b
#print(dic) # {'classic': 1450, 'pop': 3100}
sdic = sorted(dic.items(), key=operator.itemgetter(1), reverse=True)
#print(sdic) # [('pop', 3100), ('classic', 1450)]
for a in sdic:
c = 0
target = a[0]
#print(target)
tmp_dic = {}
index = -1
for i in range(len(genres)):
if genres[i] == target:
index = i
tmp_dic[index] = plays[index]
#print(tmp_dic) # {1: 600, 4: 2500}
#print(index)
if len(tmp_dic) == 1:
ans.append(index)
continue
tmp_dic = sorted(tmp_dic.items(), key=operator.itemgetter(1), reverse=True)
#print(tmp_dic) # [(4, 2500), (5, 2500), (1, 600)]
c = 0
i = 0
while c < 2:
ans.append(tmp_dic[i][0])
c += 1
i += 1
#print(ans)
return ans
#solution(['classic', 'pop', 'classic', 'classic', 'pop', 'pop'], [500, 600, 150, 800, 2500, 2500])
#solution(['classic','pop','classic','classic','pop'],[500,600,501,800,900])
'[프로그래머스] 코테 고득점 Kit > 해시' 카테고리의 다른 글
[Level 2] 전화번호 목록 (0) | 2020.05.16 |
---|---|
[Level 1] 완주하지 못한 선수 (0) | 2020.05.16 |