# 방금그곡 - 프로그래머스
def solution(m, musicinfos):
m = m.replace("C#",'H').replace("D#", 'I').replace("F#", 'J').replace("G#",'K').replace("A#",'L')
ret = []
for info in musicinfos:
s, e, name, sheet = info.split(',')
sheet = sheet.replace("C#",'H').replace("D#", 'I').replace("F#", 'J').replace("G#",'K').replace("A#",'L')
sh, sm = map(int, s.split(':'))
eh, em = map(int, e.split(':'))
time = (eh - sh) * 60 + em - sm
while len(sheet) < time:
sheet += sheet
if m in sheet[:time]:
ret.append([name, time, sh])
if not ret:
return "(None)"
ret.sort(key = lambda x: (x[1], -x[2]))
return ret.pop()[0]