본문 바로가기
Engineering WIKI/Programmers

[프로그래머스] 다트 게임

by wonos 2022. 4. 11.

 

 

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

 

programmers.co.kr

 

내 풀이 (실패)

def solution(dartResult):
    
    temp_answer = list()

    score_dic = {'S' : 1,  'D' : 2, 'T' : 3}
    
    for i, word in enumerate(dartResult):
        answer = 0
    
        if word in score_dic:
            answer += pow(int(dartResult[i - 1]), score_dic[word])
            temp_answer.append(answer)
        
        if word == "*":
            temp_answer[len(temp_answer) - 1] = temp_answer[len(temp_answer) - 1] * 2
            
            temp_answer[len(temp_answer) - 2] = temp_answer[len(temp_answer) - 2] * 2

        elif word == "#":    
            temp_answer[-1] = temp_answer[-1] * -1
    print(temp_answer)
    return sum(temp_answer)

다른 방법

def solution(dartResult):
    stack = []
    dartResult = dartResult.replace("10", "A")
    bonus = {'S': 1, 'D': 2, 'T': 3}
    
    for i in dartResult:
        if i.isdigit() or i=='A':
            stack.append(10 if i == 'A' else int(i))
        elif i in ('S', 'D', 'T'):
            num = stack.pop()
            stack.append(num ** bonus[i])
        elif i == '#':
            stack[-1] *= -1
        elif i == '*':
            num = stack.pop()
            if len(stack):
                stack[-1] *= 2
            stack.append(2 * num)
    return sum(stack)

 

다른방법 2

def solution(dartResult):
    point = []
    answer = []
    dartResult = dartResult.replace('10','k')
    point = ['10' if i == 'k' else i for i in dartResult]
    print(point)

    i = -1
    sdt = ['S', 'D', 'T']
    for j in point:
        if j in sdt :
            answer[i] = answer[i] ** (sdt.index(j)+1)
        elif j == '*':
            answer[i] = answer[i] * 2
            if i != 0 :
                answer[i - 1] = answer[i - 1] * 2
        elif j == '#':
            answer[i] = answer[i] * (-1)
        else:
            answer.append(int(j))
            i += 1
    return sum(answer)