Huin999 2021. 7. 27. 16:49
 

Codewars: Achieve mastery through challenge

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

www.codewars.com

▶  문제 : 

▶  내 답안 : 

def escape(carpark):
    if carpark == [[0, 0, 0, 0, 2]] :
        return []
    command = []
    D = 1
    i = 0
    while i < len(carpark) :
        try : 
            start = carpark[i].index(2)
            stair = carpark[i].index(1)
            if start > stair :
                command.append(f'L{start-stair}')
                if carpark[i+1][stair] == 0 :
                    carpark[i+1][stair] = 2
                    command.append(f'D{D}')                
                else :
                    D += 1
                    i += 1
                    if carpark[i+1][stair] == 0 :
                        command.append(f'D{D}')
            if start < stair :
                command.append(f'R{stair-start}')
                if carpark[i+1][stair] == 0 :
                    carpark[i+1][stair] = 2
                    command.append(f'D{D}')
                else :
                    D += 1
                    i += 1
                    if carpark[i+1][stair] == 0 :
                        command.append(f'D{D}')
            i += 1
        except :
            if stair != 4 :
                command.append(f'R{4-stair}')
            else :
                command.append(f'D{D+1}')
            break
    return command

▶  모범답안 : 

def escape(carpark):
    while 2 not in carpark[0]: carpark.pop(0)
    r, ground, pos = [], len(carpark) - 1, carpark[0].index(2)
    for f, floor in enumerate(carpark):
        stairs = floor.index(1) if f != ground else len(floor) - 1
        if stairs != pos:
            r, pos = r + ['RL'[stairs < pos] + str(abs(pos - stairs))], stairs
        if f != ground:
            r += [('D' + str(int(r.pop()[1:]) +1)) if 'D' in r[-1] else 'D1']
    return r

▶  배워야할 부분 : 

1. 랜덤 스타트 포지션 잡는 부분을 공부해야함