python
import ply.lex as lex
import ply.yacc as yacc
tokens = (
'NUMBER',
'PLUS',
'MINUS',
)
t_PLUS = r'\+'
t_MINUS = r'-'
def t_NUMBER(t):
r'\d+'
t.value = int(t.value)
return t
def p_expression_plus(p):
'expression : expression PLUS expression'
p[0] = p[1] + p[3]
def p_expression_minus(p):
'expression : expression MINUS expression'
p[0] = p[1] - p[3]
def p_expression_number(p):
'expression : NUMBER'
p[0] = p[1]
lexer = lex.lex()
parser = yacc.yacc()
result = parser.parse('2 + 3 - 1')