python解一元一次方程

2023-04-28,

将未知数看成是虚数
将常数看成是实数
最终求解。

import re

class Item:
def __init__(self,imag=0,real=0):
self.imag = imag
self.real = real
def __str__(self):
return format("(%.6f : %.6fX)")%(self.real,self .imag)
def __repr__(self):
return self.__str__()
def _calc(a,b,op):
if op == '+':
a.imag += b.imag
a.real += b.real
return a
elif op == '-':
a.imag -= b.imag
a.real -= b.real
elif op == '*':
if b.imag == 0:
a.imag *= b.real
a.real *= b.real
else:
a.imag,a.real,b.imag,b.real= b.imag,b.real,a.imag,a.real
a.imag *= b.real
a.real *= b.real
elif op == '/':
if b.real== 0:
raise Exception
a.imag /= b.real
a.real /= b.real
return a
def calculate(list):
def _ca(oplist,nulist,i,stop,opers):
op = oplist[-1]
while op in opers:
first,second = nulist[-2:]
_calc(first,second,op)
del nulist[-1]
del oplist[-1]
if len(oplist):
op = oplist[-1]
else:
op = stop
else:
oplist.append(i) oplist = []
nulist = []
for i in list:
if isinstance(i,str):
if i == '(':
oplist.append(i)
elif i in '+-':
if len(oplist):
_ca(oplist,nulist,i,"(","+-*/")
else:
oplist.append(i)
elif i in "*/":
if len(oplist):
_ca(oplist,nulist,i,"(","*/")
else:
oplist.append(i)
else:
if len(oplist):
_ca(oplist,nulist,i,"stop","+-*/")
del oplist[-1]
del oplist[-1]
else:
nulist.append(i)
_ca(oplist,nulist,i,"stop","+-*/")
return nulist[0]
if __name__ == "__main__":
# data = "((-3x))=9-9+2*x"
# data = "((-1+2x)/3)-(7+(8-9))*(1/2) = 5x + (3x-2)"
# data = "2x=10"
data = "(((4x)))=5+1x"
data = " "+re.subn("\\s+|=(.*)",lambda obj:"-(%s)"%obj.groups(1) if '=' in obj.group() else "",data)[0] regex = re.compile("(?<=[-+*/( ])-?\\d+x|(?<=[-+*/( ])-?\\d+|[-+*/()x]")
data = re.findall(regex,data)
calclist = []
for i in data:
if re.fullmatch("-?\\d+",i):
calclist.append(Item(real=int(i)))
elif re.fullmatch("-?\\d+x",i):
calclist.append(Item(imag=int(i[:-1])))
elif i == "x":
calclist.append(Item(imag=1))
else:
calclist.append(i)
result = calculate(calclist)
print(-result.real/result.imag)

来源:http://www.1994july.club/seo/?p=1703

python解一元一次方程的相关教程结束。

《python解一元一次方程.doc》

下载本文的Word格式文档,以方便收藏与打印。