Algorithm/Programmers

[Python] 키패드 누르기

느낌표 공장장 2021. 4. 29. 02:12
def solution(numbers, hand):
phone = [[1, 4, 7, '*'], [2, 5, 8, 0], [3, 6, 9, '#']]
used = []
last_l = (0, 3)
last_r = (2, 3)
for i in numbers :
if i in phone[0] :
used.append("L")
last_l = (0, phone[0].index(i))
elif i in phone[2] :
used.append("R")
last_r = (2, phone[2].index(i))
else :
now = (1, phone[1].index(i))
d_l = abs(last_l[0] - now[0]) + abs(last_l[1] - now[1])
d_r = abs(last_r[0] - now[0]) + abs(last_r[1] - now[1])
if d_l == d_r :
if hand == "left" :
used.append("L")
last_l = (1, phone[1].index(i))
else :
used.append("R")
last_r = (1, phone[1].index(i))
elif d_l < d_r :
used.append("L")
last_l = (1, phone[1].index(i))
else :
used.append("R")
last_r = (1, phone[1].index(i))
return ''.join(used)

 


풀이

1. 처음 변수들 설정

phone = [[1, 4, 7, '*'], [2, 5, 8, 0], [3, 6, 9, '#']]
used = []
last_l = (0, 3)
last_r = (2, 3)
for i in numbers :

① 키패드를 구현해 phone 변수에 저장해준다.

② 어떤 손이 사용될지 저장할 리스트 변수 만들어준다.

③ 마지막 왼손, 마지막 오른손의 위치를 튜플 형태로 저장할 변수를 만들어 준다.

   왼손은 처음에 '*'에 위치하니 (0, 3)을, 오른손은 '#'에 위치하니 (2, 3)을 저장해주었다.

④ for문으로 numbers에 저장된 숫자를 하나씩 불러온다.

 

2. 첫번째 if문

if i in phone[0] :
used.append("L")
last_l = (0, phone[0].index(i))

➀ i가 phone[0]에 있다면([1, 4, 7, '*']) 

➁ "L"을 used리스트에 추가하고 

➂ 마지막 왼손의 위치를 업데이트 해준다.

elif i in phone[2] :
used.append("R")
last_r = (2, phone[2].index(i))

elif문으로 맨 오른쪽도 위와 똑같이 해준다.

 

3-1. else 의 처음(?)

now = (1, phone[1].index(i))
d_l = abs(last_l[0] - now[0]) + abs(last_l[1] - now[1])
d_r = abs(last_r[0] - now[0]) + abs(last_r[1] - now[1])

➀ now에 현재 위치 저장해준다.

➁ d_l 변수에 마지막 왼손의 위치와 현재 위치의 거리를 저장해준다.

➂ d_r 변수에 마지막 오른손의 위치와 현재 위치의 거리를 저장해준다.

✔︎ abs() 함수 : absolute의 약자로 절대값을 구하는 함수.

 

3-2) else -> if

if d_l == d_r :
if hand == "left" :
used.append("L")
last_l = (1, phone[1].index(i))
else :
used.append("R")
last_r = (1, phone[1].index(i))

만약 d_l과 d_r이 같은 값이라면 (왼손과 오른손이 현재 번호까지 움직이게되는 거리가 같다면)

➀ 입력받은 hand가 "left"라면 (사용자가 왼손잡이라면) used 리스트에 "L" 추가 및 왼손 위치 업데이트

➁ 그렇지 않다면 (hand = "right" / 사용자가 오른손잡이) used 리스트에 "R" 추가 및 오른손 위치 업데이트

 

3-3) else -> elif, else

elif d_l < d_r :
used.append("L")
last_l = (1, phone[1].index(i))
else :
used.append("R")
last_r = (1, phone[1].index(i))

➀ 만약 d_l < d_r 이라면 (왼손이 현재 번호에 더 가깝다면) used 리스트에 "L" 추가 및 왼손 위치 업데이트

➁ 그렇지 않다면 (오른손이 현재 번호에 더 가깝다면) used 리스트에 "R" 추가 및 오른손 위치 업데이트

 

4) return

join함수로 used 리스트에 있는 값들을 연결하여 반환해준다.

'Algorithm > Programmers' 카테고리의 다른 글

[Python] 다트 게임  (0) 2021.05.01
[Python] 비밀지도  (0) 2021.04.30
[Python] 체육복  (0) 2021.04.27
[Python] 자릿수 더하기  (0) 2021.04.27
[Python] 약수의 합  (0) 2021.04.27