-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3.9.2-infixToPsotfix.py
More file actions
37 lines (32 loc) · 1.06 KB
/
3.9.2-infixToPsotfix.py
File metadata and controls
37 lines (32 loc) · 1.06 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
#! /usr/bin/env python3
# 3.9-Infix Expressions To Postfix Expressions
from Stack import Stack
def infixToPostfix(infixExpr):
prec = {}
prec['*'] = 3
prec['/'] = 3
prec['+'] = 2
prec['-'] = 2
prec['('] = 1
opStack = Stack()
postfixList = []
tokenList = infixExpr.split()
for token in tokenList:
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYX" or token in "0123456789":
postfixList.append(token)
elif token == "(":
opStack.push(token)
elif token == ")":
topToken = opStack.pop()
while topToken != '(':
postfixList.append(topToken)
topToken = opStack.pop()
else:
while (not opStack.isEmpty()) and prec[opStack.peek()] >= prec[token]:
postfixList.append(opStack.pop())
opStack.push(token)
while not opStack.isEmpty():
postfixList.append(opStack.pop())
return " ".join(postfixList)
s = input("Pleast input a infix Expression:")
print("The Postfix Expression Is :", infixToPostfix(s))