-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInfixToPostFix.py
89 lines (59 loc) · 1.99 KB
/
InfixToPostFix.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
def getPriority(op):
if op is '-' or op is '+':
return 1
elif op is '*' or op is '/':
return 2
elif op is '^':
return 3
else:
return 5
def isOperator(op):
return op is '^' or op is '-' or op is '+' or op is '*' or op is '/'
def isOpening(brac):
if brac == '(':
return True
return False
def isClosing(brac):
if brac == ')':
return True
return False
def isOperand(op):
return op.isalpha() or op.isnumeric()
def inFixToPostFix(expr):
experssion = list(expr)
stack = []
top = -1
output = []
for item in experssion:
if isOpening(item):
output.append(item)
stack.append(item)
top+=1
elif isClosing(item):
if len(stack) >= 1:
while len(stack) > 0 and not isOpening(stack[top]) :
output.append(stack[top])
del stack[top]
top -= 1
del stack[top]
top-=1
output.append(item)
elif isOperand(item):
output.append(item)
elif isOperator(item):
if len(stack) >= 1:
while len(stack) > 0 and getPriority(item) >= getPriority(stack[top]) :
output.append(stack[top])
del stack[top]
top -= 1
stack.append(item)
top+=1
else:
stack.append(item)
top+=1
print(output+stack)
inFixToPostFix('(A * (B + (C / D) ) )')
# Infix Postfix Prefix
# ( (A * B) + (C / D) ) # ( (A B *) (C D /) +) # (+ (* A B) (/ C D) )
# ((A * (B + C) ) / D) # ( (A (B C +) *) D /) # (/ (* A (+ B C) ) D)
# (A * (B + (C / D) ) ) # (A (B (C D /) +) *) # (* A (+ B (/ C D) ) )