题解 | #表达式求值# 不使用eval函数
表达式求值
http://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
import re
chars = input()
chars = re.sub(r"([-+*/()])", r" \1 ", chars)
tmp = chars.split()
tokens = []
#处理负数
f = False
for i, x in enumerate(tmp):
if f == True:
f = False
continue
if x == '-' and (i == 0 or tmp[i-1] == '('):
tokens.append(''.join(tmp[i:i+2]))
f = True
else:
tokens.append(x)
ops = []
vals = []
precedence = {'+':1, '-':1, '*':2, '/':2, '(':0}
def applyOp(v1, v2, op):
if op == '+': return v1 + v2
if op == '-': return v1 - v2
if op == '*': return v1 * v2
if op == '/': return v1 // v2
for t in tokens:
if t != '-' and t[0] == '-' or t.isdigit():
vals.append(int(t))
elif t == '(':
ops.append(t)
elif t == ')':
while len(ops) > 0 and ops[-1] != '(':
v2 = vals.pop()
v1 = vals.pop()
op = ops.pop()
val = applyOp(v1, v2, op)
vals.append(val)
ops.pop()
else:
while len(ops) > 0 and precedence[ops[-1]] >= precedence[t]:
v2 = vals.pop()
v1 = vals.pop()
op = ops.pop()
val = applyOp(v1, v2, op)
vals.append(val)
ops.append(t)
while len(ops) > 0:
v2 = vals.pop()
v1 = vals.pop()
op = ops.pop()
val = applyOp(v1, v2, op)
vals.append(val)
print(vals[-1])