나의 풀이
def solution(numbers, hand):
# 1. 왼손 오른손 위치를 초기화
left_key= [1,4,7]
right_key= [3,6,9]
hand_position=['*', '#']
keyPad = {
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)
}
# 2. 숫자를 누를 손가락 정하기
answer=""
for num in numbers:
if num in left_key:
hand_position[0]=num
answer+="L"
elif num in right_key:
hand_position[1]=num
answer+="R"
else:
#더 가까운 손으로 누른다.
#여기서 num은 if문과 elif문을 skip하고 왔으며, next_step이다.
near_hand = get_near_hand(keyPad, hand_position[0], hand_position[1],num, hand)
if near_hand == 'L':
hand_position[0]=num
answer+='L'
else:
hand_position[1]=num
answer+='R'
return answer
def get_near_hand(keyPad, l, r, num, hand):
#abs(현재위치 - next_step)
#x좌표 + y좌표
left_distance = abs(keyPad[l][0]-keyPad[num][0])+abs(keyPad[l][1]-keyPad[num][1])
right_distance= abs(keyPad[r][0]-keyPad[num][0])+abs(keyPad[r][1]-keyPad[num][1])
if right_distance>left_distance:
return "L"
elif right_distance<left_distance:
return "R"
elif right_distance== left_distance:
if hand == "right":
return "R"
else:
return "L"
다른 사람의 풀이
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
'프로그래머스(파이썬) > LV.1(파이썬)' 카테고리의 다른 글
크레인 인형 뽑기 →"열"접근★★ + 전부 1씩 빼주기(람다식)★★ (0) | 2022.12.21 |
---|---|
폰켓몬★★ → 해설, 조합X (0) | 2022.12.21 |
숫자 짝꿍 → 일치 + count() + min(a,b) + len(answer) == a.count('0')★★ + 모든 요소가 0인 경우 (0) | 2022.12.20 |
과일장수 →특정요소 여러 개 제거★★+ 1차원 리스트 슬라이싱(n등분)★★ (0) | 2022.12.20 |
가장 가까운 글자→ 다중 index를 이용★★ (0) | 2022.12.20 |