[Leetcode][python]150. Evaluate Reverse Polish Notation

150. Evaluate Reverse Polish Notation


知识点:stack

1. 原题

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Note:

Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won’t be any divide by zero operation.
Example 1:

Input: [“2”, “1”, “+”, “3”, “*”]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:

Input: [“4”, “13”, “5”, “/”, “+”]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:

Input: [“10”, “6”, “9”, “3”, “+”, “-11”, “", “/”, "”, “17”, “+”, “5”, “+”]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

2. 题意

利用栈对后缀表达式进行计算

3. 思路

  • 我是用的时候忘记用stack了,所以是自己用list模仿了stack的性质
  • 值得注意的是,python中的“/”除法和c语言不太一样。在python中,(-1)/2=-1,而在c语言中,(-1)/2=0。也就是c语言中,除法是向零取整,即舍弃小数点后的数。而在python中,是向下取整的。而这道题是默认的c语言中的语法,所以需要在遇到“/”的时候注意一下
  • 在判断string是否是数字的地方,我首先用了isdigit(),但是这个函数只能判断正数,小数和负数都不ok,所以我是使用了一个自定义的函数
  • 我是对string是否是数字进行的判断,之后发现直接对操作符进行判断更为简单
  • 取整http://kuanghy.github.io/2016/09/07/python-trunc
  • 还有要记得要del一位数字,就是两个数字中的后面那个在这里插入图片描述

4. 代码

4.1. 没有用stack,对数字进行判断的代码

class Solution(object):
    def is_number(self,s):
        try:  # 如果能运行float(s)语句,返回True(字符串s是浮点数)
            float(s)
            return True
        except ValueError:  # ValueError为Python的一种标准异常,表示"传入无效的参数"
            pass  # 如果引发了ValueError这种异常,不做任何事情(pass:不做任何事情,一般用做占                        位语句)
        try:
            import unicodedata  # 处理ASCii码的包
            unicodedata.numeric(s)  # 把一个表示数字的字符串转换为浮点数返回的函数
            return True
        except (TypeError, ValueError):
            pass
        return False
    
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        t=tokens
        l=len(t)
        n=[]
        
        for i in range(l):
            if self.is_number(t[i]):
                n.append(int(t[i]))
            else:
                if t[i]=="+":
                    n[len(n)-2]= n[len(n)-2]+ n[len(n)-1]
                    del n[len(n)-1]
                elif t[i]=="-":
                    n[len(n)-2]= n[len(n)-2]- n[len(n)-1]
                    del n[len(n)-1]
                elif t[i]=="*":
                    n[len(n)-2]= n[len(n)-2]* n[len(n)-1]
                    del n[len(n)-1]
                elif t[i]=="/":
                    
                    a=n[len(n)-2]
                    b=n[len(n)-1]
                    if a*b<0:
                        n[len(n)-2]=-((-a)/b)
                    else:
                        n[len(n)-2]=a/b
                    del n[len(n)-1]
        
        return n[0]
        
        
            

4.2. 用stack,对符号进行判断的代码

class Solution:
    def evalRPN(self, tokens: List[str]):
        stack = []
        for token in tokens:
            if token not in ["+", "-", "*", "/"]:
                stack.append(int(token))              
            else:
                b, a = stack.pop(), stack.pop()
                if token == '+':
                    stack.append(a+b)
                elif token == '-':
                	stack.append(a-b)
                elif token == '*':
                    stack.append(a*b)
                elif token == '/':
                    if a*b < 0:
                        stack.append(-((-a)/b))
                    else:
                        stack.append(a/b)
                
        return stack[0]

5. Reference

https://www.cnblogs.com/zuoyuan/p/3760530.html
https://www.jianshu.com/p/6e15345d4758
https://www.runoob.com/python3/python3-check-is-number.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值