반응형
베스트앨범
문제 설명
스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다.
- 속한 노래가 많이 재생된 장르를 먼저 수록합니다.
- 장르 내에서 많이 재생된 노래를 먼저 수록합니다.
- 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다.
노래의 장르를 나타내는 문자열 배열 genres와 노래별 재생 횟수를 나타내는 정수 배열 plays가 주어질 때, 베스트 앨범에 들어갈 노래의 고유 번호를 순서대로 return 하도록 solution 함수를 완성하세요.
제한사항
- genres[i]는 고유번호가 i인 노래의 장르입니다.
- plays[i]는 고유번호가 i인 노래가 재생된 횟수입니다.
- genres와 plays의 길이는 같으며, 이는 1 이상 10,000 이하입니다.
- 장르 종류는 100개 미만입니다.
- 장르에 속한 곡이 하나라면, 하나의 곡만 선택합니다.
- 모든 장르는 재생된 횟수가 다릅니다.
입출력 예
genres | plays | return |
---|---|---|
["classic", "pop", "classic", "classic", "pop"] | [500, 600, 150, 800, 2500] | [4, 1, 3, 0] |
입출력 예 설명
classic 장르는 1,450회 재생되었으며, classic 노래는 다음과 같습니다.
- 고유 번호 3: 800회 재생
- 고유 번호 0: 500회 재생
- 고유 번호 2: 150회 재생
pop 장르는 3,100회 재생되었으며, pop 노래는 다음과 같습니다. - 고유 번호 4: 2,500회 재생
- 고유 번호 1: 600회 재생
따라서 pop 장르의 [4, 1]번 노래를 먼저, classic 장르의 [3, 0]번 노래를 그다음에 수록합니다.
- 장르 별로 가장 많이 재생된 노래를 최대 두 개까지 모아 베스트 앨범을 출시하므로 2번 노래는 수록되지 않습니다.
문제 풀이
def solution(genres, plays):
answer = []
unique_genres = list(set(genres))
music_cnt = {}
music_idx = {}
for i in range(len(genres)):
if genres[i] not in music_cnt:
music_cnt[genres[i]] = 0 # 노래 카운트
music_cnt[genres[i]] += plays[i]
music_idx[genres[i]] = []
music_idx[genres[i]].append((str(i), plays[i]))
else:
music_cnt[genres[i]] += plays[i]
music_idx[genres[i]].append((str(i), plays[i]))
music_cnt = sorted(music_cnt.items(), key=lambda x: x[1], reverse=True)
# print(music_cnt)
# 튜플의 두 번째 원소를 기준으로 리스트 정렬
for i in music_idx:
music_idx[i] = sorted(music_idx[i], key=lambda x: x[1], reverse=True)
for i, j in music_cnt:
if len(music_idx[i]) == 1:
answer.append(int(music_idx[i][0][0]))
else:
for k in range(len(music_idx[i]) // 2):
answer.append(int(music_idx[i][k * 2][0]))
answer.append(int(music_idx[i][k * 2 + 1][0]))
break
# answer.append(music_idx[k*2+1][0])
return answer
문제 해석
music_cnt는 장르의 총합 수를 계산하기 위해 쓰인 딕셔너리 변수며, music_idx는 idx와 장르내의 수록곡을 담기 위한 변수입니다. 주석에도 작성하듯이 수록곡의 개수를 바탕으로 정렬을 진행한다음, 정렬된 장르에서 탐색을 진행하며 장르내의 수록곡에서 2곡을 가져옵니다. 마지막 break문 걸어준 이유는 한 장르에서 여러 수록곡을 지속해서 2개씩 가져오는 방식인줄 알았는데 딱 2곡만 가져오는 방식이라 break문으로 2곡만 가져오고 for문을 멈춰줬습니다.
'Algorithm > programmers' 카테고리의 다른 글
프로그래머스 PCCP 기출문제 1번 - 붕대감기 [python] (0) | 2024.04.30 |
---|---|
프로그래머스 level2 전력망을 둘로 나누기 - python (4) | 2024.03.21 |
프로그래머스 level2 의상 - python (2) | 2023.11.29 |
프로그래머스 level2 [2019 카카오 개발자 겨울 인턴십]튜플 - python (4) | 2023.11.23 |
프로그래머스 [level2] 롤케이크 자르기 - python3 (0) | 2023.11.09 |