1. key와 value를 갖고 있는 dictionary를 이용하여 문제를 풀었습니다.
2. index번호를 정답으로 출력시켜야하므로, value값에 (재생횟수와 index) 쌍을 저장하였습니다.
3. lambda를 이용하여 list와 dictionary에 정렬을 수행하였습니다.
- a=[(1,2),(0,1)]
먼저 첫 번째 인자를 기준으로 오름차순으로 정렬하고, 그 다음 두 번째 인자를 기준으로 내림차순으로 정렬할 경우,
a.sort(key=lambda x:(x[0],-x[1]))
정답 코드
def solution(genres, plays):
answer = []
dict={}
sum={}
for i in range(len(genres)):
if genres[i] not in dict:
dict[genres[i]]=[(plays[i],i)]
sum[genres[i]]=plays[i]
else:
dict[genres[i]].append((plays[i],i))
sum[genres[i]]+=plays[i]
#1. 많이 재생된 장르 순으로 정렬
sum=sorted(sum.items(), key = lambda x : -x[1])
#2. 장르 내에서 많이 재생된 노래 순서대로 정렬
#3. 재생 횟수가 같으면 고유 번호 낮은 순으로 정렬
for i in dict:
dict[i].sort(key = lambda x : (-x[0], x[1]))
# sum=[(장르, 총 재생 횟수),..]
# dict[장르]=[(재생 횟수, 고유번호),..]
for key in sum:
cnt=0
for i in range(len(dict[key[0]])):
answer.append(dict[key[0]][i][1])
cnt+=1
if cnt==2:
break
return answer
'IT > coding study' 카테고리의 다른 글
[acmicpc] 2252. 줄 세우기(python) (0) | 2021.12.01 |
---|---|
[acmicpc] 19238. 스타트 택시(python) (0) | 2021.10.24 |
[acmicpc] 21610. 마법사 상어와 비바라기(python) (0) | 2021.10.20 |
[acmicpc] 11656. 접미사 배열(python) (0) | 2021.01.28 |
[acmicpc] 7576. 토마토(BFS) (0) | 2020.09.26 |