관리 메뉴

Mini

프로그래머스 다트게임 python // 문자열파싱 정규식 본문

Algorithm/programmers

프로그래머스 다트게임 python // 문자열파싱 정규식

Mini_96 2023. 7. 12. 01:47

https://school.programmers.co.kr/learn/courses/30/lessons/17682?language=python3# 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

* Python spagetti

- 문제 : 단순히 이전값을 더하는방식은 문제에어긋남

//보너스 score+=현재값*2+이전값

- 해결 : list에 각각을 push하고

*을 만나면 [i-1]과 [i]를 2배하고

마지막에 list합을 계산

def solution(dartResult):
    answer = 0
    
    #숫자앞에 구분자넣기
    s=""
    pre=False   #이전값이 숫자엿는지
    isTen=[]    #10의 index저장
    
    for i in range(len(dartResult)): 
        
        if(pre==True and dartResult[i].isdigit()):
            s+=dartResult[i]
            isTen.append(i-1)
            continue
        if(pre==False and dartResult[i].isdigit()):
            pre=True
            s=s+"/"
        else:
            pre=False
        s+=dartResult[i]
        
    s=s[1:] #첫번쨰 / 지우기
    print(s)
    print(isTen)
    
    a=s.split("/")
    #print(a)
    pre=0   #이전점수저장
    
    idx=0
    i=0
    scores=[]
    for token in a:
        score=0 #현재점수저장
        print("###################################")
        print("prev : ",pre)
        
        #10이 포함된경우이면
        if(len(isTen) and idx in isTen):
            print("idx : ",idx)
            if(len(token)==4):
                p=0
                if(token[2]=="S"):
                    p=1
                elif(token[2]=="D"):
                    p=2
                elif(token[2]=="T"):
                    p=3
                
                if(token[3]=="*"):
                    #score+=10**p*2
                    #10 10 *
                    scores.append(10**p)
                    scores[i]=scores[i]*2
                    if(i>=1):
                        scores[i-1]=scores[i-1]*2
                elif(token[3]=="#"):
                    #score+=-1* 10**p
                    scores.append(-1*10**p)
                
            #print(answer)
            elif(len(token)==3):
                p=0
                if(token[2]=="S"):
                    p=1
                elif(token[2]=="D"):
                    p=2
                elif(token[2]=="T"):
                    p=3
                scores.append(10**p)
                #score=10**p
                #print(answer)
            
            idx+=len(token)    
            #pre=score
            #answer+=score
            print(token)
            print("score: " , score)
            print("answer: ",answer)
            continue
        
        #10이 안포함된경우
        print(token)
        if(len(token)==3):
            p=0
            if(token[1]=="S"):
                p=1
            elif(token[1]=="D"):
                p=2
            elif(token[1]=="T"):
                p=3
                
            if(token[2]=="*"):
                #score+=int(token[0])**p*2 + pre
                scores.append(int(token[0])**p)
                scores[i]=scores[i]*2
                if(i>=1):
                    scores[i-1]=scores[i-1]*2
            elif(token[2]=="#"):
                #score+=-1* int(token[0])**p
                scores.append(-1*int(token[0])**p)
            #print(answer)
        elif(len(token)==2):
            p=0
            if(token[1]=="S"):
                p=1
            elif(token[1]=="D"):
                p=2
            elif(token[1]=="T"):
                p=3
            scores.append(int(token[0])**p)

                        
        #answer+=score
        idx+=len(token)    
        i+=1
        #pre=score
        #print("score: " , score)
    
    for s in scores:
        answer+=s
    return answer

 

* 정규표현식 파이썬

import re
#re.compile(r'([대상리스트]|대상)([대상리스트])([대상리스트]옵셔널)')
p=re.compile(r'([1-9]|10)([SDT])([*#]?)')

p.findall("10S2D*3T")
[('10', 'S', ''), ('2', 'D', '*'), ('3', 'T', '')]

 

※ 0도 입력에올수잇음에 주의하자. 

re.compile([1-9] )X

re.compile([0-9]) O

import re

def solution(dartResult):

    p=re.compile(r'([0-9]|10)([SDT])([*#]?)')
    v=p.findall(dartResult)
    print(v)
    
    scores=[]
    #1s / 2d* /3t
    for num, bonus, opt in v:
        #score=0
        if(bonus=='S'):
            score=int(num)**1
        elif(bonus=='D'):
            score=int(num)**2
        elif(bonus=='T'):
            score=int(num)**3 
        
        if(opt=='#'):
            score*=-1
        elif(opt=='*'):
            score*=2
            #이전점수가 있는경우 이전점수2배
            if(scores):
                scores[-1]*=2
                #idx :  -3 -2 -1
                #list : 12 35 96
        scores.append(score)
    
    print(scores)
    return sum(scores)