• 计算器


    import re,time
    
    # 1.先循环括号
    # 2.算括号的乘除,后算加减
    
    
    s ='1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
    
    def reduce_sysbol(name):        #"+-" 或 "-+"  换成-
        if re.search("(+-|-+|--)",name):
            return re.sub("(+-|-+|--)","-",name)
        return name
    
    
    def calculation(front,sign,back):
        if sign == "*":
            return (float(front) * float(back))
        elif sign == "/":
            return (float(front) / float(back))
        elif sign == "+":
            return (float(front) + float(back))
        else:
            return (float(front) - float(back))
    
    
    def priority(name):
        obj = name.strip("()")   #两边括号取消
        obj = reduce_sysbol(obj)
        while True:
            if re.search("(?P<front>d+.*d*)(?P<sign>[*/])(?P<back>-*d+.*d*)",obj):  #先找乘除
                a  = re.search("(?P<front>d+.*d*)(?P<sign>[*/])(?P<back>-*d+.*d*)",obj)
                b = calculation(a.group("front"),a.group("sign"),a.group("back"))
                obj = obj.replace(a.group(),str(b))
                continue
            elif re.search("(?P<front>-*d+.*d*)(?P<sign>[+-])(?P<back>-*d+.*d*)",obj):
                a = re.search("(?P<front>-*d+.*d*)(?P<sign>[+-])(?P<back>-*d+.*d*)",obj)
                b = calculation(a.group("front"), a.group("sign"), a.group("back"))
                obj = obj.replace(a.group(), str(b))
            else:
                return obj
    
    def run(arg):
        obj = arg.replace(" ", "")
        while True:
            if re.search("([^()]+)",obj):         #找括号里面没有括号的
                sea_brackets = re.search("([^()]+)",obj)
                jieguo = priority(sea_brackets.group())
                obj = obj.replace(sea_brackets.group(),str(jieguo))
            else:
                jieguo = priority(obj)
                if re.search("^-*d+.*d*",obj):
                    print(jieguo)
                    exit()
                obj = obj.replace(sea_brackets.group(),str(jieguo))
                print(obj)
    
    
    if __name__ == '__main__':
        run(s)
    

      

  • 相关阅读:
    冒泡排序
    三种for循环遍历
    打印一年中的月历
    基于主主复制的mysql双机热备+keepalived实现高可用性
    docker实现apache+php容器和mysql容器独立运行
    XML和JSON
    PHP表单
    【翻译-Docker】Post-installation steps for Linux
    【翻译】docker install
    小计划
  • 原文地址:https://www.cnblogs.com/golangav/p/6792240.html
Copyright © 2020-2023  润新知