후위 표기식2(python 1935)
변수의 개수를 미리 받는 이유는 변수의 값을 따로 저장해놓을 리스트를 먼저 선언하기 위함이다
또한 후위 연산은 stack의 pop을 활용하여 계산한다
소수점 2자리까지 표현하는건 %.2f 함수를 활용한다
N = int(input())
s = str(input())
num = [0] * N
post_stack = []
for i in range(N):
num[i] = int(input())
for i in s:
if i.isalnum():
post_stack.append(num[ord(i) - ord('A')])
else:
n2 = post_stack.pop()
n1 = post_stack.pop()
if i == '+':
post_stack.append(n1 + n2)
elif i == '-':
post_stack.append(n1 - n2)
elif i == '*':
post_stack.append(n1 * n2)
elif i == '/':
post_stack.append(n1 / n2)
print('%.2f' %post_stack[0])
'algorithm' 카테고리의 다른 글
알고리즘 기초 1/2 203-자료구조(참고): 알파벳 개수 (0) | 2025.05.27 |
---|---|
알고리즘 기초 1/2 203-자료구조(참고): 후위 표기식 (0) | 2025.05.26 |
알고리즘 기초 1/2 201-자료구조(연습): 오등큰수 (0) | 2025.04.29 |
알고리즘 기초 1/2 201-자료구조(연습): 오큰수 (0) | 2025.04.21 |
알고리즘 기초 1/2 201-자료구조(연습): 쇠막대기 (0) | 2025.04.16 |