본문 바로가기
Algorithm/프로그래머스

[프로그래머스] Lv1 - 키패드 누르기 (파이썬)

by 2HS 2022. 3. 16.

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

 

코딩테스트 연습 - 키패드 누르기

[1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5] "right" "LRLLLRLLRRL" [7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2] "left" "LRLLRRLLLRR" [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] "right" "LLRLLRLLRL"

programmers.co.kr

 

from collections import defaultdict


def solution(numbers, hand):
    arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], ['*', 0, '#']]

    # 숫자의 위치 딕셔너리 정의
    location = defaultdict(list)
    for i in range(4):
        for j in range(3):
            temp = i * 3 + j + 1
            if arr[i][j] == temp:
                location[temp] = [i, j]
            if arr[i][j] == 0:
                location[0] = [i, j]

    #  L로 누룰지 R로 누룰지
    answer = ''
    L, R = [3, 0], [3, 2]
    for x in numbers:
        if x in [1, 4, 7]:
            answer += 'L'
            L = location[x]
        elif x in [3, 6, 9]:
            answer += 'R'
            R = location[x]
        else:
            left_dist = abs(L[0]-location[x][0]) + abs(L[1]-location[x][1])
            right_dist = abs(R[0]-location[x][0]) + abs(R[1]-location[x][1])
            if left_dist < right_dist:
                answer += 'L'
                L = location[x]
            elif left_dist > right_dist:
                answer += 'R'
                R = location[x]
            else:
                if hand == 'left':
                    answer += 'L'
                    L = location[x]
                else:
                    answer += 'R'
                    R = location[x]
    return answer

 

해시

1.  딕셔너리를 정의한다.

2. numbers를 탐색

    - 1, 4, 7 : 왼쪽, L을 해당 값의 위치로 초기화

    - 3, 6, 9 : 오른쪽, R을 해당 값의 위치로 초기화

    - 그 외 : 가까운 거리로 초기화 / 거리가 같다면 주로 사용하는 손으로 초기화

3. return answer