计算器的实现

 1 #(1)先找到最里层没有括号的括号
 2 #(2)用正则表达式找打乘除式子
 3 #(3)用正则表达式找打加减式子
 4 #(4)  在乘除
 5 #(5)  在加减
 6 #(6)   在去符号
 7 #(7)  最后算结果
 8 import re
 9 def atom_cal(exp):     #如果是乘除法,则计算
10     if '*' in exp:    #判断*在不在
11         a,b = exp.split('*')  #在的话就分割
12         return str(float(a) * float(b))#计算 数字是浮点型 把结果转化成字符串 是因为在下面的函数中要调用它(exp = exp.replace(atom_exp,res))
13     elif '/' in exp:    #判断除法
14         a, b = exp.split('/')   #分割
15         return str(float(a) / float(b))   #相除
16 
17 def format_exp(exp):      #符号的判断
18     exp = exp.replace('--','+')  #+代替--
19     exp = exp.replace('+-','-')  #-代替+-
20     exp = exp.replace('-+','-')  #-+代替-+
21     exp = exp.replace('++','+') #++代替+
22     return exp
23 
24 def mul_div(exp):   #找到乘除法
25     while True:
26         ret = re.search('d+(.d+)?[*/]-?d+(.d+)?',exp)  #利用正则表达式
27         if ret:             #如果找到
28             atom_exp = ret.group()  #则获取
29             res = atom_cal(atom_exp)    #再次调用乘除法的函数
30             exp = exp.replace(atom_exp,res)    #计算完成 用结果替换之前的内容  res就是乘除法运算出来的结果
31         else:return exp
32 
33 def add_sub(exp):    #找到加减法的函数
34     ret = re.findall('[+-]?d+(?:.d+)?', exp)#利用正则表达式找打+-法  ?:是取消优先级  这个正则表达式是找到数字前面的括号
35     exp_sum = 0     #定义一个总和为0
36     for i in ret:       #i 的结果是 2   -5   +9     意思就是带着括号一起的
37         exp_sum += float(i)    #再把 他们加在一起   如 2-5+9
38     return exp_sum
39 
40 def cal(exp):  #调用各种函数
41     exp = mul_div(exp)   #调用乘除法的函数
42     exp = format_exp(exp)  #调用+-符号的判断函数
43     exp_sum =  add_sub(exp)   # 调用加减的函数
44     return exp_sum   # float
45 
46 def main(exp):   #主函数
47     exp = exp.replace(' ','')    #去掉空格
48     while True:
49         ret = re.search('([^()]+)',exp)   #找到最里层括号
50         if ret :            #如果是最里层括号  且不包含括号  如  (40/5)   (-8+9)  这种
51             inner_bracket = ret.group()    #利用.group () 取出
52             res = str(cal(inner_bracket))#res 是计算出来的结果 比如(40/5) 算出res=8  先走cal()函数 再在cal()函数中找到乘除法加减的函数运算
53             exp = exp.replace(inner_bracket,res)   #再用结果代替算式  比如用 res=8 代替(40/5) 在继续找括号
54             exp = format_exp(exp)    #再把结果中含 --  换成+  (调用format_exp)
55         else:break
56     return cal(exp)   #返回最后结果
57 
58 s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
59 ret = main(s)
60 print(ret,type(ret))
计算器的实现
原文地址:https://www.cnblogs.com/mlhz/p/9520726.html