새소식

Problem solving/문제 풀이 - 2023.04.06

[Python] 프로그래머스 [3차] 방금그곡 풀이

  • -

문제 확인

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

나의 풀이

  • 들은 멜로디와 실제 곡을 비교하기 위해선, 재생 시간 만큼 곡의 멜로디를 늘려줘야 한다.
  • 곡을 늘릴 때 # 이 있으면 개수를 세기 어려우니, 먼저 # 이 붙은 음을 변경해준다.
  • 나머지 부분은 문제의 조건에 맞춰서 구현하면 된다.
    • 재생 시간이 동일할 경우, 먼저 입력된 음악을 반환하라고 돼 있는데, 입력 시간을 기준으로 정렬하지 않아도 똑같이 정답으로 나온다. 이미 입력 시간 기준으로 입력된 거 같다.
# 끝부분-처음 부분 연결돼 헷갈릴 수 있음 / 중간 멜로디만 겹칠 수 있음
# 재생 시간, 제공 악보를 보면서 비교 필요
# 1 분 1 개씩 -> 시간 충분하면 반복 재생 / 짧으면 재생 시간만큼만 !
# 조건 일치 여러개 -> 1. 재생 시간이 제일 긴 음악 제목 반환 2. 먼저 입력된 음악 제목 반환

# 샾 문자 -> 변경 필요
def solution(m, musicinfos):
    # 음악 정보 분리
    musicinfos = [info.split(",") for info in musicinfos]
    # 샵 문자 변경
    remove_sharp = {"C#" : "c", "D#" : "d", "F#" : "f", "G#" : "g", "A#" : "a"}
    for pitch, new_pitch in remove_sharp.items():
        m = m.replace(pitch, new_pitch)
        for idx, info in enumerate(musicinfos):
            info = *info[:3], info[3].replace(pitch, new_pitch)
            musicinfos[idx] = info
    # 시간 정보 계산 + 멜로디 계산
    for idx, info in enumerate(musicinfos):
        t1, t2, title, melody = info
        t1_h, t1_m = t1.split(":")
        t2_h, t2_m = t2.split(":")
        # 시간 정보 계산
        t1 = int(t1_h) * 60 + int(t1_m)
        t2 = int(t2_h) * 60 + int(t2_m)
        t = t2 - t1
        # 재생 시간에 맞게 멜로디 수정
        q, r = divmod(t, len(melody))
        melody = q * melody + melody[:r]
        musicinfos[idx] = [t, t1, t2, title, melody]
    # 조건이 일치하는 음악 찾기
    answer = []
    for info in musicinfos:
        idx = info[4].find(m)
        # 찾은 경우
        if idx != -1:
            answer.append(info)
    # 최대 길이 음악 선택
    if answer:
        answer = sorted(answer, key = lambda x : (-x[0], x[1]))
    return answer[0][3] if answer else "(None)"

 

다른 사람의 풀이

  • musicinfos를 한번만 순회해 필요한 정보를 모두 얻었다.
  • answer엔 재생 시간이 가장 긴 음악 정보만 저장된다.
def shap_to_lower(s):
    s = s.replace('C#','c').replace('D#','d').replace('F#','f').replace('G#','g').replace('A#','a')
    return s

def solution(m,musicinfos):
    answer=[0,'(None)']   # time_len, title
    m = shap_to_lower(m)
    for info in musicinfos:
        split_info = info.split(',')
        time_length = (int(split_info[1][:2])-int(split_info[0][:2]))*60+int(split_info[1][-2:])-int(split_info[0][-2:])
        title = split_info[2]
        part_notes = shap_to_lower(split_info[-1])
        full_notes = part_notes*(time_length//len(part_notes))+part_notes[:time_length%len(part_notes)]
        if m in full_notes and time_length>answer[0]:
            answer=[time_length,title]
    return answer[-1]

 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.