Created
December 13, 2015 07:30
-
-
Save dbalan/1699385202759ce1d01f to your computer and use it in GitHub Desktop.
infix evaluation
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
# infix calculation | |
# infix -> postfix -> eval | |
NUMS = map(lambda x: str(x), range(10)) | |
def toponlist(l): | |
return l[len(l)-1] | |
def dop(op, arg1, arg2): | |
if op == '-': | |
t = int(arg2) - int(arg1) | |
return str(t) | |
if op == '+': | |
t = int(arg1) + int(arg2) | |
return str(t) | |
def infix2postfix(expr): | |
prec = { | |
"+": 2, | |
"-": 2, | |
"(": 1, | |
} | |
plist = [] | |
stack = [] | |
for t in list(expr): | |
if t in NUMS: | |
plist.append(t) | |
elif t == "(": | |
stack.append(t) | |
elif t == ")": | |
top = stack.pop() | |
while top != "(": | |
plist.append(top) | |
top = stack.pop() | |
else: | |
while ((len(stack) != 0) and (prec[toponlist(stack)] >= prec[t])): | |
plist.append(stack.pop()) | |
stack.append(t) | |
while (len(stack) != 0): | |
plist.append(stack.pop()) | |
return plist | |
def evalexp(expr): | |
infix = infix2postfix(expr) | |
print infix | |
stack = [] | |
for t in infix: | |
if t in NUMS: | |
stack.append(t) | |
else: | |
op = t | |
arg1 = stack.pop() | |
arg2 = stack.pop() | |
stack.append(dop(op, arg1,arg2)) | |
return stack.pop() | |
print evalexp("1+3-(2+9)") | |
print evalexp("(2-(6+1+3)-5)+(8+7)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment