题解 | #四则运算#

四则运算

https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e

def check_priority(op):
    if op == "*" or op == "/":
        return 2
    elif op == "+" or op == "-":
        return 1
    return 0

def apply_op(val1, val2, op):
    if op == "+":
        return val1 + val2
    elif op == "-":
        return val1 - val2
    elif op == "*":
        return val1 * val2
    else:
        return val1 // val2
    
def evaluate_eq(eq):
    i = 0
    vals = []
    ops = []
    while i < len(eq):
        if eq[i] == "(":
            ops.append(eq[i])
            i += 1
            continue
        elif eq[i].isdigit() or (eq[i] == "-" and (i == 0 or eq[i-1] == "(")):
            val = 0
            sign = 1
            if eq[i] == "-":
                sign = -1
                i += 1
            while i < len(eq) and eq[i].isdigit():
                val = val * 10 + int(eq[i])
                i += 1
            vals.append(sign * val)
            i -= 1
        elif eq[i] == ")":
            while len(ops) != 0 and ops[-1] != "(":
                val2 = vals.pop()
                val1 = vals.pop()
                op = ops.pop()
                rst = apply_op(val1, val2, op)
                vals.append(rst)
            ops.pop()
        else:
            while len(ops) != 0 and check_priority(eq[i]) <= check_priority(ops[-1]):
                val2 = vals.pop()
                val1 = vals.pop()
                op = ops.pop()
                rst = apply_op(val1, val2, op)
                vals.append(rst)
            ops.append(eq[i])
        i += 1

    while len(ops) != 0:
        val2 = vals.pop()
        val1 = vals.pop()
        op = ops.pop()
        rst = apply_op(val1, val2, op)
        vals.append(rst)
    return vals[-1]


eq = input().replace("[", "(").replace("]", ")").replace("{", "(").replace("}", ")")
val = evaluate_eq(eq)
print(val)

全部评论

相关推荐

10-28 14:42
门头沟学院 Java
watermelon1124:因为嵌入式炸了
点赞 评论 收藏
分享
羊村懒哥:刚想骂一看是友军对不起
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务