#!/usr/bin/env python
# -*- coding=utf-8 -*-
import re, time
def hefaxin(xx):
‘‘‘数据合法性‘‘‘
b = 0
for i in xx: # 判断
if b < 0:break
if i == "(":b += 1
elif i == ")":b -= 1
zimu = re.search("[a-zA-Z\=]", xx) # 没有字母为空
kh = len(re.findall("\d+\.?\d*[\(]", xx)) # 判断括号是否有 数字(的情况
kh1 = len(re.findall("[()]", xx)) # 判断括号
dian = re.search("(\d+\.\.\d+)", xx) # 判断是否有 ..
if kh1 % 2 == b == kh and dian == zimu: return xx.replace(" ", "")
return 0
def tihfh(xx):
‘‘‘符号替换‘‘‘
xx = str(xx)
xx = xx.replace("++", "+")
xx = xx.replace("+-", "-")
xx = xx.replace("-+", "-")
xx = xx.replace("--", "+")
xx = xx.replace("*+", "*")
xx = xx.replace("/+", "/")
return xx
def ccf(xx):
‘‘‘乘除法‘‘‘
if re.search("\(", xx): xx = xx[1:-1] # 去括号
while re.search("[\*\/]",xx):
cenfa = re.search("\d+\.?\d*[\*\/]{1}\-?\d+\.?\d*", xx)
if cenfa:
cenfa = cenfa.group()
if cenfa.count("*") == 1: # 一个乘法
a, b = cenfa.split("*")
xx = xx.replace(cenfa, str(float(a) * float(b)))
elif cenfa.count("*") == 2:
a, b = cenfa.split("**")
xx = xx.replace(cenfa, str(float(a) ** float(b)))
elif cenfa.count("/") == 1:
a, b = cenfa.split("/")
xx = xx.replace(cenfa, str(float(a) / float(b)))
elif cenfa.count("/") == 2:
a, b = cenfa.split("//")
xx = re.sub(cenfa, str(float(a) // float(b)), xx)
else:
return xx
return xx
def jjf(xx):
‘‘‘加减法,按匹配顺序计算‘‘‘
if "(" in xx: xx = xx[1:-1] # 去括号
while re.search("\d+\.?\d*[\+\-]\d+\.?\d*",xx):
findret = re.search("[\-]?\d+\.?\d*[\+\-]\d+\.?\d*", xx)
if findret:
findret = findret.group()
if re.search("\d+\.?\d*\+\d+\.?\d*",findret): # 加法
a, b = findret.split("+")
xx = xx.replace(findret, str(float(a) + float(b)))
elif re.search("\d+\.?\d*\-\d+\.?\d*",findret): # 减法
a, b = findret.split("-")
xx = xx.replace(findret, str(float(a) - float(b)))
else:return xx
return xx
def kuohao(xx):
‘‘‘寻找括号‘‘‘
xx = re.search("(\([^()]+\))", xx)
if xx: return xx.group() # 找到就返回找到结果
return 0 # 没找到返回0
if __name__ == ‘__main__‘:
while True:
jishuan = input("请输入公式,保留2位小数。\n绿色为正确,红色结果错误!\n>>>")
db = hefaxin(jishuan) # 合法性判断
if db: # 返回正确执行精算
while db.count("(") > 0: # 循环一直有括号的
kh = kuohao(db) # 寻找括号
db = db.replace(kh, str(jjf(ccf(tihfh(kh))))) # 替换括号
else: # 无括号的情况
ret = jjf(ccf(tihfh(db)))
if "+" in ret: ret = ret[1:] # 取正数前面符号
while len(re.findall("\d+\.?\d*[\+\-\*\/]+\d+\.?\d*",ret)) > 0:
ret = jjf(ccf(tihfh(ret)))
if eval(jishuan) == float(ret):s = 32 # 正确就显示绿色
else:s = 31 # 错误就是红色
print("\33[%d;1m%s=%.2f\n\33[1m" % (s, jishuan, float(ret)))
else:print("\33[31;1m程序不合法,无法计算!\33[1m\n\n")
# 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )"
#jishuan = "1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )"
# 2*3*4*-1=6.0*-4.0
#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161231/index.html