KEEP GOING

[python] 프로그래머스 17682번 : 다트게임 (ord, isnumeric) 본문

code review/implementation

[python] 프로그래머스 17682번 : 다트게임 (ord, isnumeric)

jmHan 2022. 4. 1. 11:06
반응형

https://programmers.co.kr/learn/courses/30/lessons/17682

 

코딩테스트 연습 - [1차] 다트 게임

 

programmers.co.kr

 

 

 

def solution(dartResult):
    arr = []
    for idx, dart in enumerate(dartResult):
        # '*', '#'이 아닌 문자라면 
        if 65 <= ord(dart) <= 90:
            k = idx - 1 # 숫자 10을 처리하기 위한 변수 
            if dartResult[idx-1] == '0' and idx-2 >= 0 and dartResult[idx-2] == '1':
                k = idx - 2
                # print('hello')
            if dart == 'S':
                arr.append(int(dartResult[k:idx])**1)
            elif dart == 'D':
                arr.append(int(dartResult[k:idx])**2)
            else:
                arr.append(int(dartResult[k:idx])**3)
        else:
            # 스타상인 경우 
            if dart == '*':
                point = 2
                pre = arr.pop()
                if not arr:
                    arr.append(pre * point)
                else:
                    pre2 = arr.pop()
                    arr.append(pre2 * point)
                    arr.append(pre * point)
            # 아차상인 경우
            elif dart == '#':
                pre = arr.pop()
                arr.append(-pre)
    return sum(arr)

18번과 22번 테스트 케이스만 틀려서 질문하기란을 확인해보니 스타상 *을 처리하는데에서 문제가 있어보였다.

pre2가 pre보다 이전 회차의 점수이기 때문에 pre보다 pre2를 먼저 arr이라는 점수 저장 배열에 저장해줘야 한다.

하지만 둘의 순서를 뒤바꿔서 배열에 append 하였기에 문제가 생겼다. 

다시말해

arr.append(pre * point)

arr.append(pre2 * point)

 

arr.append(pre2 * point)
arr.append(pre * point) 로 수정해주었더니 문제가 해결되었다 : ) 

 

 

 

[코드 개선]

def solution(dartResult):
    answer = 0
    arr = []
    s = ''
    for dart in dartResult:
        # '*', '#'이 아닌 문자라면 
        if dart.isnumeric():
            s += dart
        elif dart == 'S':
            arr.append(int(s)**1)
            s = ''
        elif dart == 'D':
            arr.append(int(s)**2)
            s = ''
        elif dart == 'T':
            arr.append(int(s)**3)
            s = ''
        else:
            # 스타상인 경우 
            if dart == '*':
                point = 2
                if len(arr) < 2:
                    arr[-1] = arr[-1]*point
                else:
                    arr[-2] = arr[-2]*point
                    arr[-1] = arr[-1]*point
            # 아차상인 경우
            elif dart == '#':
                arr[-1] = -arr[-1]
                
    return sum(arr)

스타상이랑 아차상에 대해

점수를 저장한 배열에서 pop한 원소(점수)를 조건 처리 후 append 해주었는데 

배열에 직접 접근하는 방법이 있어서 가져와봤다.

arr[-1] = arr[-1] * point

이런식으로 접근 가능

그리고 나는 ord를 이용해 숫자임을 판별해주었는데 이렇게 하면 숫자가 10이 들어올 때 

'1'과 '0'으로 인식되므로 조건이 까다로워져서 코드가 복잡해졌었다.

이 대신에 s라는 문자열을 두어 

isnumeric이라는 문자열 내장함수를 이용하여 숫자인 경우 s에 저장해두고

S나 D, T, *, #가 오는 경우 저장된 점수를 처리해줌으로써 깔끔하게 코드를 작성할 수 있었다.

반응형
Comments