유형: 구현

풀이 시간: 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)
복사했습니다!