python 简易计算器_python 实现简易计算器

importrefrom functools importreducedef mul_div(exp): #计算两个数的乘法或者除法

if '*' inexp:

a, b= exp.split('*')return float(a)*float(b)if '/' inexp:

a, b= exp.split('/')return float(a) /float(b)defexp_fmt(exp):while re.search('[+-]{2,}',exp):

exp= exp.replace('--','+')

exp= exp.replace('+-','-')

exp= exp.replace('-+','-')

exp= exp.replace('++','+')returnexpdefremove_addsub(exp):

ret= re.findall('[-+]?\d+(?:\.\d+)?',exp)

res= reduce(lambda a,b:float(a)+float(b),ret)returnresdef remove_muldiv(exp): #计算表达式中的所有的乘除法

whileTrue:

ret= re.search('\d+(\.\d+)?[*/]-?\d+(\.\d+)?',exp)ifret:

son_exp= ret.group() #3*4 12*5

res =mul_div(son_exp)

exp=exp.replace(son_exp,str(res))else:returnexpdefcal(exp):

res= remove_muldiv(exp) #计算乘除

res = exp_fmt(res) #符号整理

ret = remove_addsub(res) #计算加减

returnretdefmain(exp):

exp= exp.replace(' ', '')whileTrue:

ret= re.search('\([^()]+\)', exp)ifret:

res=cal(ret.group())

exp=exp.replace(ret.group(), str(res))else: returncal(exp)

exp= '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'ret=main(exp)print(ret)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值