python作业----计算器

import re
s = "1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))"

def cheng(s):
    s1 = re.search("d+(.d+)?[*/][-]?d+(.d+)?", s)
    if s1 is None:
        return s
    s2 = s1.group()
    ret = re.split(r'([*/])',s2)
    if ret[1] == "*":
        num = float(ret[0]) * float(ret[2])
    elif ret[1] == "/":
        num = float(ret[0])/float(ret[2])
    s2 = s2.replace("*","*")
    s3 = re.sub(s2,str(num),s,1)
    return cheng(s3)



def jia(s):
    s = s.replace("++","+")
    s = s.replace("+-","-")
    s = s.replace("--","+")
    s1 = re.search("[-]?d+(.d+)?[+-]d+(.d+)?",s)
    if s1 is None:
        return s
    s2 = s1.group()
    ret = re.split(r'([+-])',s2)
    if ret[0] == "":
        if ret[3] == "+":
            num = float(ret[2])*(-1) + float(ret[4])
        elif ret[3] == "-":
            num = float(ret[2])*(-1) - float(ret[4])

    else:
        if ret[1] == "+":
            num = float(ret[0]) + float(ret[2])
        elif ret[1] == "-":
            num = float(ret[0]) - float(ret[2])
    s2 = s2.replace("+", "+")
    s3 = re.sub(s2, str(num), s, 1)
    return jia(s3)

def kuohao(s):
    ret = re.search("(([^()]*))",s)
    if ret is None:
        return s
    s_w = ret.group()
    s1 = ret.group(1)
    num = cheng(s1)
    num2 = jia(num)
    s_w = s_w.replace("(","(")
    s_w = s_w.replace(")",")")
    s_w = s_w.replace("+","+")
    s_w = s_w.replace("*","*")
    s = re.sub(s_w,num2,s,1)
    return kuohao(s)
def fun(s):
    ret = kuohao(s)
    ret1 = cheng(ret)
    ret2 = jia(ret1)
    return ret2
s = s.replace(" ","")
ret =fun(s)
print(ret)
原文地址:https://www.cnblogs.com/ahliucong/p/9325247.html