파이썬 알고리즘-121 (프로그래머스) 방금그곡

jiffydev·2021년 3월 12일
0

Algorithm

목록 보기
128/134

코드

# 틀린 코드
from datetime import datetime

def solution(m, musicinfos):
    answer = ''
    res=[]
    for info in musicinfos:
        info=info.split(',')
        time_a=datetime.strptime(info[0],'%H:%M')
        time_b=datetime.strptime(info[1],'%H:%M')
        time_diff=(time_b-time_a).seconds//60

        score=''
        if len(info[3])<time_diff:
            i=0
            j=0
            while i<time_diff:
                if info[3][j%(len(info[3]))]!='#':
                    score+=info[3][j%(len(info[3]))]
                    i+=1
                    j+=1
                else:
                    score+='#'
                    j+=1
        elif len(info[3])>time_diff:
            score=info[3][:time_diff]
        else:
            score=info[3]
        
        index=0
        if m in score:
            i=0
            tmp=''
            for x in score:
                if tmp==m and x!='#':
                    res.append((index, time_diff, info[2]))
                    break
                
                elif tmp==m and x=='#':
                    break
                
                if x==m[i]:
                    tmp+=x
                    i+=1
                else:
                    tmp=''
                    i=0
            index+=1
    if not res:
        return "(None)"
    
    res=sorted(res, key=lambda x: (-x[1], x[0]))
    answer=res[0][2]
    
    return answer

다른 사람의 풀이

# datetime 모듈을 사용하는 것보다
# 시간 계산하는 함수를 구현하는 것이 속도가 빠르다.
from datetime import datetime

def changecode(music_): 
    music_ = music_.replace('C#', 'c')
    music_ = music_.replace('D#', 'd')
    music_ = music_.replace('F#', 'f')
    music_ = music_.replace('G#', 'g')
    music_ = music_.replace('A#', 'a')    
    return music_ 

def solution2(m, musicinfos):
    answer=[]
    m=changecode(m)
    for idx, musicinfo in enumerate(musicinfos):
        musicinfo=changecode(musicinfo)
        musicinfo=musicinfo.split(',')

        time_a=datetime.strptime(musicinfo[0],'%H:%M')
        time_b=datetime.strptime(musicinfo[1],'%H:%M')
        time=(time_b-time_a).seconds//60

        if len(musicinfo[3])>=time:
            melody=musicinfo[3][:time]
        else:
            q,r=divmod(time, len(musicinfo[3]))
            melody=musicinfo[3]*q + musicinfo[3][:r]

        if m in melody:
            answer.append((idx,time,musicinfo[2]))
    
    if len(answer)!=0:
        answer=sorted(answer, key=lambda x: (-x[1], x[0]))
        return answer[0][2]
    return "(None)"
profile
잘 & 열심히 살고싶은 개발자

0개의 댓글