dictionary data type을 활용하여 푸는 문제
python에서 stl의 compare와 같은 구현을 통하여 원하는 방식으로 sort할 수 있다.
python 3.x 버전 부터는 sorted 인자로 key = cmp_to_key(보조 함수이름)를 통하여 구현 가능.
dict를 sort 할 때 sorted(dict, ...) 로 구현하면 key만 가지는 list가 리턴되니 조심하자.
아래에는 1.문제링크, 2.code, 3.테스트 케이스 순으로 첨부하였다.
1.문제링크
https://programmers.co.kr/learn/courses/30/lessons/42579
알고리즘 연습 - 베스트앨범 | 프로그래머스
스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다. 속한 노래가 많이 재생된 장르를 먼저 수록합니다. 장르 내에서 많이 재생된 노래를 먼저 수록합니다. 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다. 노래의 장르를 나타내는 문자열 배열 genres와 노래별 재생 횟수를 나타내는 정수 배열 play
programmers.co.kr
2.code :
from functools import cmp_to_key
def solution(genres, plays):
answer = []
d_score = {}
d_index = {}
for index, (genres,plays) in enumerate(zip(genres, plays)):
d_score[genres] = d_score.get(genres, 0) + plays
if d_index.get(genres, 0) == 0 :
d_index[genres] = []
d_index[genres].append([index, plays])
print(d_score)
# print(d_index)
l_sorted = sorted(d_score.items(), key = lambda k : k[1], reverse =True)
print("l_sorted: ",l_sorted)
for obj in l_sorted:
genres = obj[0]
l_srtd_plays = sorted(d_index[genres],key= cmp_to_key(compare))
answer.append(l_srtd_plays[0][0])
if len(l_srtd_plays) >1:
answer.append(l_srtd_plays[1][0])
print(genres, l_srtd_plays)
return answer
def compare(x,y):
if x[1] == y[1]:
if x[0] < y[0] :
return -1
else:
return 1
elif x[1] < y[1]:
return 1
else:
return -1
3.테스트 케이스
'알고리즘&자료구조(algorithm& data structure) > 프로그래머스(programmers)' 카테고리의 다른 글
[프로그래머스]해시-위장 문제 풀이 (0) | 2021.01.03 |
---|---|
[프로그래머스 / 고득점 kit] 탐욕법: 조이스틱 ver2 (0) | 2019.07.24 |
[프로그래머스 / 고득점 kit] 탐욕법: 조이스틱- ver 1 (0) | 2019.07.24 |
[programmers/ 고득점 kit] 정렬: 가장 큰수 (0) | 2019.07.16 |