๐์ ์ฒด ์ฝ๋
import sys
sys.stdin=open("C:\\input.txt",'rt')
a = input()
print(a)
stack = []
res = ''
for x in a:
# x๊ฐ ์ซ์์ผ ๊ฒฝ์ฐ
if x.isdecimal():
stack.append(int(x))
# 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])
๐ ํ์ ํ๊ธฐ๋ฒ ๊ณ์ฐ๋ฒ
ํ์ ํ๊ธฐ๋ฒ์์๋ ์ฐ์ฐ์๊ฐ ๋ค์ ์์นํ๊ธฐ ๋๋ฌธ์,
์ผ์ชฝ์์ ์ค๋ฅธ์ชฝ์ผ๋ก ์ฝ์ผ๋ฉด์ ์ซ์๋ ์คํ์ ๋ฃ๊ณ , ์ฐ์ฐ์๋ ๊บผ๋ด์ ๊ณ์ฐํ๋ฉด ๋ผ.
๐ ํ์ ํ๊ธฐ๋ฒ ์์
๋ณต์ฌํธ์ง
3 5 2 * + 8 -
→ ๊ณ์ฐ ์์:
- 3 → ์คํ์ push
- 5 → ์คํ์ push
- 2 → ์คํ์ push
- * → 5 * 2 = 10, ๊ฒฐ๊ณผ๋ฅผ ์คํ์ push
- + → 3 + 10 = 13, ๊ฒฐ๊ณผ๋ฅผ ์คํ์ push
- 8 → ์คํ์ push
- - → 13 - 8 = 5, ๊ฒฐ๊ณผ๋ฅผ ์คํ์ push
โก ์ต์ข ๊ฒฐ๊ณผ = 5
๐ ์ฝ๋ ๋ถ์
import sys sys.stdin = open("C:\\Users\\csh\\Documents\\์ฝ๋ฉํ
์คํธ\\์๋ฃ๊ตฌ์กฐํ์ฉ(์คํ,ํ,ํด์ฌ,ํ)\\input.txt", 'rt') a = input() # ํ์ ํ๊ธฐ๋ฒ ์์ ์
๋ ฅ print(a) stack = [] # ์ซ์๋ฅผ ์ ์ฅํ ์คํ
- a: ํ์ ํ๊ธฐ๋ฒ ์์ (๊ณต๋ฐฑ ์์ด ์ ๋ ฅ)
- stack: ์ซ์ ์ ์ฅ์ ์ํ ์คํ
๐ข ์ซ์์ธ ๊ฒฝ์ฐ → ์คํ์ push
if x.isdecimal(): stack.append(int(x))
- isdecimal() → ์ซ์์ธ์ง ํ์ธ
- ์ซ์๋ฉด ์ ์ํ์ผ๋ก ๋ณํํด์ ์คํ์ push
โโ ๊ณฑ์ /๋๋์ ์ฒ๋ฆฌ
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)
- ์ฐ์ฐ์๊ฐ ๋์ค๋ฉด ์คํ์์ ๋ ๊ฐ์ ์ซ์๋ฅผ ๊บผ๋
- n2๊ฐ ๋จผ์ pop() → ์ฐ์ฐ์ ์ผ์ชฝ ์ซ์
- n1์ด ๋ค์ pop() → ์ฐ์ฐ์ ์ค๋ฅธ์ชฝ ์ซ์
- ๊ณ์ฐ ํ ๊ฒฐ๊ณผ๋ฅผ ๋ค์ ์คํ์ push
โ ์ต์ข ๊ฒฐ๊ณผ ์ถ๋ ฅ
print(stack[0])
- ์คํ์ ๋ง์ง๋ง ๊ฐ์ด ์ ๋ต์ด๋ฏ๋ก ์ถ๋ ฅ
๐ก ์คํ ์์
์ ๋ ฅ
352*+8-
๊ณ์ฐ ๊ณผ์ (์คํ ์ํ)
๋ฌธ์์ฐ์ฐ์คํ ์ํ
3 | push | [3] |
5 | push | [3, 5] |
2 | push | [3, 5, 2] |
* | 5 * 2 = 10 → push | [3, 10] |
+ | 3 + 10 = 13 → push | [13] |
8 | push | [13, 8] |
- | 13 - 8 = 5 → push | [5] |
์ถ๋ ฅ ๊ฒฐ๊ณผ
5
โณ ์๊ฐ ๋ณต์ก๋ ๋ถ์
- O(n) → ํ์ ํ๊ธฐ๋ฒ ์์์ ํ ๋ฒ๋ง ์ํํ๋ฉด์ ์ฐ์ฐ
- ์คํ ์ฐ์ฐ(push, pop) → O(1) ์ด๋ฏ๋ก ์ ์ฒด์ ์ผ๋ก ๋งค์ฐ ๋น ๋ฆ
๐น ์ ๋ฆฌ
โ
ํ์ ํ๊ธฐ๋ฒ ์์์ ์คํ์ ์ฌ์ฉํด ๊ณ์ฐ
โ
์ฐ์ฐ์๋ฅผ ๋ง๋๋ฉด ์ซ์ ๋ ๊ฐ๋ฅผ ๊บผ๋ด์ ๊ณ์ฐ ํ ๋ค์ push
โ
์๊ฐ ๋ณต์ก๋ O(n), ๋งค์ฐ ํจ์จ์