본문 바로가기
알고리즘/프로그래머스

[파이썬][프로그래머스] Lv. 1 키패드 누르기

by SBOX Learning by doing 2022. 6. 21.
반응형

def solution(numbers, hand):
    
    answer = ''
    # L_point : *, R_point:# 초기값 세팅
    L_hand = '*'
    R_hand = '#'
    # 위치 찍기
    temp = {
        '1':[0,0],
        '2':[1,0],
        '3':[2,0],
        '4':[0,1],
        '5':[1,1],
        '6':[2,1],
        '7':[0,2],
        '8':[1,2],
        '9':[2,2],
        '0':[1,3],
        '*':[0,3],
        '#':[2,3],
        }
    
    for i in numbers:

        # 147 이면 L
        if i in [1,4,7]:
            answer += 'L'
            # L의 현재위치 업데이트
            L_hand = str(i)
        # 369 이면 R
        elif i in [3,6,9]:
            answer += 'R'
            # R의 현재위치 업데이트
            R_hand = str(i)
        # 2580 이면 
        else:
            # 위치를 찍어서 제곱하기
            left_count = where(temp[L_hand],temp[str(i)])
            right_count = where(temp[R_hand],temp[str(i)])

            # 가까운 순
            if left_count > right_count:
                answer += 'R'
                R_hand = str(i)
            elif left_count < right_count:
                answer += 'L'
                L_hand = str(i)
                
            # 같으면 왼손잡이 오른손 잡이
            else:
                if hand == 'right':
                    answer += 'R'
                    R_hand = str(i)
                else:
                    answer += 'L'
                    L_hand = str(i)
    return answer

# 거리 제곱
def where(a, b):
    tmp = 0
    if (a[0] - b[0]) > 0:
        tmp += (a[0] - b[0])
    else:
        tmp -= (a[0] - b[0])
    if (a[1] - b[1]) > 0:
        tmp += (a[1] - b[1])
    else:
        tmp -= (a[1] - b[1])
    
    return tmp

반응형

댓글