zoukankan      html  css  js  c++  java
  • python 计算器

    import re
    def atom_cal(exp): # 计算乘除法
        if '*' in exp:
            a,b = exp.split('*')
            return str(float(a) * float(b))
        elif '/' in exp:
            a, b = exp.split('/')
            return str(float(a) / float(b))
    
    def fuhaochuli(exp): # 符号处理
        exp = exp.replace('++','+')
        exp = exp.replace('-+','-')
        exp = exp.replace('+-','-')
        exp = exp.replace('--','+')
        return exp
    
    def mul_div(exp): # 匹配乘除法进行计算并替换
        while True:
            ret = re.search('d+(.d+)?[*/]-?d+(.d+)?',exp)
            if ret:
                a = ret.group()
                b = atom_cal(a)
                exp = exp.replace(a,b)
            else:return exp
    
    def add_sub(exp): # 匹配加减法计算并进行替换
        res = re.findall('[-+]?d+(?:.d+)?',exp)
        exp_sum = 0
        for i in res:
            exp_sum += float(i)
        return exp_sum
    
    def cal(exp):    # 计算
        exp = mul_div(exp)
        exp = fuhaochuli(exp)
        exp_sum = add_sub(exp)
        return exp_sum
    
    def main(exp):    # 格式处理,计算结果并进行替换
        exp = exp.replace(" ",'')
        while True:
            ret = re.search('([^()]+)',exp)
            if ret:
                inner_bracket = ret.group()
                res = str(cal(inner_bracket))
                exp = exp.replace(inner_bracket,res)
                exp = fuhaochuli(exp)
            else:break
        return cal(exp)
    
    s = '3*(1+3-0.62)'
    ret = main(s)
    print(ret)
  • 相关阅读:
    希腊字母写法
    The ASP.NET MVC request processing line
    lambda aggregation
    UVA 10763 Foreign Exchange
    UVA 10624 Super Number
    UVA 10041 Vito's Family
    UVA 10340 All in All
    UVA 10026 Shoemaker's Problem
    HDU 3683 Gomoku
    UVA 11210 Chinese Mahjong
  • 原文地址:https://www.cnblogs.com/zbw582922417/p/9526262.html
Copyright © 2011-2022 走看看