728x90
반응형
문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/42579 |
1차 실패
from collections import Counter
def solution(genres, plays):
m=[]
answer=[]
d={}
for i,name in enumerate(genres):
answer.append([i,name,plays[i]])
answer.sort(reverse=True, key=lambda x:x[2])
answer.sort(reverse=True, key=lambda x:x[1])
for i in range(len(genres)):
if genres[i] in d:
d[genres[i]]+=plays[i]
else:
d[genres[i]]=plays[i]
di=sorted(d.items(),reverse=True, key=lambda x:x[1])
for i in range(len(answer)):
for j in range(len(di)):
if di[j][0] in answer[i]:
m.append(answer[i][0])
if len(m)==2*(j+1):
break
return m
2차 실패
def solution(genres, plays):
m=[]
answer=[]
d={}
for i,name in enumerate(genres):
answer.append([i,name,plays[i]])
answer.sort(reverse=True, key=lambda x:x[2])
answer.sort(reverse=True, key=lambda x:x[1])
for i in range(len(genres)):
if genres[i] in d:
d[genres[i]]+=plays[i]
else:
d[genres[i]]=plays[i]
di=sorted(d.items(),reverse=True, key=lambda x:x[1])
for i in range(len(di)):
for j in range(len(answer)):
if j>2:
break
elif di[i][0] in answer[j]:
m.append(answer[j][0])
answer.pop(0)
return m
3차 실패
from collections import Counter
def solution(genres, plays):
m=[]
answer=[]
d={}
for i,name in enumerate(genres):
answer.append([i,name,plays[i]])
answer.sort(reverse=True, key=lambda x:x[2])
answer.sort(reverse=True, key=lambda x:x[1])
for i in range(len(genres)):
if genres[i] in d:
d[genres[i]]+=plays[i]
else:
d[genres[i]]=plays[i]
di=sorted(d.items(),reverse=True, key=lambda x:x[1])
for i in range(len(di)):
j=0
for _ in range(2):
if di[i][0] in answer[j]:
m.append(answer[j][0])
del answer[j]
return m
4차 성공
from operator import itemgetter
def solution(genres, plays):
d={}
answer=[]
for i in range(len(genres)):
if genres[i] not in d:
d[genres[i]]=[]
d[genres[i]].append(0)
d[genres[i]].append((i,plays[i]))
d[genres[i]][0]+=plays[i]
a=list(d.values())
a.sort(reverse=True, key=itemgetter(0))
while a:
a[0].pop(0)
a[0].sort(reverse=True, key=itemgetter(1))
for i in range(len(a[0])):
if i>=2:
break
answer.append(a[0][i][0])
a.pop(0)
return answer
처음에 너무 복잡하게 list를 많이 만들고 2개 이상의 곡을 가지고 있는 장르를 감당하지 못해 에러가 난 것 같다..
다른 분의 풀이를 보고 도움을 받았는데 이렇게 간단하게 풀수있다니,,,,,,,,,,
그래도 덕분에 itemgetter 사용법도 알게 되었다..!
갠적으루 lambda보다 itemgetter가 훨씬 편해,,,,
728x90
반응형
댓글