python 四则运算计算器

刚开始只是为了实现某个功能,中间需要对表达式进行计算,想着写个四则运算计算器也很简单就顺手写了, 写到后面发现需要考虑的问题还挺多的,囧。

现在把代码贴出来记录一下这辛苦的过程吧,毕竟写得挺长的= =
不做解释了,单纯为了记录,毕竟写的也挺菜的,也就能基本实现功能2333

def calculate(in_formula: str) -> int:
    """
    对字符串类型的数学表达式进行计算,返回计算结果
    数学表达式可包含加减乘除、括号
    :param in_formula: 数学表达式 如'2*(-5+3)/-1+20/(3+1)+2+(-9-2)*2'
    :return: 计算结果
    """
    if '(' in in_formula:
        result_in_brackets = []
        reg_formula_in_brackets = re.compile(r'\([^(]+\)')
        formula_in_brackets = reg_formula_in_brackets.findall(in_formula)
        else_formula = reg_formula_in_brackets.split(in_formula)
        for i in formula_in_brackets:
            result_in_brackets.append(simple_arithmetic(re.sub(r"[()]", '', i)))
        for i in range(0, int(len(else_formula)) + 1, 2):
            else_formula.insert(i + 1, str(result_in_brackets[int(i / 2)]))
        result = simple_arithmetic(''.join(else_formula))
    else:
        result = simple_arithmetic(''.join(in_formula))
    return result


def simple_arithmetic(in_formula: str) -> int:
    """
    不含括号的简单公式计算(加减乘除)
    :param in_formula: 只包含加减乘除不含括号的计算公式
    :return: 计算结果
    """
    result = 0
    if '+' in in_formula or '-' in in_formula:

        reg = re.compile(r"(?<![+*/\-])[+\-]")
        operators = reg.findall(in_formula)
        sub_formulas = reg.split(in_formula)

        for ind, sub_formula in enumerate(sub_formulas):
            if ind == 0 and sub_formula == '':
                sub_formulas[0] = 0
                sub_formulas[1] = operators[0] + sub_formulas[1]
                operators[0] = '+'
                continue
            if '/' in sub_formula or '*' in sub_formula:
                val = multiply_divide(sub_formula)
            else:
                val = int(sub_formula)
            sub_formulas[ind] = val
        result = sub_formulas[0]
        for ind, i in enumerate(operators):
            if i == '+':
                result += int(sub_formulas[ind + 1])
            elif i == '-':
                result -= int(sub_formulas[ind + 1])

    elif '/' in in_formula or '*' in in_formula:
        result = multiply_divide(in_formula)

    else:
        return result
    return result


def multiply_divide(in_formula: str) -> int:
    """
    乘除法的计算
    :param in_formula:只含有乘除法的计算公式
    :return: 计算结果
    """
    result = 1
    if '/' not in in_formula:
        sub_formulas = in_formula.split('*')
        for i in sub_formulas:
            result = result * int(i)
    elif '*' not in in_formula:
        sub_formulas = in_formula.split('/')
        for ind, i in enumerate(sub_formulas):
            result = int(i) if ind == 0 else result / int(i)
    else:
        reg = re.compile(r'[*/]')
        operators = reg.findall(in_formula)
        sub_formulas = reg.split(in_formula)
        result = int(sub_formulas[0])
        for ind, i in enumerate(operators):
            if i == '*':
                result = int(sub_formulas[ind + 1]) * result
            elif i == '/':
                result = result / int(sub_formulas[ind + 1])
    return result


def addition_subtraction(formula: str) -> int:
    """
    加减法运算
    :param formula:只含有加减法的运算公式
    :return: 运算结果
    """
    result = 0
    if '+' not in formula:
        sub_formulas = formula.split('-')
        result = int(sub_formulas[0])
        for i in sub_formulas[1:]:
            result = result - int(i)
    elif '-' not in formula:
        sub_formulas = formula.split('+')
        for i in sub_formulas:
            result = int(i) + result

    elif '+' in formula or '-' in formula:
        reg = re.compile(r'[+\-]')
        operators = reg.findall(formula)
        sub_formulas = reg.split(formula)
        result = int(sub_formulas[0])
        for ind, i in enumerate(operators):
            if i == '+':
                result += int(sub_formulas[ind + 1])
            elif i == '-':
                result -= int(sub_formulas[ind + 1])
    else:
        return formula
    return result


if __name__ == '__main__':
    print(calculate('2*(-5+3)/-1+20/(3+1)+2+(-9-2)*2'))

posted @ 2019-12-25 11:22  丛影HHZ  阅读(1712)  评论(0编辑  收藏  举报