Python练习-天已经亮了计算器也终于完成了

时间:2023-03-09 15:10:54
Python练习-天已经亮了计算器也终于完成了
 # 编辑者:闫龙
import re #导入re模块(正则表达式)
calc2 = "1-2*((60-30+(-40/52)*(9-2*5/3+7/3*-99/4*2998+10*568/14))-(-4*3)/(16-3*2))"
calc1 = "1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))"
calc = "1-2*((60*30+(-40/5)*(9*2*5/3+7/3*99/4*2998+10*568/14))-(-4*32)/(16-3*2))"
def Format(Str):
"格式化运算式"
Str = Str.replace("+-","-")
Str = Str.replace("-+", "-")
Str = Str.replace("++", "+")
Str = Str.replace("--", "+")
return Str
def SumCut(Str):
while re.search("-?[0-9]+\.?[0-9]*[-+][0-9]+\.?[0-9]*",Str):
newRes= re.search("-?[0-9]+\.?[0-9]*[-+][0-9]+\.?[0-9]*",Str)
WhatIs = newRes.group()
if(WhatIs.find("-") > 0):
l = WhatIs.split("-")
Str = Str.replace(WhatIs,str(float(l[0])-float(l[1])))
elif(WhatIs.find("+") > 0):
l = WhatIs.split("+")
Str = Str.replace(WhatIs,str(float(l[0])+float(l[1])))
return Str.replace("(","").replace(")","")
def MulDiv(Str):
while re.search("-?[0-9]+\.?[0-9]*[/*].?[0-9]+\.?[0-9]*",Str):
newRes= re.search("-?[0-9]+\.?[0-9]*[/*].?[0-9]+\.?[0-9]*",Str)
WhatIs = newRes.group()
if(WhatIs.find("/") > 0):
l = WhatIs.split("/")
Str = Str.replace(WhatIs,str(float(l[0])/float(l[1])))
elif(WhatIs.find("*") > 0):
l = WhatIs.split("*")
if(float(l[0])<0 and float(l[1])<0):
Str = Str.replace(WhatIs, "+"+str(float(l[0]) * float(l[1])))
else:
Str = Str.replace(WhatIs,str(float(l[0])*float(l[1])))
return Format(Str)
while re.search("\([^()]+\)",calc):
res = re.search("\([^()]+\)", calc)
resTwo = MulDiv(Format(res.group()))
resTwo = SumCut(resTwo)
calc = calc.replace(res.group(),resTwo)
else:
resTwo = MulDiv(calc)
resTwo = SumCut(resTwo)
calc = resTwo
print(calc)

以上,我什么也不想说,睡觉!