[정리]
1. 장르의 수를 구하기위해 totalplay_genres 딕셔너리 선언하기
1-1. sorted()메소드를 사용해서 장르별 빈도순으로 정렬한 리스트 반환, Lambda사용
2.Idx별 장르명과 플레이횟수를 저장하는 딕셔너리 선언하기
2-1. sorted()메소드를 사용해서 장르별 빈도순을 idx와 묶어서 정렬한 리스트 반환,Lambda 사용
3.모든 제한사항을 통과하여 두개씩 추출하는 방법을 생각
- 속한 노래가 많이 재생된 장르를 먼저 수록합니다.
- 장르 내에서 많이 재생된 노래를 먼저 수록합니다.
- 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다.
[1차시도]
- 밤늦게 풀었더니 이상한 로직을 세웠다. 근데 테스트 케이스 9번을 제외하고 전부통과되었다.
def solution(genres, plays):
answer = []
#어떤 장르가 얼마나 재생됬는지 부터 구해봅시다.
totalplay_genres ={}
sorted_genres ={}
for i in range(len(genres)):
sorted_genres[i] = [genres[i],plays[i]]
if genres[i] not in totalplay_genres:
totalplay_genres[genres[i]] = plays[i]
else:
totalplay_genres[genres[i]] += plays[i]
sum_genres = sorted(totalplay_genres.items(), key = lambda x:x[1],reverse = True)
sort_genres = sorted(sorted_genres.items(), key = lambda x:(x[1][1]),reverse = True)
print(sort_genres)
for i in range(len(totalplay_genres)):
for j in range (len(sort_genres)):
if sort_genres[j][1][0] == sum_genres[i][0] and sort_genres[j][1][1] !=0 :
answer.append(sort_genres[j][0])
##이부분이 틀린 곳이다.######################
if len(answer) %2 ==0:
if len(answer) != 1:
break
if len(answer) ==1:
answer.append(sort_genres[j][0])
#########################################
print(answer)
return answer
[테스트 케이스 9번의 반례를 찾아보자]
genres =['c','a','b','a','a','b','b','b','b','c','c','c','d']
plays =[1,500,9, 600, 501, 800,500,300,2,2,1,2,100000]
solution(genres,plays)
이 경우 가장 많이 플레이된 d , 1개 밖에 없기 때문에 다음 들어오는 b의 노래가 합쳐진 answer의 길이가 2가 되는 순간 break가 걸리게 코드가 짜여져있었다.(왜그랬지)
[2차시도]
-count 변수를 이용해서 모든 테스트 케이스를 통과 할 수 있었다.
def solution(genres, plays):
answer = []
totalplay_genres ={}
sorted_genres ={}
count =0
for i in range(len(genres)):
sorted_genres[i] = [genres[i],plays[i]]
if genres[i] not in totalplay_genres:
totalplay_genres[genres[i]] = plays[i]
else:
totalplay_genres[genres[i]] += plays[i]
sum_genres = sorted(totalplay_genres.items(), key = lambda x:x[1],reverse = True)
sort_genres = sorted(sorted_genres.items(), key = lambda x:(x[1][1]),reverse = True)
print(sort_genres)
for i in range(len(totalplay_genres)):
count =0##대신 이 반복문을 돌때 count 변수를 항상 초기화 시켜야된다
for j in range (len(sort_genres)):
###변경된 부분######## count 변수를 추가하였다
if sort_genres[j][1][0] == sum_genres[i][0] and sort_genres[j][1][1] !=0 :
answer.append(sort_genres[j][0])
count = count +1
if count ==2:## 이부분 이후의 예외처리는 개수가 한개만일때는 이로직에 알아서 걸려서 break됨
print(count)
break
print(answer)
return answer
성공!
[다른 풀이]
1. 내장 함수 zip()사용
2.문자열 slicing 활용
3.while문
'[PS] 알고리즘문제풀이' 카테고리의 다른 글
[백준,PS,재귀,DP,삼성SW][PYTHON] #14501. 퇴사 (0) | 2020.05.16 |
---|---|
[프로그래머스,PS,스택,큐][PYTHON] #1. 탑 (0) | 2020.05.14 |
[프로그래머스,PS,해시][PYTHON] #3.위장 (0) | 2020.05.13 |
[프로그래머스,PS,해시][PYTHON] #2.전화번호 목록 (0) | 2020.05.12 |
[프로그래머스,PS,해시][PYTHON] #1.완주하지 못한 선수 (0) | 2020.05.12 |