Notice
Recent Posts
Recent Comments
Link
«   2025/11   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
Archives
Today
Total
관리 메뉴

DANIELOGIC

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

Algorithm/프로그래머스

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

daniel; 2025. 5. 21. 14:53

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

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

문제

코드

def solution(numbers, hand):
    new = [[3,6,9,'#'],[2,5,8,0],[1,4,7,'*']]
    result = ''
    l_loc = (2,3)
    r_loc = (0,3)
    for i in numbers:
        if i in new[2]:
            result += "L"
            l_loc = (2,new[2].index(i))
        elif i in new[0]:
            result += "R"
            r_loc = (0,new[0].index(i))
        else:
            n_loc = (1,new[1].index(i))
            left = abs(l_loc[0]-1) + abs(l_loc[1]-n_loc[1])
            right = abs(r_loc[0]-1) + abs(r_loc[1]-n_loc[1])
            if left == right:
                if hand == "left":
                    result += "L"
                    l_loc = n_loc
                else:
                    result += "R"
                    r_loc = n_loc
            elif left > right:
                result += "R"
                r_loc = n_loc
            else:
                result += "L"
                l_loc = n_loc
    return result

리뷰

처음엔 유클리드 거리를 사용해 문제를 풀었지만 답이 나오지 않았다.

 

맨하탄 거리로 바꾸니 잘 작동했다.

 

'상하좌우'로 움직인다는 사실을 기억하자.