-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstackCalculator.py
119 lines (99 loc) · 3.1 KB
/
stackCalculator.py
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
class Stack:
def __init__(self):
self.items = []
def push(self, val):
self.items.append(val)
def pop(self):
try:
return self.items.pop()
except IndexError:
print("Stack is empty")
def top(self):
try:
return self.items[-1]
except IndexError:
print("Stack is empty")
def __len__(self):
return len(self.items)
def isEmpty(self):
return self.__len__() == 0
def get_token_list(expr):
token_list = []
operstack = Stack()
for i in range(len(expr)):
if expr[i] in '+-/*^()':
if operstack.isEmpty():
token_list.append(expr[i])
else:
temp_list = []
while (not operstack.isEmpty()):
temp_list.append(operstack.pop())
temp_list.reverse()
token_list.append(''.join(temp_list))
token_list.append(expr[i])
elif expr[i] == ' ':
continue
else:
operstack.push(expr[i])
if not operstack.isEmpty():
temp_list = []
while (not operstack.isEmpty()):
temp_list.append(operstack.pop())
temp_list.reverse()
token_list.append(''.join(temp_list))
# print(token_list)
return token_list
def infix_to_postfix(token_list):
opstack = Stack()
out_list = []
# 연산자의 우선순위 설정
prec = {}
prec['('] = 0
prec['+'] = 1
prec['-'] = 1
prec['*'] = 2
prec['/'] = 2
prec['^'] = 3
for token in token_list:
if token == '(':
opstack.push(token)
elif token == ')':
while (not opstack.isEmpty() and opstack.top() != '('):
out_list.append(opstack.pop())
opstack.pop()
elif token in '+-/*^':
while (not opstack.isEmpty() and prec[token] <= prec[opstack.top()]):
out_list.append(opstack.pop())
opstack.push(token)
else: # operand일 때
out_list.append(token)
# opstack 에 남은 모든 연산자를 pop 후 outstack에 append
# ... ... ...
while (not opstack.isEmpty()):
out_list.append(opstack.pop())
return out_list
def compute_postfix(token_list):
calstack = Stack()
for token in token_list:
if token in '+-*/^':
second_oper = float(calstack.pop())
first_oper = float(calstack.pop())
if token == '+':
val = first_oper + second_oper
elif token == '-':
val = first_oper - second_oper
elif token == '*':
val = first_oper * second_oper
elif token == '/':
val = first_oper / second_oper
else:
val = first_oper ** second_oper
calstack.push(val)
else:
calstack.push(token)
return calstack.pop()
# 아래 세 줄은 수정하지 말 것!
expr = input()
# value = infix_to_postfix(get_token_list(expr))
value = compute_postfix(infix_to_postfix(get_token_list(expr)))
print(value)