码迷,mamicode.com
首页 > 其他好文 > 详细

计算器写法 | '1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'

时间:2019-06-01 21:48:11      阅读:618      评论:0      收藏:0      [点我收藏+]

标签:eval   ack   cal   dal   arch   数值   替换   else   obj   

import re
# 计算乘除的方法
def parse_exp(exp):
	if "*" in exp:
		a,b = exp.split("*")
		# print(a,b)
		return str(float(a) * float(b))
		
	if "/" in exp:
		a,b = exp.split("/")
		return str(float(a) / float(b))

# 去除++ +- -- -+ bug情况
def exp_format(exp):
	exp = exp.replace("+-","-")
	exp = exp.replace("--","+")
	exp = exp.replace("-+","-")
	exp = exp.replace("++","+")
	return exp
	
# 实际计算
def exp_calc(strvar):
	# 计算乘除
	while True:
		res_obj = re.search("\d+(\.\d+)?[*/][+-]?\d+(\.\d+)?",strvar)
		if res_obj:
			res = res_obj.group()
			# print(res) #"5*-2"
			res2 = parse_exp(res)
			# print(res2)
			strvar = strvar.replace(res,res2)
		else:
			break
	# print(strvar)
	# 计算加减
	res = exp_format(strvar)
	# print(res)
	lst = re.findall("[+-]?\d+(?:\.\d+)?",res)
	# print(lst)
	count = 0
	for i in lst:
		count += float(i)
	# print(count)
	return count

# 去除括号
def remove_bracket(strvar):
	while True:
		res_obj = re.search("\([^()]+\)",strvar)
		if res_obj:
			res_exp = res_obj.group()
			# print(res_exp)
			# 计算括号里面的值,exp_calc
			res = str(exp_calc(res_exp))
			# print(res,type(res))
			# 把算好的实际数值转换成字符串,替换以前的圆括号
			strvar = strvar.replace(res_exp,res)
		else:
			# 直接返回替换好的字符串
			return strvar
# 主函数	
def main(strvar):	
	# 先把所有的空格去掉 
	strvar = strvar.replace(" ","")
	# 去除括号
	res = remove_bracket(strvar)
	# print(res)
	# 计算最后结果
	return exp_calc(res)
# strvar = "-  30  +(  40+5*-2)*    2"
a = ‘1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))‘

res = main(a)
print(res)
# 验证结果
res = eval(a)
print(res)
	
	
	

  

计算器写法 | '1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'

标签:eval   ack   cal   dal   arch   数值   替换   else   obj   

原文地址:https://www.cnblogs.com/huangjiangyong/p/10960876.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!