11/1 키패드 누르기
https://school.programmers.co.kr/learn/courses/30/lessons/67256?language=python3
문제가 길고 복잡해 보이지만 문제를 따라 차근차근 코드를 작성하니 무난하게 풀렸다..
내 풀이
def manhattan(hand_x, hand_y, x, y) :
return abs(hand_x - x) + abs(hand_y - y)
def solution(numbers, hand):
answer = ''
left_x, left_y = 3, 0 # 왼쪽 엄지 좌표
right_x, right_y = 3, 2 # 오른쪽 엄지 좌표
# (숫자 : y좌표) 딕셔너리
left_num = {1 : 0, 4 : 1, 7 : 2}
middle_num = {2 : 0, 5 : 1, 8 : 2, 0 : 3}
right_num = {3 : 0, 6 : 1, 9 : 2}
for num in numbers :
if num in left_num.keys() :
answer = answer + 'L'
left_x, left_y = left_num[num], 0
elif num in right_num.keys() :
answer = answer + 'R'
right_x, right_y = right_num[num], 2
else :
target_x, target_y = middle_num[num], 1
left_distance = manhattan(left_x, left_y, target_x, target_y)
right_distance = manhattan(right_x, right_y, target_x, target_y)
if left_distance > right_distance :
answer = answer + 'R'
right_x, right_y = target_x, target_y
elif left_distance < right_distance :
answer = answer + 'L'
left_x, left_y = target_x, target_y
else :
if hand == "right" :
answer = answer + 'R'
right_x, right_y = target_x, target_y
else :
answer = answer + 'L'
left_x, left_y = target_x, target_y
return answer
왼쪽 엄지로 누를 숫자, 가운데 숫자, 오른쪽 엄지로 누를 숫자의 y좌표를 따로따로 딕셔너리를 3개를 할당하니 가독성이 좋지 않은것 같아서 좌표 딕셔너리를 하나로 합쳤다.
수정한 풀이
def manhattan(hand_x, hand_y, x, y) :
return abs(hand_x - x) + abs(hand_y - y)
def solution(numbers, hand):
number_coord = {
1 : (0, 0), 2 : (0, 1), 3 : (0, 2),
4 : (1, 0), 5 : (1, 1), 6 : (1, 2),
7 : (2, 0), 8 : (2, 1), 9 : (2, 2),
0 : (3, 1)
}
left_coord = (3, 0) # 왼쪽 엄지 좌표
right_coord = (3, 2) # 오른쪽 엄지 좌표
answer = ''
for num in numbers :
coord = number_coord[num]
if num in [1, 4, 7] :
answer = answer + 'L'
left_coord = coord
elif num in [3, 6, 9] :
answer = answer + 'R'
right_coord = coord
else :
target_coord = coord
left_distance = manhattan(left_coord[0], left_coord[1], target_coord[0], target_coord[1])
right_distance = manhattan(right_coord[0], right_coord[1], target_coord[0], target_coord[1])
if left_distance > right_distance :
answer = answer + 'R'
right_coord = coord
elif left_distance < right_distance :
answer = answer + 'L'
left_coord = coord
else :
if hand == "right" :
answer = answer + 'R'
right_coord = coord
else :
answer = answer + 'L'
left_coord = coord
return answer
댓글남기기