유형: 구현
풀이 시간: 20분
def solution(numbers, hand):
answer = ''
lf = [1, 4, 7]
rh = [3, 6, 9]
lfhand = -1
rhhand = -2
for nb in numbers:
if nb in lf:
answer += 'L'
lfhand = nb
elif nb in rh:
answer += 'R'
rhhand = nb
else:
ld = getdistance(lfhand, nb)
rd = getdistance(rhhand, nb)
if ld == rd:
if hand == 'right':
rhhand = nb
answer += 'R'
else:
answer += 'L'
lfhand = nb
elif ld > rd:
rhhand = nb
answer += 'R'
else:
answer += 'L'
lfhand = nb
return answer
def getdistance(hand, nb):
pad = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [-1, 0, -2]]
handi, handj, nbi, nbj = 0, 0, 0, 0
for i in range(len(pad)):
if hand in pad[i]:
handi = i
handj = pad[i].index(hand)
if nb in pad[i]:
nbi = i
nbj = pad[i].index(nb)
return abs(nbi-handi) + abs(nbj - handj)
문제를 보고 조금 당황했으나 큰 어려움 없이 풀었다.
세부 조건이 많아서 복잡했던 문제.
최적화도 해보았다
중복되는 코드 줄이기...
def solution(numbers, hand):
answer = ''
lf, rh = [1, 4, 7], [3, 6, 9]
lfhand, rhhand = -1, -2
flag = 0
for nb in numbers:
if nb in lf:
flag = 1
elif nb in rh:
flag = 2
else:
ld = getdistance(lfhand, nb)
rd = getdistance(rhhand, nb)
if ld == rd:
if hand == 'right':
flag = 2
else:
flag = 1
elif ld > rd:
flag = 2
else:
flag = 1
if flag == 1:
answer += 'L'
lfhand = nb
else:
answer += 'R'
rhhand = nb
return answer
def getdistance(hand, nb):
pad = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [-1, 0, -2]]
handi, handj, nbi, nbj = 0, 0, 0, 0
for i in range(len(pad)):
if hand in pad[i]:
handi = i
handj = pad[i].index(hand)
if nb in pad[i]:
nbi = i
nbj = pad[i].index(nb)
return abs(nbi-handi) + abs(nbj - handj)
'프로그래머스 > Lv. 1' 카테고리의 다른 글
54. 성격 유형 검사하기 (0) | 2024.07.17 |
---|---|
53. 신규 아이디 추천 ★ (isalpha, isdigit) (0) | 2024.07.17 |
51. 크레인 인형뽑기 게임 (0) | 2024.07.16 |
50. 햄버거 만들기 ★ (0) | 2024.07.16 |
49. 숫자 짝꿍 ★ (Counter, union) (0) | 2024.07.16 |