유자차의 재테크 공부방

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

파이썬/알고리즘 문제 풀이

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

유자차H 2022. 3. 4. 22:56
반응형

문자열.upper() : 문자열을 대문자로 치환

abs(숫자) : 숫자의 절대값으로 출력

 

풀이방법

def solution(numbers, hand):
    ans = ""
    pos_l = [3,0]
    pos_r = [3,2]
    for i in numbers:
        # 항상 왼손
        if i in [1,4,7]:
            ans += "L"
            pos_l = [(i-1)//3, (i-1)%3]
        # 항상 오른손
        elif i in [3,6,9]:
            ans +="R"
            pos_r = [(i-1)//3, (i-1)%3]
        # 왼손 vs 오른손
        else:
            if i == 0:
                i = 11

            temp = [(i-1)//3, (i-1)%3]

            l = abs(temp[0]-pos_l[0]) + abs(temp[1]-pos_l[1])
            r = abs(temp[0]-pos_r[0]) + abs(temp[1]-pos_r[1])

            if l == r:
                if hand[0].upper() == "L":
                    ans += "L"
                    pos_l = temp
                else:
                    ans += "R"
                    pos_r = temp
            elif l < r:
                ans += "L"
                pos_l = temp
            else:
                ans += "R"
                pos_r = temp

    return ans
반응형
Comments