经典的基于单调栈的表达式求值算法是没有validate表达式是否正确的,1+2, 1 2 +都是可以evaluate出来的,因为它们的op栈和operand栈都是一样的。
和json validator一样,框架都是都是输入字符驱动的状态转移。
合法的主要是保证:
1)运算符和值交替出现,注意运算符可以首先出现但必须是+-,作为正负号
2)最后必须是值
值有2种:数和括号
定义4个状态:
EMPTY:当前表达式目前是空的
IN_VALUE:当前处在一个值的scope中,还没确定结束
AFTER_VALUE:当前处在一个值的后面,这个值已经确定结束
AFTER_OP:当前处在运算符后面,前面是一个运算符
还有一个左括号个数的计数leftParenthese
def validExpression(exp):
EMPTY, IN_VALUE, AFTER_VALUE, AFTER_OP = range(4)
state, leftParenthese = EMPTY, 0
for c in exp:
if c.isdigit():
if state == AFTER_VALUE: return False # adjacent oprand
elif state in [AFTER_OP, EMPTY]: state = IN_VALUE
elif c == ' ':
if state == IN_VALUE: state = AFTER_VALUE
elif c in '+-*/':
if state == AFTER_OP: return False # adjacent operator
if c in '*/' and state == EMPTY: return False # exp couldn't start by /*
state = AFTER_OP
elif c == '(':
if state in (AFTER_VALUE, IN_VALUE): return False
state, leftParenthese = EMPTY, leftParenthese + 1
elif c == ')':
# not allowed: ends with op, emtpy parenthese, unmatched right parenthese
if state in (EMPTY, AFTER_OP) or leftParenthese == 0: return False
state, leftParenthese = AFTER_VALUE, leftParenthese - 1
else: return False # invalid character
return state in (IN_VALUE, AFTER_VALUE) and leftParenthese == 0