PYTHON之化简求解一元一次方程
最近学习PLY,写了一个简单的解方程程序,暂时只能解一元一次方程,只能用整数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|x|+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)
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 - t,t - t)
if(final == 0):
if(final == 0):
print("infinite solutions")
else:
print("no solution")
else:
print("simplest : %s"% (str(final) + 'x' + '+' + str(final) + ' = 0'))
print("x = %.3f"%( -final/final))
def p_expression_binop(t):
'''expression : expression PLUS expression
| expression MINUS expression'''
if t == '+': t = (t+t,t + t)
elif t == '-': t = (t-t,t - t)
def p_expression_uminus(t):
'expression : MINUS expression %prec UMINUS'
t =(-t, -t)
def p_expression_mulgroupx(t):
'expression : NUMBER LPAREN expression PARENVAR'
if(t != 0):
print("warning : only linear equation supported!")
t = (t*t,0)
def p_expression_groupx(t):
'expression : LPAREN expression PARENVAR'
if(t != 0):
print("warning : only linear equation supported!")
t = (t,0)
def p_expression_group(t):
'expression : LPAREN expression RPAREN'
t = t
def p_expression_mulgroup(t):
'expression : NUMBER LPAREN expression RPAREN'
t = (t*t,t*t)
def p_expression_number(t):
'expression : NUMBER'
t = (0,t)
def p_expression_ukn(t):
'expression : UKN'
t = (t,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) 啥 解个方程还要1块钱一次 fanvalen 发表于 2020-9-14 17:09
啥 解个方程还要1块钱一次
解多了可以给你便宜点 fanvalen 发表于 2020-9-14 17:09
啥 解个方程还要1块钱一次
直接把楼主的代码偷走就不用钱了~~~~~{:301_976:} fanvalen 发表于 2020-9-14 17:09
啥 解个方程还要1块钱一次
还有更黑心的,2元一次! fanvalen 发表于 2020-9-14 17:09
啥 解个方程还要1块钱一次
懵逼的我看了半天才理解过来,一元一次方程 youkan_pj 发表于 2020-9-14 17:44
懵逼的我看了半天才理解过来,一元一次方程
一元一次
哈哈哈
写的太乱了!导包都是第一行的不要到处导包!就是写的有点乱 最好就加入if name== main 我寻思着一元一次方程可能蛮简单的
页:
[1]
2