题解 | #逆波兰表达式求值#

逆波兰表达式求值

https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382

from typing import List

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for token in tokens:
            if token in {'+', '-', '*', '/'}:
                b = stack.pop()
                a = stack.pop()
                if token == '+':
                    stack.append(a + b)
                elif token == '-':
                    stack.append(a - b)
                elif token == '*':
                    stack.append(a * b)
                elif token == '/':
                    # Ensure b is not zero to avoid division by zero error
                    if b == 0:
                        raise ValueError("Division by zero encountered")
                    stack.append(int(a / b))  # Assuming integer division is intended
            else:
                stack.append(int(token))
        return stack[0]  # The final result is on top of the stack

全部评论

相关推荐

三本咋了:觉得真的挺优秀的 实习title够了 ,字节实习跟agent不是很垂直 换个agent项目 差个机会,祈好运 ,有个教学类型的hello_agents 在github上面 感觉不太够用 (当然我还在学) ,你现在有好的项目了么,推荐一下呗
听劝,我这个简历该怎么改...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务