• python 实现计算器功能 输入字符串,输出相应结果


    import re
    formul='1 - 2 *( (6 0- 30+(0-40/5) * (9-2* 5/3 +7 /3*99/4*2998 +10 *568/14)) - (-4*3) / (16-3*2))'
    def zhengli(func):
        func = func.replace("+-","-").replace("--","+")
        return func
    def addjian(func):
        func = func.strip("()")
        ret = re.findall("-?d*.?d+",func)
        sum=0
        for i in ret:
            sum +=float(i)
        return str(sum)
    def chengchu(func):
        func = func.strip("()")
        while("/"in func or "*" in func):
            ret = re.search('d*.?d+[*/]-?d*.?d',func).group()
            digital = re.split('([*/])',ret)         #加个括号是为了优先级的原因,保留非数字
            result = str(float(digital[0])*float(digital[2])) if digital[1] == '*' else str(float(digital[0])/float(digital[2]))
            func = func.replace(ret,result,1)
            func = zhengli(func)
        return func
    
    
    def comput(formal):
        formal = re.sub('s','',formal)
        while(re.search('([^()]*)',formal)):
            print(formal)
            ret = re.findall('([^()]*)',formal)
            for i in ret:
                print("wu kuohao:"+i)
                result_chengchu = chengchu(i) if '*'in i or '/' in i else i#先算乘除
                result_addjian = addjian(result_chengchu) if '+'in result_chengchu or '-' in result_chengchu else result_chengchu#再算加减
                formal = formal.replace(i,result_addjian,1)
                formal = zhengli(formal)
        else:
            result_chengchu = chengchu(formal) if '*' in formal or '/' in formal else formal  # 先算乘除
            result_addjian = addjian(result_chengchu) if '+' in result_chengchu or '-' in result_chengchu else result_chengchu  # 再算加减
            return result_addjian
    
    
    print(comput(formul))
  • 相关阅读:
    异常介绍
    docker 命令
    acm
    Openfiler能把标准x86/64架构的系统变成一个强大的NAS、SAN存储和IP存储网关
    docker 图解学习
    基于Docker的TensorFlow机器学习框架搭建和实例源码解读
    菜鸟打印控件
    Oracle 12c on Solaris 10 安装文档
    内存对齐小解
    安装oracle 11gr2 rac on solaris
  • 原文地址:https://www.cnblogs.com/double-t/p/10192333.html
Copyright © 2020-2023  润新知