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

cotato·2021년 5월 7일

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

My Solution

def solution(numbers, hand):
    answer = ''
    
    curr_left = [3, 0]
    curr_right = [3, 2]
    
    for n in numbers:
        if n == 1 or n == 4 or n == 7:
            answer += 'L'
            curr_left = [(n - 1) / 3, 0]
        elif n == 3 or n == 6 or n == 9:
            answer += 'R'
            curr_right = [(n - 3) / 3, 0]
        else:
            row = (n - 2) / 3 if n != 0 else 3
            col = 1
            dist_left = abs(curr_left[0] - row) + abs(curr_left[1] - col)
            dist_right = abs(curr_right[0] - row) + abs(curr_right[1] - col)
            # print('dist_left: {}, dist_right: {}'.format(dist_left, dist_right))
            if dist_left < dist_right or (dist_left == dist_right and hand == 'left'):
                answer += 'L'
                curr_left = [row, col]
            else:
                answer += 'R'
                curr_right = [row, col]
            
    
    return answer

주의할 점

거리 계산할 때 절댓값을 빼먹으면 안된다.

profile
coding_potato

0개의 댓글