import re #导入包
20-60+30 ,40-+30,40–30,±40+30,抽取用于计算的公用代码块
def compute_handler(sub_exp,symbol,exp,flag = False):
item = sub_exp.split(symbol)
if “-” in symbol and flag == False :
exp = exp.replace(sub_exp, str(float(item[0]) - float(item[1])))
elif “+” in symbol and flag == False :
exp = exp.replace(sub_exp, str(float(item[0]) + float(item[1])))
elif “+” in symbol and flag:
exp = exp.replace(sub_exp, str(float(item[0]) - float(item[1])))
elif “-” in symbol and flag:
exp = exp.replace(sub_exp, str(float(item[0]) + float(item[1])))
elif “" in symbol:
exp = exp.replace(sub_exp, str(float(item[0]) * float(item[1])))
elif “/” in symbol:
exp = exp.replace(sub_exp, str(float(item[0]) / float(item[1])))
else:
print(‘检查你的symbol’)
return exp
#对计算字符串的符号,优化
def format_exp(exp):
exp = exp.replace(“±”,"-")
exp = exp.replace("-+", “-”)
exp = exp.replace("++", “+”)
exp = exp.replace("–", “+”)
return exp
#(4+6-9) 6+9-7 加减函数
def add_sub(exp):
sub_exp = “”
flag = False
ret = re.search(’([-]?\d+[.]?\d[±]\d+[.]?\d*)’,exp)
if ret:
sub_exp = ret.group(0)
if sub_exp[0] == “-” and len(sub_exp) > 0:
sub_exp = sub_exp.strip(”-")
flag = True
if ‘+’ in sub_exp:
return add_sub(compute_handler(sub_exp,’+’,exp,flag))
elif ‘-’ in sub_exp:
return add_sub(compute_handler(sub_exp, ‘-’, exp,flag))
else :
return exp
#49/7-69-6 乘除函数
def mu_div(exp):
sub_exp = “”
ret = re.search(’\d+[.]?\d[/][-]?\d+[.]?\d’,exp)
if ret:
sub_exp =ret.group(0)
if ‘’ in sub_exp:
return mu_div(compute_handler(sub_exp, '’, exp))
elif ‘/’ in sub_exp:
return mu_div(compute_handler(sub_exp, ‘/’, exp))
else :
return exp
#获取优先计算的括号内容字符串,交给函数process_control,按照先乘除后加减顺序执行加减乘除函数
def inner_brackte(exp):
exp = exp.replace(" “,”")
ret = re.search("([^()]+)",exp)
if ret:
sub_exp = ret.group(0)
result = process_control(sub_exp)
exp = exp.replace(sub_exp,str(result))
exp = format_exp(exp)
return inner_brackte(exp)
else:
exp = process_control(exp)
ret =re.search("[\d]+[±*/][\d]",exp)
if ret :
exp = inner_brackte(format_exp(exp))
else:
print(‘结果是:’, exp)
#计算流程,先加减后乘除
def process_control(exp):
exp = format_exp(exp)
exp = mu_div(exp)
exp = format_exp(exp)
exp = add_sub(exp)
return exp.strip("(").strip(")")
#计算机函数调用
inner_brackte(‘1 - 2 * ( (60-30 +(-40/5) * (9-25/3 + 7 /399/42998 +10 * 568/14 )) - (-43)/ (16-32) )’)
print(eval('1 - 2 * ( (60-30 +(-40/5) * (9-25/3 + 7 /399/42998 +10 * 568/14 )) - (-43)/ (16-32) )’))