#!/usr/bin/env pythonimportre
defdeal_negative_issue(calc_list):
new_calc_list=[] #定义一个新的空列表,后面筛选完成后将数据放入新列表中 forindex,item inenumerate(calc_list):
ifitem.strip().endswith("*") oritem.strip().endswith("/"): #挑选出以乘号或除号结尾的字符串 new_calc_list.append("%s-%s"%(calc_list[index],calc_list[index+1])) #拼接字符串 处理类似2*5/-3# elif ("*" or "/") in item: #找出列表中的有乘除的选项,这种写法我试了好像只匹配*在,单独40/5这种匹配不出来 elif("/") initem or("*") initem:
print(item)
new_calc_list.append(item)
print("new_calc_ist",new_calc_list)
returnnew_calc_list
defdeal_unusual_issue(formula):
formula = formula.replace("++","+")
formula = formula.replace("+-", "-")
formula = formula.replace("-+", "-")
formula = formula.replace("--", "+")
formula = formula.replace("- -", "+")
returnformula
# def addition_and_subtraction(formula):# sub_calc_list = re.split("[+-]",formula)# sub_operator_list = re.findall("[+-]",formula)# print(type(sub_calc_list), sub_operator_list)# totle_res = None# for index,i in enumerate(sub_calc_list):# if totle_res: #sub_res为真,表示这不是第一次循环# if sub_operator_list[index-1]=="+": #通过sub_operator_list中的index判断到底是加法还是减法# totle_res += float(i)# else:# totle_res -= float(i)# else:# sub_res = float(i)# print(totle_res)defcalculating(formula):
print("运算",formula)
calc_list = re.split("[+-]",formula) #通过+-符号将各个乘除运算分隔出来 calc_list = deal_negative_issue(calc_list)
print(calc_list)
foritem incalc_list:
sub_calc_list = re.split("[*/]",item)
sub_operator_list = re.findall("[*/]",item) #将乘号除号通过列表方式分隔出来 print(sub_calc_list,sub_operator_list)
sub_res = Noneforindex,i inenumerate(sub_calc_list):
ifsub_res: #sub_res为真,表示这不是第一次循环 ifsub_operator_list[index-1]=="*": #通过sub_operator_list中的index判断到底是加法还是减法, sub_res *= float(i)
else:
sub_res /= float(i)
else:
sub_res = float(i)
print("[%s]="%item,sub_res)
formula = formula.replace(item,str(sub_res))
formula = deal_unusual_issue(formula)
print(formula)
#计算+-法 totle_calc_list = re.split("[+-]", formula)
totle_operator_list = re.findall("[+-]", formula) # 将乘号除号通过列表方式分隔出来 print(totle_calc_list, totle_operator_list)
totle_res = Noneforindex,item inenumerate(totle_calc_list):
iftotle_res: #sub_res为真,表示这不是第一次循环 iftotle_operator_list[index-1]=="+": #通过sub_operator_list中的index判断到底是加法还是减法, totle_res += float(item)
else:
totle_res -= float(item)
else:
totle_res = float(item)
# return formula print("[结果]=", totle_res)
returntotle_res
defcalc(formula):
parentheses_flag = True calc_res= Nonewhileparentheses_flag:
m = re.search("\([^()]*\)",formula) #找出最底层的括号,一个一个找 print(m)
ifm:
# print(type(m.group())) subformula = m.group().strip("()") #把找出来的括号剥离 subres = calculating(subformula)
formula = formula.replace(m.group(),str(subres))
else:
print("没括号了")
print("最终结果为",calculating(formula))
parentheses_flag = Falseif__name__ == '__main__':
res = calc("1 - 2 * ( (60-30 +(9-2*5/-3 + 7 /3*99/4*2998 +10 * 568/14 ) * (40/5)) - (4*3)/ (16-3*2) )")
#res = calc("2 * (40/5)")