150. 逆波兰表达式求值

150. 逆波兰表达式求值,第1张

150. 逆波兰表达式求值


我直接震惊、、、怪不得一开始一直不过 卡在了这里 我淦

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        '''
        思路:栈实现,遇着数字入栈,遇着运算符出栈
        '''
        stack = []
        for i in tokens:
            if i not in ['+','-','*','/']: # 判断该字符是否为字符串
                stack.append(int(i))
            else:
                a,b = stack.pop(),stack.pop() # 根据题意,stack里面必定至少有俩元素
                if i == '+':
                    stack.append(b+a)
                elif i == '-':
                    stack.append(b-a)
                elif i == '/':
                    stack.append(int(b/a))
                else:
                    stack.append(b*a)
        return stack.pop()

看了一下答案,这个语句写的确实六六

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for item in tokens:
            if item not in {"+", "-", "*", "/"}:
                stack.append(item)
            else:
                first_num, second_num = stack.pop(), stack.pop()
                stack.append(
                    int(eval(f'{second_num} {item} {first_num}'))   # 第一个出来的在运算符后面
                )
        return int(stack.pop()) # 如果一开始只有一个数,那么会是字符串形式的

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5702566.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存