Created
November 10, 2017 02:59
-
-
Save taylorsmithgg/36cfd02fc8a650e238ffbdc4582fca7b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pythonds.basic.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 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 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) | |
print(infixToPostfix("A * B + C * D")) | |
print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment