python语言实现简单的计算器功能

import re #导入包

20-60+30 ,40-+30,40–30,±40+30,抽取用于计算的公用代码块

def compute_handler(sub_exp,symbol,exp,flag = False):
item = sub_exp.split(symbol)
if “-” in symbol and flag == False :
exp = exp.replace(sub_exp, str(float(item[0]) - float(item[1])))
elif “+” in symbol and flag == False :
exp = exp.replace(sub_exp, str(float(item[0]) + float(item[1])))
elif “+” in symbol and flag:
exp = exp.replace(sub_exp, str(float(item[0]) - float(item[1])))
elif “-” in symbol and flag:
exp = exp.replace(sub_exp, str(float(item[0]) + float(item[1])))
elif “" in symbol:
exp = exp.replace(sub_exp, str(float(item[0]) * float(item[1])))
elif “/” in symbol:
exp = exp.replace(sub_exp, str(float(item[0]) / float(item[1])))
else:
print(‘检查你的symbol’)
return exp
#对计算字符串的符号,优化
def format_exp(exp):
exp = exp.replace(“±”,"-")
exp = exp.replace("-+", “-”)
exp = exp.replace("++", “+”)
exp = exp.replace("–", “+”)
return exp
#(4+6-9) 6+9-7 加减函数
def add_sub(exp):
sub_exp = “”
flag = False
ret = re.search(’([-]?\d+[.]?\d
[±]\d+[.]?\d*)’,exp)
if ret:
sub_exp = ret.group(0)
if sub_exp[0] == “-” and len(sub_exp) > 0:
sub_exp = sub_exp.strip(”-")
flag = True
if ‘+’ in sub_exp:
return add_sub(compute_handler(sub_exp,’+’,exp,flag))
elif ‘-’ in sub_exp:
return add_sub(compute_handler(sub_exp, ‘-’, exp,flag))
else :
return exp
#49/7-69-6 乘除函数
def mu_div(exp):
sub_exp = “”
ret = re.search(’\d+[.]?\d
[/][-]?\d+[.]?\d’,exp)
if ret:
sub_exp =ret.group(0)
if ‘’ in sub_exp:
return mu_div(compute_handler(sub_exp, '
’, exp))
elif ‘/’ in sub_exp:
return mu_div(compute_handler(sub_exp, ‘/’, exp))
else :
return exp
#获取优先计算的括号内容字符串,交给函数process_control,按照先乘除后加减顺序执行加减乘除函数
def inner_brackte(exp):
exp = exp.replace(" “,”")
ret = re.search("([^()]+)",exp)
if ret:
sub_exp = ret.group(0)
result = process_control(sub_exp)
exp = exp.replace(sub_exp,str(result))
exp = format_exp(exp)
return inner_brackte(exp)
else:
exp = process_control(exp)
ret =re.search("[\d]+[±*/][\d]",exp)
if ret :
exp = inner_brackte(format_exp(exp))
else:
print(‘结果是:’, exp)

#计算流程,先加减后乘除
def process_control(exp):
exp = format_exp(exp)
exp = mu_div(exp)
exp = format_exp(exp)
exp = add_sub(exp)
return exp.strip("(").strip(")")

#计算机函数调用
inner_brackte(‘1 - 2 * ( (60-30 +(-40/5) * (9-25/3 + 7 /399/42998 +10 * 568/14 )) - (-43)/ (16-32) )’)
print(eval('1 - 2 * ( (60-30 +(-40/5) * (9-2
5/3 + 7 /399/42998 +10 * 568/14 )) - (-43)/ (16-32) )’))

在这里插入图片描述运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值