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))

 

posted @ 2018-12-28 18:56  会飞的两棵树  阅读(2262)  评论(0编辑  收藏  举报