-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfixToPostfix.py
More file actions
58 lines (53 loc) · 1.56 KB
/
infixToPostfix.py
File metadata and controls
58 lines (53 loc) · 1.56 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
from stack import stack
def infixTopost(inTopost):
prec = {}
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
s1 = stack()
pofixlist = []
tokenList = inTopost.split()
for token in tokenList:
if token not in "*/+-()":
pofixlist.append(token)
elif token == "(":
s1.push(token)
elif token == ")":
toptok = s1.pop()
while toptok != "(":
pofixlist.append(toptok)
toptok = s1.pop()
else:
while not (s1.isEmpty()) and (prec[s1.peek()] >= prec[token]):
pofixlist.append(s1.pop())
s1.push(token)
while not s1.isEmpty():
pofixlist.append(s1.pop())
return " ".join(pofixlist)
def postfixeval(postfixex):
s = stack()
tokenlist = postfixex.split()
for token in tokenlist:
if token not in ("+-*/"):
s.push(int(token))
else:
operand2 = s.pop()
operand1 = s.pop()
result = domath(token, operand1, operand2)
s.push(result)
return s.pop()
def domath(token, operand1, operand2):
if token == "*":
return operand1 * operand2
elif token == "/":
return operand1 / operand2
elif token == "+":
return operand1 + operand2
else:
return operand1 - operand2
expr = input("enter your expressioin with space between items or numbers: ")
postfix = infixTopost(expr)
result = postfixeval(postfix)
print(result)