python 计算器
开发一个简单的python计算器
- 实现加减乘除及拓号优先级解析
- 用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等类似公式后,必须自己解析里面的(),+,-,*,/符号和公式(不能调用eval等类似功能偷懒实现),运算后得出结果,结果必须与真实的计算器所得出的结果一致
# 编辑者:闫龙 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("++", "+") 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)

浙公网安备 33010602011771号