不为成仙,只为在这红尘中等你回来。

您现在的位置是:网站首页>>Python

Python3 计算器作业(正则)

2020年7月22日 15:16 | 分类:Python | 标签: Python

实现能计算类似 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) ) 等类似公式的计算器程序

import re


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


def cal_atom(exp):
    if '*' in exp:
        num1, num2 = exp.split("*")
        return str(float(num1) * float(num2))
    else:
        num1, num2 = exp.split("/")
        return str(float(num1) / float(num2))


def inner_bracket(exp, muldiv_re, addsub_re):
    """加减乘除运算"""
    while True:
        ret = muldiv_re.search(exp)
        if ret:
            ret = ret.group()
            res = cal_atom(ret)
            exp = exp.replace(ret, res)
        else:
            break
    exp = exp_format(exp)
    ret = addsub_re.findall(exp)
    count = 0
    for i in ret:
        count += float(i)

    return count


def remove_brackets(exp, bracket_re, muldiv_re, addsub_re):
    """优先计算最内层括号中的表达式"""
    while True:
        ret = bracket_re.search(exp)
        if ret:
            ret = ret.group()
            res = inner_bracket(ret, muldiv_re, addsub_re)
            exp = exp.replace(ret, str(res))
            exp = exp_format(exp)
        else:
            return exp


def main(exp):
    exp = exp.replace(" ", "")
    bracket_re = re.compile("\([^()]+\)")
    muldiv_re = re.compile(r"\d+(\.\d+)?[*/]-?\d+(\.\d+)?")
    addsub_re = re.compile("[-+]?\d+(?:\.\d+)?")
    exp = remove_brackets(exp, bracket_re, muldiv_re, addsub_re)
    return inner_bracket(exp, muldiv_re, addsub_re)


exp = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
print(main(exp))