상세 컨텐츠

본문 제목

5.4 후위 연산

Algorithm/inflearn python algorithm

by 개복신 개발자 2021. 7. 22. 20:44

본문

728x90
반응형
후위식 연산
후위연산식이 주어지면 연산한 결과를 출력하는 프로그램을 작성하세요.
만약 3*(5+2)-9 을 후위연산식으로 표현하면 352+*9- 로 표현되며 그 결과는 21입니다.

▣ 입력설명
첫 줄에 후위연산식이 주어집니다. 연산식의 길이는 50을 넘지 않습니다.
식은 1~9의 숫자와 +, -, *, /, (, ) 연산자로만 이루어진다.

▣ 출력설명
연산한 결과를 출력합니다.

▣ 입력예제 1
352+*9-

▣ 출력예제 1
12

내 풀이

a=input()
stack=[]
res=0
for i in a:
    if i.isdecimal():
        stack.append(i)
    else:
        if i=="+":
            res+=int(stack[-1])+int(stack[-2])
            for i in range(2):
                stack.pop()
            stack.append(res)
            res=0
        elif i=="-":
            res+=int(stack[-2])-int(stack[-1])
            for i in range(2):
                stack.pop()
            stack.append(res)
            res=0
        elif i=="*":
            res+=int(stack[-1])*int(stack[-2]) 
            for i in range(2):
                stack.pop()
            stack.append(res)
            res=0
        elif i=="/":
            res+=int(stack[-2])/int(stack[-1])
            for i in range(2):
                stack.pop()
            stack.append(res)
            res=0

res=''.join(map(str,stack))
print(res)

 

강의 풀이

a=input()
stack=[]
for x in a:
    if x.isdecimal():
        stack.append(int(x))
    else:
        if x=="+":
            n1=stack.pop()
            n2=stack.pop()
            stack.append(n2+n1)
        elif x=="-":
            n1=stack.pop()
            n2=stack.pop()
            stack.append(n2-n1)
        elif x=="*":
            n1=stack.pop()
            n2=stack.pop()
            stack.append(n2*n1)
        elif x=="/":
            n1=stack.pop()
            n2=stack.pop()
            stack.append(n2/n1)
print(stack[0])

-처음에 스택에 넣을 때 int로 변환함

내 풀이에서는 str형태로 스택에 집어넣어 꺼내서 계산할 때 변환함-->비효율적

애초에 처음부터 int로 변환해야 코드가 간결해짐

 

-n1=stack.pop() n2=stack.pop()

스택의 마지막 요소를 삭제하고 n1, n2에 입력해서 계산

계산 따로 pop 따로 한 내 코드보다 간결함

 

반응형

'Algorithm > inflearn python algorithm' 카테고리의 다른 글

트리  (0) 2021.07.31
5.5 공중 구하기(큐)  (0) 2021.07.23
5.3 후위 표기식 만들기(스택)  (0) 2021.07.22
5.2 쇠막대기(스택)  (0) 2021.07.22
5.1 가장 큰 수 (스택)  (0) 2021.07.19

관련글 더보기

댓글 영역