题解 | #表达式求值#留个纪念以后再改进#左右改的面目全非

表达式求值

https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d

def operate(operator, num1, num2):
    if operator == "+":
        return num1 + num2
    elif operator == "-":
        return num1 - num2
    elif operator == "*":
        return num1 * num2
    else:
        return num1 / num2


priority = {"+": 1, "-": 1, "*": 2, "/": 2, "(": 0, ")": 0}

receive = input()
digit = []
operand = list()
operator = list()
count = len(receive)

for i in receive:
    count -= 1
    if i.isdigit():
        digit.append(i)
        if count == 0:
            digit1 = int("".join(map(str, digit)))
            operand.append(digit1)
    else:
        if count == len(receive) - 1 and i == "-":  # 考虑负数的情况
            operand.append(0)
        if digit:
            digit1 = int("".join(map(str, digit)))
            digit = []
            operand.append(digit1)
        if (
            i == "-" and operator and operator[-1] == "(" and count == t
        ):  # 考虑负数的情况
            operand.append(0)
        if not operator or priority[i] > priority[operator[-1]] or i == "(":
            operator.append(i)
            if i == "(":#考虑负数的情况
                t = count - 1
        else:
            if i == ")":
                while operator[-1] != "(":
                    num2 = operand.pop()
                    num1 = operand.pop()
                    operand.append(operate(operator.pop(), num1, num2))
                operator.pop()

            else:
                while operator and priority[i] <= priority[operator[-1]]:
                    # while的先后不能颠倒,因为如果一个判断是语法错误,会直接报错而不
                    # 会进行后续判断
                    # 改成if没有通过的案例:
                    #  3*5+8-0*3-6+0+0
                   
                    num2 = operand.pop()
                    num1 = operand.pop()
                    operand.append(operate(operator.pop(), num1, num2))
                operator.append(i)

# print(operand)
# print(operator)
while operator: #上述不能得出最终结果,而是得到两个化简后的序列
                #其中,operator序列中 符号 优先度从左往右依次增大
    num2 = operand.pop()
    num1 = operand.pop()
    operand.append(operate(operator.pop(), num1, num2))
print(operand[0])


全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务