키패드 누르기

발자·2022년 9월 15일
0

programmers

목록 보기
10/34

def solution(numbers, hand):
    answer = ''
    leftLocation = 10
    rightLocation = 12
    hand = hand[0].upper()
    # 0 > 11 변경
    for i in range(0, len(numbers)) :
        if numbers[i] == 0 :
            numbers[i] = 11

    for point in numbers :
        # 1, 4, 7일 때 왼손 사용
        if point in [1, 4, 7] :
            answer += 'L'
        # 3, 6, 9일 때 오른손 사용
        elif point in [3, 6, 9] :
            answer += 'R'
        # 2, 5, 8, 0일 때
        else :
            # 왼손, 오른손, 키패드의 좌표를 계산하여 거리 구하기
            a, b = divmod(point-1, 3)
            c1, d1 = divmod(leftLocation-1, 3)
            c2, d2 = divmod(rightLocation-1, 3)
            leftDis = abs(a-c1) + abs(b-d1)
            rightDis = abs(a-c2) + abs(b-d2)
            # 오른손이 가까울 때
            if leftDis > rightDis :
                answer += 'R'
            # 왼손이 가까울 때
            elif leftDis < rightDis :
                answer += 'L'
            # 왼손, 오른손과의 거리가 같을 때
            else :
                answer += hand
        # 마지막에 사용한 손 위치 저장
        if answer[-1] == 'R' :
            rightLocation = point
        else :
            leftLocation = point
    return answer

🗝️몫, 나머지
🧩 키패드 좌표를 계산하지 않고 dictionary로 지정해줘도 깔끔하다.

0개의 댓글