计算机功能简单实现

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 format_exp(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:
atom_exp = ret.group()
res = atom_cal(atom_exp)
exp = exp.replace(atom_exp, res)

else:
return exp

def add_sub(exp):
ret = re.findall("[+-]?\d+(?:\.\d+)?", exp)
exp_sum = 0
for i in ret:
exp_sum += float(i)
return exp_sum


def cal(exp):
exp = mul_div(exp)
exp = format_exp(exp)
exp_sum = add_sub(exp)
return exp_sum
ret = cal('1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) ')
print(ret)

转载于:https://www.cnblogs.com/zzy7372/p/9520506.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值