python 求表达式的值

197 阅读1分钟

python3 计算表达式算法题

输入一个表达式字符串,只支持“+-*”三种运算,返回计算结果

输入:"(2*(3-4))*5"

返回值: -10

代码

class Solution:

def cal(self,num1 ,num2,op):

    if op == "+":
        return num2 + num1
    elif op == "-":
        return num2 - num1
    else:
        return num2 * num1
def isnum(self,n):

    l = [i for i in range(10)]
    try:
        return int(n) in l
    except:
        return False
def solve(self , s: str) -> int:

    stack_num = []
    num = []
    stackop = []
    i = 0
    while i < len(s):
        if self.isnum(s[i]):
            j = i+1
            while j < len(s) and self.isnum(s[j]):
                j += 1
            stack_num.append(int(s[i:j]))
            i = j-1
        elif s[i] == ")":
             while stackop[-1] != "(" and len(stack_num) > 1:
                op = stackop.pop()
                num1 = stack_num.pop()
                num2 = stack_num.pop()
                n = self.cal(num1, num2, op)
                stack_num.append(n)
             stackop.pop()
        elif s[i] in "+-":
            while stackop and stackop[-1] in '+-*':
                op = stackop.pop()
                num1 = stack_num.pop()
                num2 = stack_num.pop()
                n = self.cal(num1, num2, op)
                stack_num.append(n)
            stackop.append(s[i])
        else:
            stackop.append(s[i])
        i += 1
    print(stack_num)
    print(stackop)
    while stackop:
        op = stackop.pop()
        num1 = stack_num.pop()
        num2 = stack_num.pop()
        n = self.cal(num1, num2, op)
        stack_num.append(n)
        
    return stack_num[-1]