python 实现一个计算器功能

#s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
#第一步 分步实现 ("2-1*-22+3-10/-5")
    # 1. 实现一个乘除法  两两相乘/相除
    # 2. 实现一个加减法  两两相加/相减
    # 3. 把计算结果 替换原来的表达式
    # 4. 替换完成后 处理整体表达式的符号
    # 5. 五个函数: 计算atom_cal()  format()  mul_div()  add_sub()  cal()
#第二步 去括号 计算括号内的

import re

def format(exp):
    exp = exp.replace("-+","-")
    exp = exp.replace("+-","-")
    exp = exp.replace("--","+")
    exp = exp.replace("++","+")
    return exp


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 mul_div(exp):
    while True:
        ret = re.search("d+(.d+)?[*/]-?d+(.d+)?",exp)    #拿到乘除表达式 #从左到右拿结果,拿不到返回None
        if ret:
            atom_exp = ret.group()
            res = atom_cal(atom_exp)
            # print(atom_exp,res)
            exp = exp.replace(atom_exp,res)
        else:
            return exp


def add_sub(exp):
    ret = re.findall("[+-]?d+(?:.d+)?", exp)  # 取出数字和数字前面的符号  findall返回的是一个列表 查找所有项
    exp_sum = 0
    for i in ret:
        exp_sum = exp_sum + float(i)  # 取出来的是字符串
    return exp_sum


def cal(exp):
    exp = mul_div(exp)
    exp = format(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 = format(exp)
        else:break
    return cal(exp)
s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
ret = main(s)
print(ret)
原文地址:https://www.cnblogs.com/kenD/p/9525984.html