cal.py
#!/usr/bin/env python # -*- coding:utf8 -*- import re def calculation(x,y,m): if m=='+' or m=='--': return x+y elif m=="-" or m=='+-' or m=='-+': return x - y elif m == "*": return x * y elif m == "/": return x / y elif m == "%": return x % y elif m == "//": return x // y elif m == "**": return x**y else: print('This mark is not exist, mark:%s' %m) return 0 def subcal(a): while True: temb = re.search('d*.?d+[*/\%]+[+-]?d*.?d+', a) # 高级别运算符*/%//** if temb == None: break temb = temb.group() c = re.findall('[+-]?d*.?d+', temb) #高级别运算符时,对应的正负号算是数值的一部分 d = re.findall('[*/\%]+', temb) tem = calculation(float(c[0]), float(c[1]), d[0]) a = a.replace(temb, str(tem), 1) while True: temb = re.search('[+-]?d*.?d+[+-]+d*.?d+', a) # +-运算 [+-]+d*.?d+, 取首字符是加减符号的情况 if temb == None: break temb = temb.group() c = re.findall('(d*.?d+)', temb) d = re.findall('[+-]+', temb) if len(d)>1: #如果数量大于1,证明首字符是正负号,与数字一起计算 tem = calculation(float(''.join([d[0],c[0]])), float(c[1]), d[-1]) else: tem = calculation(float(c[0]), float(c[1]), d[0]) a = a.replace(temb, str(tem), 1) return a if __name__=="__main__": s = '1 - 2 * ((60-30+(40+4 / 2+4/ -2+3)*(9-2*5/-3+7/3*9/4*2 +10*56 /14))-(-4*3)/(16-3*2))' # s='1+2' # s='1-2' # s='3+2-9' # s='-5+2+1' # s='-1+9/3' # s='9+5*2-10-9//5-1+3**2' # s='9//5' print(eval(s)) s=s.replace(" ","") while True: #计算括号内数值,从最里层括号开始计算所有括号 tema=re.search('([^()]+)',s) #最里边括号 if tema == None: break tema=tema.group() a = re.sub('(|)', '', tema) # 去掉括号,只保留计算 # a=tema.replace('(','') # a = a.replace(')', '') #去掉括号,只保留计算 a=subcal(a) s=s.replace(tema,str(a),1) s=float(subcal(s)) #转为浮点 s=int(s) if s==int(s) else s #如果是整数,取整 print(s)
s1.py
#!/usr/bin/env python # -*- coding:utf8 -*- import re from cal import subcal s = '1 - 2 * ((60-30+(40+4 / 2+4/ -2+3)*(9-2*5/-3+7/3*9/4*2 +10*56 /14))-(-4*3)/(16-3*2))' # s='1+2' # s='1-2' # s='3+2-9' # s='-5+2+1' # s='-1+9/3' # s='9+5*2-10-9//5-1+3**2' # s='9//5' s='19%-5' print(eval(s)) s=s.replace(" ","") while True: #计算括号内数值,从最里层括号开始计算所有括号 tema=re.search('([^()]+)',s) #最里边括号 if tema == None: break tema=tema.group() a = re.sub('(|)', '', tema)#去掉括号,只保留计算 # a=tema.replace('(','') # a = a.replace(')', '') #去掉括号,只保留计算 a=subcal(a) s=s.replace(tema,str(a),1) s=float(subcal(s)) #转为浮点 s=int(s) if s==int(s) else s #如果是整数,取整 print(s)