python解一元一次方程

强颜欢笑 提交于 2019-12-14 09:43:22

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

  • 将未知数看成是虚数
  • 将常数看成是实数
  • 最终求解。
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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!