728x90
자료구조 3주차 숙제_2
멜론 베스트 앨범 뽑기
📄 나의 코드
class PlaysIndex:
def __init__(self, index, play):
self.index = index
self.play = play
def get_melon_best_album(genre_array, play_array):
dict_sum = {}
for i in range(len(genre_array)):
if genre_array[i] in dict_sum.keys():
dict_sum[genre_array[i]] += play_array[i]
else:
dict_sum[genre_array[i]] = play_array[i]
dict_sum_sort = sorted(dict_sum.items(), key=lambda x: x[1], reverse=True)
dict_list = {}
for k in dict_sum_sort:
dict_list[k[0]] = []
for z in range(len(genre_array)):
if genre_array[z] in dict_list.keys():
ip = PlaysIndex(z, play_array[z])
dict_list[genre_array[z]].append(ip)
result = []
for key in dict_list:
dict_list_sort = sorted(dict_list[key], key=lambda x: x.play, reverse=True)
count = 0
for u in dict_list_sort:
count += 1
result.append(u.index)
if count == 2:
break
return result
print("정답 = [4, 1, 3, 0] / 현재 풀이 값 = ", get_melon_best_album(["classic", "pop", "classic", "classic", "pop"], [500, 600, 150, 800, 2500]))
print("정답 = [0, 6, 5, 2, 4, 1] / 현재 풀이 값 = ", get_melon_best_album(["hiphop", "classic", "pop", "classic", "classic", "pop", "hiphop"], [2000, 500, 600, 150, 800, 2500, 2000]))
총 장르별 음악 재생 횟수를 알 수 있는 딕셔너리 dict_sum
장르별 모든 음악 정보 리스트 dict_list
딕셔너리 value값 정렬
sorted_dict = sorted(dict.items(), key = lambda x: x[1], reverse = True)
dict.items()하면, key, value값이 나오는데 이중에서 value값을 기준으로 정렬할 것이니,
key = lambda x:x[1] 로 설정
내림차순으로 정렬해야 하니 reverse = True로 한다.
genres = ["hiphop", "classic", "pop", "classic", "classic", "pop", "hiphop"]
plays = [2000, 500, 600, 150, 800, 2500, 2000]
for key in dict_list:
print(dict_list[key])
# 출력
[<__main__.PlaysIndex object at 0x00000268F17D6970>, <__main__.PlaysIndex object at 0x00000268F194B040>]
[<__main__.PlaysIndex object at 0x00000268F1941A90>, <__main__.PlaysIndex object at 0x00000268F1941D90>]
[<__main__.PlaysIndex object at 0x00000268F1836A60>, <__main__.PlaysIndex object at 0x00000268F1941760>, <__main__.PlaysIndex object at 0x00000268F1941B20>]
dict_list 의 value값은 index(곡 위치)와 play(재생횟수)로 이루어진 객체이다.
따라서 이를 출력하려면 print(dict_list[key].index) 또는 print(dict_list[key].play)가 되어야한다.
이미 총 재생횟수가 많은 순으로 정렬후, 빈 리스트가 들어가도록 했으니
이제 재생횟수가 많은 순으로 정렬하면 된다.
result = []
for key in dict_list:
print(dict_list[key])
dict_list_sort = sorted(dict_list[key], key=lambda x:x.play, reverse=True)
count = 0
for u in dict_list_sort:
count += 1
result.append(u.index)
if count == 2:
break
print(result)
따라서 다음과 같이 정렬하면 원하는 인덱스를 추출할 수 있다!
또한 각 장르당 2곡씩만 들어가니 count 변수를 이용해 두곡만 들어갈 수 있도록 해줬다.
'알고리즘' 카테고리의 다른 글
코딩 테스트 연습 30일 (0) | 2022.12.30 |
---|---|
코딩 테스트 연습 29일 (0) | 2022.12.29 |
코딩 테스트 연습 28일 (0) | 2022.12.28 |
자료구조 3주차 숙제 (0) | 2022.12.27 |
코딩 테스트 연습 27일 (0) | 2022.12.27 |