찾아야 하는 멜로디가 주어지고 재생이 시작된 시간, 끝난 시간, 곡 명, 악보가 들어있는 2차원 배열이 있는데 여기서 조건에 부합하는 곡명이 무엇인가를 반환 하거나 없으면 "(none)"을 반환하는 문제이다.
def solution(melody, musicinfos):
meltoNum = {"C": "A", "C#": "B", "D": "C", "D#": "D", "E": "E", "F": "F",
"F#": "G", "G": "H", "G#": "I", "A": "J", "A#": "K", "B": "L", "E#": "M"}
melChange = ""
cnt1 = 0
queue = list()
songInfo = list()
while cnt1 < len(melody):
if cnt1 < len(melody) - 1 and melody[cnt1 + 1] == "#":
melChange += meltoNum[melody[cnt1:cnt1 + 2]]
cnt1 += 2
else:
melChange += meltoNum[melody[cnt1]]
cnt1 += 1
for i in musicinfos:
tmp = list(map(str, i.split(",")))
h = int(tmp[1][0:2]) - int(tmp[0][0:2])
m = int(tmp[1][3::]) - int(tmp[0][3::])
t = 60 * h + m
n = ''
cnt = 0
while cnt < len(tmp[3]):
if cnt < len(tmp[3])-1 and tmp[3][cnt+1] == "#":
n += meltoNum[tmp[3][cnt:cnt+2]]
cnt += 2
else:
n += meltoNum[tmp[3][cnt]]
cnt += 1
tmp[3] = n
sen = ''
for j in range(t):
sen += tmp[3][j % len(tmp[3])]
songInfo.append([t, tmp[2], sen])
for i in range(len(songInfo)):
if melChange in songInfo[i][2]:
queue.append([songInfo[i][0], songInfo[i][1]])
if len(queue) != 0:
queue.sort(reverse=True, key=lambda x: x[0])
answer = queue.pop(0)
return answer[1]
else:
return "(None)"
깔끔하게 코드 작성을 못했는데 조건에 맞춰 이것저것 추가하다보니 살짝 난잡해진 감이 없잖아 있다.
멜로디가 A,B,C와 같이 한 문자인 경우도 있지만 A# 과 같이 '#'이 붙는 음을 처리하기 위해 딕셔너리로 따로 치환을 해주었다.
그리고 재생이 끝난시간에서 시작시간을 빼서 숫자로 나타내 저장해 주고 멜로디에 부합하는 곡들은 큐에 저장한 후 정렬 후 맨앞에 있는 것을 반환해주었다.
문제 설명에는 "E#"이 나와있지 않아서 왜 통과가 안되나 의아했다. 문제 수정이 필요할 것 같다.