Last active
August 29, 2015 14:16
-
-
Save sooop/94db5b4ea22bf4af893b to your computer and use it in GitHub Desktop.
This file contains 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
import re | |
def expr_parse(exp): | |
assert isinstance(exp, str) | |
XRE = re.compile(r'(?:(?<=\D)(?=\d)|(?!=\d))', re.MULTILINE) | |
return re.sub(XRE, " ", exp) | |
class EmptyStackException(Exception): | |
pass | |
class Stack: | |
def __init__(self): | |
self._list = [] | |
def push(self, item): | |
self._list.append(item) | |
@property | |
def isEmpty(self): | |
return self._list == [] | |
def pop(self): | |
if self.isEmpty: | |
raise EmptyStackException("Stack is empty") | |
else: | |
return self._list.pop() | |
def peek(self): | |
if self.isEmpty: | |
return None | |
else: | |
return self._list[-1] | |
def convertToPostFix(expStr): | |
tokens = expr_parse(expStr).split(' ') | |
OPS = ("+", "-", "*", "/", "(", ")") | |
precs = { | |
"*" : 2, | |
"/" : 2, | |
"+" : 1, | |
"-" : 1, | |
"(" : 0, | |
} | |
opStack = Stack() | |
output = [] | |
for item in tokens: | |
if item not in OPS: | |
output.append(item) | |
elif item == "(": | |
opStack.push(item) | |
elif item == ")": | |
while opStack.peek() != "(": | |
output.append(opStack.pop()) | |
opStack.pop() | |
else: | |
done = False | |
while not opStack.isEmpty and not done: | |
if precs[opStack.peek()] >= precs[item]: | |
output.append(opStack.pop()) | |
else: | |
done = True | |
opStack.push(item) | |
while not opStack.isEmpty: | |
output.append(opStack.pop()) | |
return " ".join(output) | |
#a = "12+3*8" | |
a = "(26+46)*(89-12)" | |
print(convertToPostFix(a)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment