-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfixToPrefix.py
71 lines (55 loc) · 1.55 KB
/
infixToPrefix.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
'''
Infix to postfix
'''
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 infix_to_postfix(infix):
opstack = Stack()
outstack = []
token_list = infix.split(' ')
# 연산자의 우선순위 설정
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() != '('):
outstack.append(opstack.pop())
opstack.pop()
elif token in '+-/*^':
while (not opstack.isEmpty() and prec[token] <= prec[opstack.top()]):
outstack.append(opstack.pop())
opstack.push(token)
else: # operand일 때
outstack.append(token)
# opstack 에 남은 모든 연산자를 pop 후 outstack에 append
# ... ... ...
while (not opstack.isEmpty()):
outstack.append(opstack.pop())
return " ".join(outstack)
infix_expr = input()
postfix_expr = infix_to_postfix(infix_expr)
print(postfix_expr)