⚡️algorithm

[문자열] 프로그래머스 lv2. 방금그곡

남남이루 2022. 5. 31. 18:18

문제

내가 들은 음계가 그 노래 음계에 포함이 되니?

리뷰

if m in played:
가 중요했다.

코드

melody = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
m = 'ABCDEFG'
info =     ["12:00,12:14,HELLO,CDEFGAB", "13:00,13:05,WORLD,ABCDEF"]
answer = 'HELLO'

def removeSharp(music):
    if 'A#' in music:
        music = music.replace('A#', 'a')
    if 'F#' in music:
        music = music.replace('F#', 'f')
    if 'C#' in music:
        music = music.replace('C#', 'c')
    if 'G#' in music:
        music = music.replace('G#', 'g')
    if 'D#' in music:
        music = music.replace('D#', 'd')
    return music

for i in info:
    infos = i.split(',')
    melody = infos[3]

    s,e = infos[0].split(':'), infos[1].split(':')
    time = int(s[0])*60 + int(s[1]) - int(e[0])*60 + int(e[1])

    played = ''
    for t in range(time):
        long = len(melody)
        idx = t
        if t >= long:
            # t = 4, real = 5번째
            # t = 5, real = 6번째
            idx = (t%long)-1
        played += melody[idx]

    played = removeSharp(played)
    m = removeSharp(m)
    answer = ('(None)', None)

    if m in played:
        if (answer[1] == None) or (time > answer[1]):
            answer = (infos[2], time)
    print(answer[0])

    1. 29 개선 => 런타임 에러

#   시작, 종료, 제목, 코드

def formatCode(words):
    words = words.lower()
    result = ''
    for l in words:
        if l == '#':
            result = result[:-1] + result[-1].upper()
        else:
            result += l
    return result

def getTimeGap(time1, time2):
    h1,m1 = time1.split(':')
    h2,m2 = time2.split(':')
    # 23:59 ~ 00:01
    if int(h2)-int(h1) < 0:
        h2 += 24
    return (int(h2)-int(h1))*60 + int(m2) - int(m1)



def solution(m, musicinfos):
    # m : 기억하는 코드
    comp = [[0,'']]
    m = formatCode(m)

    for info in musicinfos:
        start, end, name, code = info.split(',')
        gap = getTimeGap(start, end)

        code = formatCode(code)
        long = len(code)

        played = ''
        for moment in range(gap):
            if moment >= long:
                moment %= long

            played += code[moment]

            if m in played:
                if comp[0][0] < gap:
                    comp = [gap, name]
                break

    return comp[1] if comp[1]!='' else '(None)'