牛客---计算四则运算

输入一个表达式(用字符串表示),求这个表达式的值。保证字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。且表达式一定合法。

输入:3+2*{1+2*[-4/(8-6)+7]}
输出:25

方法一:利用eval函数

def calculate_expression(expression:str):
    expression = expression.replace('[','(').replace(']',')')
    expression = expression.replace('{','(').replace('}',')')
    try:
        result = eval(expression)
        return result
    except:
        raise ValueError(f"表达式计算出错: {e}")

方法二:栈

from ast import operator
import sys

def calculate(expression: str) -> float:
    def evaluate(tokens):
        values = []
        operators = []

        def apply_operator():
            right = values.pop()
            left = values.pop()
            operator = operators.pop()
            if operator == "+":
                values.append(left + right)
            elif operator == "-":
                values.append(left - right)
            elif operator == "*":
                values.append(left * right)
            elif operator == "/":
                values.append(left / right)

        precedence = {"+": 1, "-": 1, "*": 2, "/": 2}

        i = 0
        while i < len(tokens):
            token = tokens[i]
            if token.isdigit():  # 处理数字
                num = 0
                while i < len(tokens) and tokens[i].isdigit():
                    num = num * 10 + int(tokens[i])
                    i += 1
                values.append(num)
                continue
            elif token == "-" and (i == 0 or tokens[i - 1] in "+-*/([{"):
                # 处理负数(作为一元运算符)
                num = 0
                i += 1
                while i < len(tokens) and tokens[i].isdigit():
                    num = num * 10 + int(tokens[i])
                    i += 1
                values.append(-num)
                continue
            elif token in "([{":  # 左括号,递归解析子表达式
                start = i + 1
                balance = 1
                while balance != 0:
                    i += 1
                    if tokens[i] in "([{":
                        balance += 1
                    elif tokens[i] in ")]}":
                        balance -= 1
                values.append(evaluate(tokens[start:i]))

            elif token in "+-*/":  # 处理操作符
                while (
                    operators and precedence.get(operators[-1], 0) >= precedence[token]
                ):
                    apply_operator()
                operators.append(token)
            elif token in ")]}":  # 右括号,跳过(不会发生因为已处理)
                pass
            i += 1

        # 处理剩余的操作符
        while operators:
            apply_operator()
        return values[0]

    # 预处理表达式以去除空格并转换为字符列表
    tokens = list(expression.replace(" ", ""))
    return evaluate(tokens)


for line in sys.stdin:
    a = line.split()
    print(int(calculate(a[0])))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值