一个简易计算器代码

import re
def basic_cal(cal_list):
def del_ex(temp,ind):
cal_list[ind-1]=temp
del cal_list[ind],cal_list[ind]
def mul_div(c_list):
while True:
for index,args in enumerate(c_list):
if args=="*":
args_temp=float(c_list[index-1])*float(c_list[index+1])
del_ex(args_temp,index)
break
elif args=="/":
args_temp=float(c_list[index-1])/float(c_list[index+1])
del_ex(args_temp,index)
break
if "*" not in c_list and "/" not in c_list:
return c_list
def plu_min(c_list):
while True:
for index,args in enumerate(c_list):
if args=="+":
args_temp=float(c_list[index-1])+float(c_list[index+1])
del_ex(args_temp,index)
break
elif args=="-":
args_temp=float(c_list[index-1])-float(c_list[index+1])
del_ex(args_temp,index)
break
if "+" not in c_list and "-" not in c_list:
return c_list
if cal_list[0]=="-":
cal_list[0]+=cal_list[1]
del cal_list[1]
cal_list=mul_div(cal_list)
cal_list=plu_min(cal_list)
return cal_list


y="((2+3*5)-4/25*(-25-36))/5*23+22551*(5/2+6.56*5.25)/5*25-(88+22)"
y1=y
while True:
if "(" in y:
y_bra=re.search(r"\([\d\+-/\*]+\)",y).group()
else:
y_bra=y
if re.search("[\+\*/-]-[\d\.]+",y_bra):
s_min=re.search("[\+\*/-]-[\d\.]+",y_bra).group()
y_bra=y_bra.replace(s_min,s_min[0]+"000")
y=y.replace(s_min,s_min[0]+"000")
y_list=re.findall("[\d\.]+|\+|-|/|\*",y_bra)
y_list[y_list.index("000")]=s_min[1:len(s_min)]
else:
y_list=re.findall("[\d\.]+|\+|-|/|\*",y_bra)
y_list=basic_cal(y_list)
y=y.replace(y_bra,str(y_list[0]))
if y==str(y_list[0]):
break
print("the answer is",y_list,eval(y1))
posted @ 2020-06-05 06:00  原竹  阅读(1185)  评论(0编辑  收藏  举报