计算类似这样的表达式
1 - 2 *((6 0 - 3 0 +(-40/5)*(9-2*5/3 + 7/3*99/4*2998 +10 *568/14)) - (-4*3)/(16-3*2))
提示:
1.去空格
2.用正则匹配最简式子
3.计算结果去替换原式
4.while 循环
1 import re
2
3 #处理表达式 将+-替换成- --替换成+
4 def dealwith(express):
5 express = express.replace('+-','-')
6 express = express.replace('--','+')
7 return express
8 #计算
9 def cal_exp_son(exp_son):
10 #用来计算原子型表达式 两个数之间的乘除法
11 if '/' in exp_son:
12 a,b = exp_son.split('/')
13 return str(float(a)/float(b))
14 elif '' in exp_son:
15 a,b = exp_son.split('')
16 return str(float(a)float(b))
17
18 def cal_express_no_bracket(exp):
19 # 计算没有括号的表达式
20 # exp是没有经过处理的最内层带括号的表达式
21 while True:
22 exp = exp.strip('()')
23 #先乘除后加减
24 ret = re.search('\d+.?\d[/]-?\d+.?\d',exp)
25 if ret:
26 exp_son = ret.group()
27 ret = cal_exp_son(exp_son)
28 exp= exp.replace(exp_son,ret)
29 exp =dealwith(exp)
30 else:
31 ret =re.findall('-?\d+.?\d*',exp)
32 sum=0
33 for i in ret:
34 sum +=float(i)
35 return str(sum)
36
37 def remove_bracket(new_express):
38 #提取括号里没有其他括号的表达式
39 while True:
40 ret = re.search('([^()]+)',new_express)
41 if ret:
42 express_no_bracket = ret.group()
43 print('匹配到内部不在有括号的值:',express_no_bracket)
44 ret = cal_express_no_bracket(express_no_bracket)
45 new_express = new_express.replace(express_no_bracket,ret)
46 new_express = dealwith(new_express)
47 print(new_express)
48 else:
49 print('表达式中已经没有括号了:',new_express)
50 ret = cal_express_no_bracket(new_express)
51 return ret
52
53 express = '1 - 2 *((6 0 - 3 0 +(-40/5)*(9-2*5/3 + 7/3*99/4*2998 +10 *568/14)) - (-4*3)/(16-3*2))'
54 # 去空格
55 new_express = express.replace(' ','')
56 print(new_express)
57 ret = remove_bracket(new_express)
58 print(ret)
View Code