题解 | #四则运算#

四则运算

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)

全部评论

相关推荐

lxylxy_:其实是美团卷起来了
点赞 评论 收藏
分享
整顿职场的柯基很威猛:这种不可怕,最可怕的是夹在一帮名校里的二本选手,人家才是最稳的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务