파이썬 알고리즘 147번 | [백준 2504번] 괄호의 값 - 스택 (진행 중)

Yunny.Log ·2022년 5월 10일
0

Algorithm

목록 보기
150/318
post-thumbnail

147. 괄호의 값

1) 어떤 전략(알고리즘)으로 해결?

2) 코딩 설명

<내 풀이>



<다른 분의 풀이 or 내 틀린 풀이, 문제점>

=> 테스트 케이스는 잘 돌아가는데, 어딘가에서 Index Error가 발생한다고 한다.

import sys
stk=[]
cnt=0 #덩어리마다의 점수 모으기
scoreround=1#덩어리마다 갱신 예정
scoresquare=1
strr=list(sys.stdin.readline())
score=0
chk=0
for i in range(len(strr)):
    #print(stk)
    #print(strr[i])

    if strr[i]=="(":
        stk.append(strr[i])

    elif strr[i]=="[":
        stk.append(strr[i])

    elif strr[i]==")":
        idx=len(stk)-1 # 스택의 맨 마지막 인덱스부터

        while stk[idx] != "(" and stk:
            idx-=1
            if idx<0 :
                chk=1
                break

        else : #만났다면 
            if len(stk)>idx+1:
                push=0
                sumidx=idx+1
                #print(len(stk))
                #print(sumidx)

                while sumidx<len(stk) and stk[sumidx]!="(" and stk[sumidx]!="[":
                    # 내 앞에 있는 정수들 <()이나[] 만나기 전)을 다 누적해서 더해주기
                    if type(stk[sumidx])==int:
                        #print("int")
                        #print(stk[sumidx])
                        push+=stk[sumidx]
                        stk.pop(sumidx)
                    else :
                        sumidx+=1

                if push==0: 
                    #첫번째 IF문에 걸렸었으나 내 앞에 있는게 다 ( 또는 [ 였다면(앞에 암것도 없었다면)
                    push=1

                stk.pop(idx)
                stk.insert(idx,push*2)

            else : #내 앞에 아무것도 없다면
                stk.append(2)
                stk.pop(idx)    


    elif strr[i]=="]":
        idx=len(stk)-1 # 스택의 맨 마지막 인덱스부터

        while stk[idx] != "[" and stk:
            idx-=1
            if idx<0 :
                break

        else : #만났다면 
            if len(stk)>idx+1:
                push=0
                sumidx=idx+1
                while sumidx<len(stk) and stk[sumidx]!="(" and stk[sumidx]!="[":
                    if type(stk[sumidx])==int:
                        push+=stk[sumidx]
                        stk.pop(sumidx)
                    else :
                        sumidx+=1

                if push==0: #첫번째 IF문에 걸렸었으나 내 앞에 있는게 다 ( 또는 [ 였다면
                    push=1

                stk.pop(idx)
                stk.insert(idx,push*3)

            else : #내 앞에 아무것도 없다면
                stk.append(3)
                stk.pop(idx)    

for i in stk :
    if type(i)!=int:
        chk=1

if chk==0:
    print(sum(stk))
else : print(0)

인덱스에러 발생구간

나는 항상 테스트 케이스, 예외처리할 때 값이 엄청 단순한 경우 ( 딱 입력이 하나만 들어간다거나 0이 들어간다거나)를 빼먹고 생각해서 늘 에러를 겪는다. 아래서부터 차근차근 생각해나가자

인덱스 에러 수정

스택이 있는지 여부부터 확인한 다음에 stk[idx]를 조사하는 것으로 수정 !!

70% 구간에서 실패하고 말았다. why?

이 경우는 성립이 안돼야하는데 돌아간다;;
적절히 아닌 경우를 판별해야 한다.

  • 이런 식으로 chk 하는 걸 더 촘촘히 해주었는데 안된다 흑흑 (72 퍼)

아항~ 이것도 올바르지 않은 애들이래

([(]))
10
지금 난 이것도 되게 되거든..

  • 이건 어떻게 걸러내지?
    • 아 근데 이거 걸러내는 것 easy ..
      오히려 저 경우는 내 앞에 바로 나와 다른 괄호가 없는 경우.. 저 조건을 미리 염두에 뒀으면 구현도 쉬워졌는디 문제를 잘 읽자구나

95%까지 맞은 풀이..

import sys
stk=[]
cnt=0 #덩어리마다의 점수 모으기
scoreround=1#덩어리마다 갱신 예정
scoresquare=1
strr=list(sys.stdin.readline())
score=0
chk=0
for i in range(len(strr)):
    #print(stk)
    #print(strr[i])

    if strr[i]=="(":
        stk.append(strr[i])

    elif strr[i]=="[":
        stk.append(strr[i])

    elif strr[i]==")":
        idx=len(stk)-1 # 스택의 맨 마지막 인덱스부터

        while stk and stk[idx] != "(" :
            if stk[idx]=="[": # [(] 이런 경우는 안되니깐
                chk=1
            idx-=1
            if idx<0 :
                chk=1 #이 경우에도 체크해주는 (예외 처리 추가)
                break


        else : #만났다면 
            if len(stk)>idx+1:
                push=0
                sumidx=idx+1

                while sumidx<len(stk) and stk[sumidx]!="(" and stk[sumidx]!="[":
                    # 내 앞에 있는 정수들 <()이나[] 만나기 전)을 다 누적해서 더해주기
                    if type(stk[sumidx])==int:
                        #print("int")
                        #print(stk[sumidx])
                        push+=stk[sumidx]
                        stk.pop(sumidx)
                    else :
                        sumidx+=1

                if push==0: 
                    #첫번째 IF문에 걸렸었으나 내 앞에 있는게 다 ( 또는 [ 였다면(앞에 암것도 없었다면)
                    push=1

                stk.pop(idx)
                stk.insert(idx,push*2)

            else : #내 앞에 아무것도 없다면
                stk.append(2)
                stk.pop(idx)    


    elif strr[i]=="]":

        idx=len(stk)-1 # 스택의 맨 마지막 인덱스부터

        while stk and stk[idx] != "[" :
            if stk[idx]=="(": # [(] 이런 경우는 안되니깐
                chk=1
            idx-=1
            #print(idx)
            if idx<0 :
                chk=1 #이 경우에도 체크해주는 (예외 처리 추가)
                break


        else : #만났다면 

            if len(stk)>idx+1:
                push=0
                sumidx=idx+1
                while sumidx<len(stk) and stk[sumidx]!="(" and stk[sumidx]!="[":
                    if type(stk[sumidx])==int:
                        push+=stk[sumidx]
                        stk.pop(sumidx)
                    else :
                        sumidx+=1

                if push==0: #첫번째 IF문에 걸렸었으나 내 앞에 있는게 다 ( 또는 [ 였다면
                    push=1

                stk.pop(idx)
                stk.insert(idx,push*3)

            else : #내 앞에 아무것도 없다면
                stk.append(3)
                stk.pop(idx)    

for i in stk :
    if type(i)!=int:
        chk=1

if chk==0:
    print(sum(stk))
else : print(0)

  • 95% 까지 갔다가 막판에서 틀렸다구 한다. why??
  • 어떤 예왼지 참말로 궁금한데 , 지금은 더이상 생각이 안날 것 같아

<반성 점>

  • 지금 머리가 안돌아가나 .... 숫자를 스택에 덧붙이고 싶은데 생각이 안난다.
  • 이거 로직을 생각안하고 냅다 코드부터 짰더니 이 사단이 났다. 충분히 생각하고 그 다음 코드로 구현하는 것이 훨씬 더 빨라

<배운 점>

  • exit(0) 으로 바로 프로그램 종료하기 가능!

0개의 댓글