파이썬 알고리즘 153번 | [백준 1935번] 후위표기 - 스택

Yunny.Log ·2022년 5월 20일
0

Algorithm

목록 보기
156/318
post-thumbnail

153. 후위표기

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

  • 스택에 넣고 연산자 발견하면 뽑기

2) 코딩 설명

<내 풀이>


import sys
from collections import deque
n=int(sys.stdin.readline().strip())
s=list(sys.stdin.readline().strip())
r=[]
qu = deque()

for i in range(n):
    r.append(int(sys.stdin.readline().strip()))

for i in range(len(s)):#식의 길이만큼 돌면서
    # print(i,"번째", s[i])
    if s[i].isalpha() :
        qu.append(r[ord(s[i])-65])
        # print(qu)
        # print("야호",alphaidx)
    else :
        b=qu.pop()
        a=qu.pop()
        if s[i]=="+":
            qu.append(a+b)
        elif s[i]=="-":
           qu.append(a-b)
        elif s[i]=="/":
           qu.append(a/b)
        elif s[i]=="*":
            qu.append(a*b)
# print(qu[0])
#소수점 두자리
print(format(qu[0], ".2f"))

<내 틀렸던 풀이, 문제점>


import sys
from collections import deque
n=int(sys.stdin.readline().strip())
s=list(sys.stdin.readline().strip())
r=[]
qu = deque()

for i in range(n):
    r.append(int(sys.stdin.readline().strip()))

alphaidx =0

for i in range(len(s)):#식의 길이만큼 돌면서
    if s[i].isalpha() :
        qu.append(r[alphaidx])
        alphaidx+=1
        # print(qu)
        # print("야호",alphaidx)
    else :
        b=qu.pop()
        a=qu.pop()
        if s[i]=="+":
            qu.append(a+b)
        elif s[i]=="-":
           qu.append(a-b)
        elif s[i]=="/":
           qu.append(a/b)
        elif s[i]=="*":
            qu.append(a*b)
print(qu[0])

1
AA+A+
1

이런 문자가 하나인 경우를 고려하지 않고, alphaidx 라는 값으로 계속 증가하게 해서 r에서 해당하는 인덱스를 가져오게 하는 방식을 취했어서 처음에 틀렸음

<반성 점>

<배운 점>

  • 소수점 2자리로 출력하는 방법
    https://jsikim1.tistory.com/226

    num = 3.14159265358979
    print("기존 값 : ", num)
    print("소수 첫번째 자리까지 표기: ", format(num, ".1f"))
    print("소수 두번째 자리까지 표기: ", format(num, ".2f"))
    print("소수 세번째 자리까지 표기: ", format(num, ".3f"))
    print("소수 네번째 자리까지 표기: ", format(num, ".4f"))
    print("format() 사용 타입 : ", type(format(num)))

0개의 댓글