网站建设资讯

NEWS

网站建设资讯

通过Python正则表达式实现简单四则运算-创新互联

python练习作业...
import math, re
string = "1.5 - 2.4 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )"
string = ''.join(string.split()) #字符串去空格
#字符串格式化
def stringFormat(string):
    string = string.replace('--', '+')
    string = string.replace('-', '+-')
    string = string.replace('*+-', '*-')
    string = string.replace('/+-', '/-')
    return string

#不含括号字符串公式计算函数
def stringCalculate(string):
    fResult = 0.0  # 浮点型计算结果
    tmpListAdd = list()  # 加减法列表
    #公式数据拆分
    strList = stringFormat(string).split('+')
    #第一步先根据加法将字符串分段,如果分段内含有乘除法,则进入乘除法分段计算,否则转化成浮点数,存入列表
    for inLoopAdd in strList:  #第一层循环---加减法分割
        #乘法模块
        if'*' in inLoopAdd or '/' in inLoopAdd:
            tmpListMulti = list()  #乘法列表
            for inloopMulti in inLoopAdd.split('*'):   #第二层----乘法分割
                #除法模块
                if '/' in inloopMulti:
                    divList = inloopMulti.split('/')
                    fDivResult = float(divList[0])
                    for inloopDiv in range(len(divList)-1):  #第三层-----内层除法计算
                        fDivResult /= float(divList[inloopDiv+1])
                        tmpListMulti.append(fDivResult)
                else:
                    tmpListMulti.append(float(inloopMulti))
            fMultiResult = 1
            for inloop in tmpListMulti:
                fMultiResult *= inloop
            tmpListAdd.append(fMultiResult)
        elif inLoopAdd:
            tmpListAdd.append(float(inLoopAdd))
    #将各分段结果累加
    for fAddResult in tmpListAdd:
        fResult += fAddResult
    return str(fResult)

#去括号
while('(' in string):
        temString = re.search('\([0-9+\-*./]*\)', string).group()
        string = string.replace(temString, stringCalculate(temString[1:-1]))

print(stringCalculate(string))

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。

创新互联公司科技有限公司专业互联网基础服务商,为您提供成都IDC机房托管高防服务器,成都IDC机房托管,成都主机托管等互联网服务。
分享名称:通过Python正则表达式实现简单四则运算-创新互联
文章起源:http://cdweb.net/article/ggojs.html