求解一元一次方程,如10 x- 2 x= x + 12
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 解一元一次方程
def solve(eq, var='x'):
eq1 = eq.replace("=", "-(")+")"
eq1 = eq1.replace("x", "*x")
eq1 = eq1.replace("+*x", "+x")
eq1 = eq1.replace("-*x", "-x")
eq1 = eq1.replace("(*x", "(x")
#print(eq1)
c = eval(eq1, {var: 1j})
return -c.real/c.imag
#test = "10 x- 2 x= x + 12"
test = raw_input('Input a euqation:\n')
#去除空格
test = test.replace(" ", "")
print('The answer is', solve(test))
求解二元一次方程组,如2 x- 3y=10;3x= 5y-10
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sympy as sp
def transform(eq, var='x', var1='y'):
eq1 = eq.replace("=", "-(")+")"
eq1 = eq1.replace("x", "*x")
eq1 = eq1.replace("+*x", "+x")
eq1 = eq1.replace("-*x", "-x")
eq1 = eq1.replace("(*x", "(x")
eq1 = eq1.replace("y", "*y")
eq1 = eq1.replace("+*y", "+y")
eq1 = eq1.replace("-*y", "-y")
eq1 = eq1.replace("(*y", "(y")
return eq1
test1 = raw_input('Input the first euqation:\n')
test2 = raw_input('Input the second euqation:\n')
test1 = test1.replace(" ", "")
test2 = test2.replace(" ", "")
# 符号化变量
#x = sp.Symbol('x')
x, y = sp.symbols('x y')
print sp.solve([transform(test1), transform(test2)], [x, y])
版权声明:本文为qq_38197757原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。