最近学习PLY,写了一个简单的解方程程序,暂时只能解一元一次方程,只能用整数
[Python] 纯文本查看 复制代码
tokens = (
'NUMBER','UKN','PARENVAR',
'PLUS','MINUS','EQUALS',
'LPAREN','RPAREN',
)
# Tokens
t_PLUS = r'\+'
t_MINUS = r'-'
t_EQUALS = r'='
t_LPAREN = r'\('
t_RPAREN = r'\)'
def t_PARENVAR(t):
r'\)x'
return t
def t_UKN(t):
r'x|[2-9]x|[1-9][0-9]+x'
if(t.value == 'x'):
t.value = (1,0)
else:
t.value = (int(t.value[:-1]),0)
return t
def t_NUMBER(t):
r'\d+'
t.value = (0, int(t.value))
return t
# Ignored characters
t_ignore = " \t"
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
# Build the lexer
import ply.lex as lex
lexer = lex.lex(debug=False)
# Parsing rules
precedence = (
('left','PLUS','MINUS'),
('right','UMINUS'),
)
def p_statement_expr(t):
'statement : expression EQUALS expression'
final = (t[1][0] - t[3][0],t[1][1] - t[3][1])
if(final[0] == 0):
if(final[1] == 0):
print("infinite solutions")
else:
print("no solution")
else:
print("simplest : %s"% (str(final[0]) + 'x' + '+' + str(final[1]) + ' = 0'))
print("x = %.3f"%( -final[1]/final[0]))
def p_expression_binop(t):
'''expression : expression PLUS expression
| expression MINUS expression'''
if t[2] == '+' : t[0] = (t[1][0]+t[3][0],t[1][1] + t[3][1])
elif t[2] == '-': t[0] = (t[1][0]-t[3][0],t[1][1] - t[3][1])
def p_expression_uminus(t):
'expression : MINUS expression %prec UMINUS'
t[0] =(-t[2][0], -t[2][1])
def p_expression_mulgroupx(t):
'expression : NUMBER LPAREN expression PARENVAR'
if(t[3][0] != 0):
print("warning : only linear equation supported!")
t[0] = (t[1][1]*t[3][1],0)
def p_expression_groupx(t):
'expression : LPAREN expression PARENVAR'
if(t[2][0] != 0):
print("warning : only linear equation supported!")
t[0] = (t[2][1],0)
def p_expression_group(t):
'expression : LPAREN expression RPAREN'
t[0] = t[2]
def p_expression_mulgroup(t):
'expression : NUMBER LPAREN expression RPAREN'
t[0] = (t[3][0]*t[1][1],t[3][1]*t[1][1])
def p_expression_number(t):
'expression : NUMBER'
t[0] = (0,t[1][1])
def p_expression_ukn(t):
'expression : UKN'
t[0] = (t[1][0],0)
def p_error(t):
print("Syntax error" ,t.value)
import ply.yacc as yacc
parser = yacc.yacc(debug=False)
while True:
try:
s = input('calc > ')
except EOFError:
break
parser.parse(s) |