CS/algorithm & data structure

[프로그래머스] [3차] 방금그곡 (파이썬 풀이)

hjkim0502 2022. 6. 30. 21:22

https://programmers.co.kr/learn/courses/30/lessons/17683

 

코딩테스트 연습 - [3차] 방금그곡

방금그곡 라디오를 자주 듣는 네오는 라디오에서 방금 나왔던 음악이 무슨 음악인지 궁금해질 때가 많다. 그럴 때 네오는 다음 포털의 '방금그곡' 서비스를 이용하곤 한다. 방금그곡에서는 TV,

programmers.co.kr

 

* 테케 해결 못 함

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

def solution(m, musicinfos):
    ans = []    
    m = change_code(m)
    
    for i, info in enumerate(musicinfos):
        start, end, title, code = info.split(',')
        code = change_code(code)
        time = int(end.split(':')[0]) * 60 + int(end.split(':')[1])\
        - (int(start.split(':')[0]) * 60 + int(start.split(':')[1]))
        
        # 재생된 악보
        quo, rem = divmod(time, len(code))
        song = code * quo + code[:rem]

        if m in song:
            ans.append([title, time, i])
            
    if not ans:
        return '(None)'
    return sorted(ans, key = lambda x:(-x[1], x[2]))[0][0]
  • 아이디어: # 붙은 음을 한 문자로 처리하고, 재생시간에 따라 악보 생성한 뒤 기억한 멜로디와 같은지 확인
  • 본인은 #을 사전에 처리하지 않고 재생된 악보에서 m + '#' 제거한 뒤에 m 있으면 정답 리스트에 추가했는데, 테케 3개에서 실패해서 다른 답안 참고함
  • 예외처리, 조건 잊지 않기 위해 종이에 잘 적어 놓기
def change_code(code):
    return code.replace('C#', 'c').replace('D#', 'd').replace('F#', 'f').replace('G#', 'g').replace('A#', 'a')

def solution(m, musicinfos):
    ans = []  
    m = change_code(m)
    
    for i, info in enumerate(musicinfos):
        start, end, title, code = info.split(',')
        code = change_code(code)
        time = int(end.split(':')[0]) * 60 + int(end.split(':')[1])\
        - (int(start.split(':')[0]) * 60 + int(start.split(':')[1]))
        
        quo, rem = divmod(time, len(code))
        song = code * quo + code[:rem]

        if m in song:
            if not ans:
                ans = [title, time, i]
                
            prev_time, prev_idx = ans[1], ans[2]
            if time > prev_time:
                ans = [title, time, i]
            elif time == prev_time:
                if prev_idx > i:
                    ans = [title, time, i]
            
    if not ans:
        return '(None)'
    return ans[0]
  • 정답을 산출하는 방식을 바꾼 코드인데, 시간 효율이 거의 비슷하게 나옴 (ans에 최대 100까지만 들어갈 수 있어서 그러지 않을까 싶다)