[プログラマー]キーボードを押す(Python)

6482 ワード

Link
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
注意事項
距離を計算するときは割引を漏らすことはできません.