공부하고 기록하는, 경제학과 출신 개발자의 노트

프로그래밍/코딩테스트 문제풀이

[Python] 프로그래머스. 2020 카카오 인턴 - 키패드 누르기 (Level 1)

inspirit941 2020. 8. 31. 02:55
반응형

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

 

코딩테스트 연습 - 키패드 누르기

[1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5] "right" "LRLLLRLLRRL" [7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2] "left" "LRLLRRLLLRR" [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] "right" "LLRLLRLLRL"

programmers.co.kr

 

def solution(numbers, hand):
pad = {
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, right = {1,4,7}, {3,6,9}
left_pos, right_pos = (3,0), (3,2)
answer = []
for num in numbers:
if num in left:
left_pos = pad[num]
answer.append("L")
elif num in right:
right_pos = pad[num]
answer.append("R")
else:
ldist = abs(left_pos[0] - pad[num][0]) + abs(left_pos[1] - pad[num][1])
rdist = abs(right_pos[0] - pad[num][0]) + abs(right_pos[1] - pad[num][1])
if ldist == rdist:
if hand == 'left':
answer.append("L")
left_pos = pad[num]
else:
answer.append("R")
right_pos = pad[num]
else:
if ldist > rdist:
answer.append("R")
right_pos = pad[num]
else:
answer.append("L")
left_pos = pad[num]
return "".join(answer)
반응형