简单计算器实现

实现计算器的加减乘除

import re
def atom_cal(exp): # 计算乘除法
if '*' in exp:
a,b = exp.split('*')
return str(float(a) * float(b))
elif '/' in exp:
a, b = exp.split('/')
return str(float(a) / float(b))

def fuhaochuli(exp): # 符号处理
exp = exp.replace('++','+')
exp = exp.replace('-+','-')
exp = exp.replace('+-','-')
exp = exp.replace('--','+')
return exp

def mul_div(exp): # 匹配乘除法进行计算并替换
while True:
ret = re.search('\d+(\.\d+)?[*/]-?\d+(\.\d+)?',exp)
if ret:
a = ret.group()
b = atom_cal(a)
exp = exp.replace(a,b)
else:return exp

def add_sub(exp): # 匹配加减法计算并进行替换
res = re.findall('[-+]?\d+(?:\.\d+)?',exp)
exp_sum = 0
for i in res:
exp_sum += float(i)
return exp_sum

def cal(exp): # 计算
exp = mul_div(exp)
exp = fuhaochuli(exp)
exp_sum = add_sub(exp)
return exp_sum

def main(exp): # 格式处理,计算结果并进行替换
exp = exp.replace(" ",'')
while True:
ret = re.search('\([^()]+\)',exp)
if ret:
inner_bracket = ret.group()
res = str(cal(inner_bracket))
exp = exp.replace(inner_bracket,res)
exp = fuhaochuli(exp)
else:break
return cal(exp)

s = '5+5'
ret = main(s)
print(ret)


  上一篇:微信抢红包简单实现 下一篇:github超时解决  

湘ICP备19016894号 © 2019 小钱