문제링크: 키패드 누르기
✍🏻 Information
| content | |
|---|---|
| 언어 | python |
| 난이도 | ⭐️⭐️ |
| 풀이시간 | 30분 |
| 제출횟수 | 2 |
| 인터넷검색유무 | yes |
🍒 My Code
phone = [[1,2,3],
[4,5,6],
[7,8,9],
['*',0,'#']]
def check_distance(x,y,target_x,target_y):
return abs(x-target_x)+abs(y-target_y)
def solution(numbers, hand):
answer = ''
lx,ly = 3, 0
rx,ry = 3, 2
for number in numbers:
coordinate=[[i,j] for i in range(4) for j in range(3) if phone[i][j]==number] #핸드폰에서 현재 좌표찾기
print(coordinate)
if coordinate[0][1]==0:
answer+='L'
lx,ly = coordinate[0][0],coordinate[0][1]
elif coordinate[0][1]==1:
left = check_distance(lx,ly,coordinate[0][0],coordinate[0][1])
right = check_distance(rx,ry,coordinate[0][0],coordinate[0][1])
if left<right:
answer+='L'
lx,ly = coordinate[0][0],coordinate[0][1]
elif left>right:
answer+='R'
rx,ry = coordinate[0][0],coordinate[0][1]
else:
if hand=="left":
answer+='L'
lx,ly = coordinate[0][0],coordinate[0][1]
else:
answer+='R'
rx,ry = coordinate[0][0],coordinate[0][1]
elif coordinate[0][1]==2:
answer+='R'
rx,ry = coordinate[0][0],coordinate[0][1]
return answer
💡 What I learned
2차원 list에서 원하는 value의 index 찾기newlist=[(i,j) for i in range(n) for j in range(m) if mylist[i][j]==1]
이렇게 하니 coordinate[0]을 다 붙여줘야하는 귀찮음이 있었는데 해결할 방법을 모색해봐야겠다.
<풀이1 - 좌표를 지정>
def solution(numbers, hand):
answer = ''
location = [[3, 1], [0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
left, right = [3, 0], [3, 2]
for i in numbers:
if i % 3 == 1:
answer += 'L'
left = location[i]
elif i % 3 == 0 and i != 0:
answer += 'R'
right = location[i]
else:
l = abs(location[i][0] - left[0]) + abs(location[i][1] - left[1])
r = abs(location[i][0] - right[0]) + abs(location[i][1] - right[1])
if l < r:
answer += 'L'
left = location[i]
elif l > r:
answer += 'R'
right = location[i]
else:
answer += hand[0].upper() #L이나 R을 answer에 더하는 과정
if hand == 'right':
right = location[i]
else:
left = location[i]
return answer
<풀이2 - 딕셔너리 사용>
def solution(numbers, hand):
answer = ''
key_dict = {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),
'*':(3,0),0:(3,1),'#':(3,2)}
left = [1,4,7]
right = [3,6,9]
lhand = '*'
rhand = '#'
for i in numbers:
if i in left:
answer += 'L'
lhand = i
elif i in right:
answer += 'R'
rhand = i
else:
curPos = key_dict[i]
lPos = key_dict[lhand]
rPos = key_dict[rhand]
ldist = abs(curPos[0]-lPos[0]) + abs(curPos[1]-lPos[1])
rdist = abs(curPos[0]-rPos[0]) + abs(curPos[1]-rPos[1])
if ldist < rdist:
answer += 'L'
lhand = i
elif ldist > rdist:
answer += 'R'
rhand = i
else:
if hand == 'left':
answer += 'L'
lhand = i
else:
answer += 'R'
rhand = i
return answer