문제에서의 내용이 리스트가 두개 이상이 Input으로 주어지거나, 키 & 벨류로 풀어야 할 것같다 하면 딕셔너리를 사용해야하고, 해쉬를 사용하야 한다는 느낌은 이제 받을 수 있다.
def solution(genres, plays):
answer = []
total_d ={}
temp = []
#key 1.
temp = [[genres[i],plays[i],i]for i in range(len(genres))]
temp = sorted(temp,key=lambda x: (x[0],-x[1],x[2]))
for g in temp:
if g[0] not in total_d:
total_d[g[0]] = g[1]
else:
total_d[g[0]] += g[1]
#key 2.
total_d = sorted(total_d.items(), key = lambda x: -x[1])
# print(total_d.items()) ==> dict_items([('pop', 3100),('classic', 1450)])
# print(total_d) ==> {'pop': 3100,'classic': 1450}
for i in total_d:
count =0
for j in temp:
if i[0] == j[0]:
count+=1
if count >2:
break
else:
answer.append(j[2])
return answer
temp = [[genres[i],plays[i],i]for i in range(len(genres))]
=> [['classic', 500, 0], ['pop', 600, 1], ['classic', 150, 2], ['classic', 800, 3], ['pop', 2500, 4]]
temp = sorted(temp,key=lambda x: (x[0],-x[1],x[2]))
=> [['classic', 800, 3], ['classic', 500, 0], ['classic', 150, 2], ['pop', 2500, 4], ['pop', 600, 1]]
total_d = sorted(total_d.items(), key = lambda x: -x[1])
# print(total_d.items()) ==> dict_items([('pop', 3100),('classic', 1450)])
# print(total_d) ==> {'pop': 3100,'classic': 1450}
def solution(genres, plays):
answer = []
dic1 = {}
dic2 = {}
for i, (g, p) in enumerate(zip(genres, plays)):
if g not in dic1:
dic1[g] = [(i, p)]
else:
dic1[g].append((i, p))
if g not in dic2:
dic2[g] = p
else:
dic2[g] += p
# print(dic1)
# =>{'classic': [(0, 500), (2, 150), (3, 800)], 'pop': [(1, 600), (4, 2500)]}
# print(dic2)
# =>{'classic': 1450, 'pop': 3100}
for (k, v) in sorted(dic2.items(), key=lambda x:x[1], reverse=True):
for (i, p) in sorted(dic1[k], key=lambda x:x[1], reverse=True)[:2]:
answer.append(i)
return answer