프로그래머스
[프로그래머스] Lv.1 키패드 누르기 [Python, 파이썬] KAKAO
YoonJuHan
2023. 10. 9. 11:54
- 문제 : https://school.programmers.co.kr/learn/courses/30/lessons/67256
- 🔑 맨하탄 거리
- 번호들의 좌표, 양 엄지 손가락의 좌표를 기록
- 2, 5, 8, 0을 눌러야 할 때
- 맨하탄 거리 공식 | x1 - x2 |+ | y1 – y2 | 을 사용해 거리를 구한다.
- 거리가 짧은 손가락으로 누른다.
def solution(numbers, hand):
answer = ''
# 번호들의 좌표
coordinate = {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)}
lh, rh = (3,0), (3,2) # 엄지 손가락 시작 좌표
for n in numbers:
n_coord = coordinate[n] # 눌러야 할 번호 좌표
if n in [1, 4, 7]:
answer += 'L'
lh = n_coord
elif n in [3, 6, 9]:
answer += 'R'
rh = n_coord
else: # | x1 - x2 | + | y1 – y2 | (맨하탄 거리)
lhd = abs(lh[0] - n_coord[0]) + abs(lh[1] - n_coord[1])
rhd = abs(rh[0] - n_coord[0]) + abs(rh[1] - n_coord[1])
if lhd < rhd:
answer += 'L'
lh = n_coord
elif lhd > rhd:
answer += 'R'
rh = n_coord
else:
if hand == 'left':
answer += 'L'
lh = n_coord
else:
answer += 'R'
rh = n_coord
return answer