백준 1918 파이썬 (후위표기식)

철웅·2022년 11월 17일
0

BOJ

목록 보기
14/46

문제 : https://www.acmicpc.net/problem/1918

  1. A~Z (피연산자)는 바로 result에
  2. * or / 일 경우
    stack이 존재하고 top이 (이 아니라면 -> 괄호 연산이라면 괄호가 끝날때까지
    stack의 top이 * 또는 / 이 이라면 -> 같은 기호에 우선순위가 밀리지 않는다면(이미 있는 *, /)
    -> stack의 top을 result에 추가, stack에 append
  3. + or -일 경우
    stack이 존재하고 괄호 연산이라면 괄호가 끝날때까지 -> stack의 top을 result에 추가, stack에 append
  4. (일 경우 -> stack에 append
  5. )일 경우
    괄호연산이 끝날때까지 stack의 top을 result에 추가
  6. 나머지 남는 문자들 result에 추가

💻 Code

import sys

data = sys.stdin.readline().rstrip()
stack = []
result = ""

for i in data:
    if('A' <= i <= 'Z'):
        result += i
    else:
        if(i == '('):
            stack.append(i)
        elif(i==')'):
            while(stack and stack[-1] != '('):
                result += stack.pop()
            stack.pop() # '(' 수거
        elif(i == '*' or i == '/'):
            while(stack and stack[-1] != '(' and (stack[-1] == '*' or stack[-1] == '/')):
                    result += stack.pop()
            stack.append(i)
        elif(i == '+' or i == '-'):
            while(stack and stack[-1] != '('):
                result += stack.pop()
            stack.append(i)
     
while(stack):
    result += stack.pop()

print(result)

  • while(stack and stack[-1] != '(' and (stack[-1] == '*' or stack[-1] == '/')):
    한 줄을 길게 작성하는게 여러줄 적는 것보다는 나쁘지 않을수도?

🔎 전체 흐름

0개의 댓글