euphoriaO-O

[Python][프로그래머스] 키패드 누르기 본문

Programming/Algorithm

[Python][프로그래머스] 키패드 누르기

euphoria0-0 2020. 7. 11. 15:10

#2020카카오인턴십 문제

def solution(numbers, hand):
    ans = ''
    L, R = 10,12  # 거리 계산이 편하도록
    # 자명
    for n in numbers:
        if n in [1,4,7]:
            ans += 'L'
            L = n
        elif n in [3,6,9]:
            ans += 'R'
            R = n
        else:
            n = 11 if n == 0 else n  # 거리 계산이 편하도록
            # 거리 계산
            i,j = (n-1)//3, (n-1)%3   #1,1
            Li,Lj = (L-1)//3, (L-1)%3 #1,0
            Ri,Rj = (R-1)//3, (R-1)%3 #0,2
            Ld = abs(i-Li) + j-Lj
            Rd = abs(Ri-i) + Rj-j
            # 가까운 손 & ~손잡이 확인
            if Ld == Rd:
                ans += hand[0].upper()
                if ans[-1]=='L':
                    L = n
                else:
                    R = n
            elif Ld < Rd:
                ans += 'L'
                L = n
            else:
                ans += 'R'
                R = n
    return ans
Comments