-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13. Stack_postfixEval.py
More file actions
104 lines (85 loc) · 2.76 KB
/
13. Stack_postfixEval.py
File metadata and controls
104 lines (85 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# 지금까지는 A+B와 같이 각 피연산자가 하나의 문자로 구성되어 수식을 문자열 형태로 보아도 무방했으나, ex) "A+B"
# 현실에서는 120+34와 같은 형식으로 많이 쓰이므로
# 120같은 피연산자를 하나의 수로 보기위해 리스트를 사용했다. ex) [120, '+', 34]와 같이 ,,,
# 결과적으로 중위표현식을 후위표현식으로 바꾸는 코드또한 달라져야한다.
class ArrayStack:
def __init__(self):
self.data = []
def size(self):
return len(self.data)
def isEmpty(self):
return self.size() == 0
def push(self, item):
self.data.append(item)
def pop(self):
return self.data.pop()
def peek(self):
return self.data[-1]
# 3 + 7 따위의 수식을 [3, '+', 7]로 만들기
def splitTokens(exprStr):
tokens = []
val = 0
valProcessing = False
for c in exprStr:
if c == ' ':
continue
if c in '0123456789':
val = val * 10 + int(c)
valProcessing = True
else:
if valProcessing:
tokens.append(val)
val = 0
valProcessing = False
tokens.append(c)
if valProcessing:
tokens.append(val)
return tokens
# 중위표현식(3+7)을 후위표현식(37+)로 바꾸기
def infixToPostfix(tokenList):
prec = {
'*': 3,
'/': 3,
'+': 2,
'-': 2,
'(': 1,
}
opStack = ArrayStack()
postfixList = []
for t in tokenList:
if type(t) == int:
postfixList.append(t)
elif t == '(':
opStack.push(t)
elif t == ')':
while opStack.peek() != '(':
postfixList.append(opStack.pop())
opStack.pop()
elif t in prec:
while not opStack.isEmpty() and prec[opStack.peek()] >= prec[t]:
postfixList.append(opStack.pop())
opStack.push(t)
while not opStack.isEmpty():
postfixList.append(opStack.pop())
return postfixList
# 후위표현식(37+) 계산
def postfixEval(tokenList):
opStack = ArrayStack()
for token in tokenList:
if type(token) == int:
opStack.push(token)
else:
if token == '+':
opStack.push(opStack.pop() + opStack.pop())
elif token == '-':
opStack.push(-opStack.pop() + opStack.pop())
elif token == '*':
opStack.push(opStack.pop() * opStack.pop())
elif token == '/':
opStack.push(1/opStack.pop() * opStack.pop())
return opStack.pop()
tokens = splitTokens('(11 + 34) * 4')
postfix = infixToPostfix(tokens)
val = postfixEval(postfix)
print(postfix)
print(val)