码迷,mamicode.com
首页 > 其他好文 > 详细

Evaluate Reverse Polish Notation

时间:2014-08-22 12:18:26      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   io   for   ar   

Evaluate Reverse Polish Notation

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

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

Some examples:

["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9

["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

原题链接: https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/

题目大意: 逆波兰表达式

思路: 利用栈实现, 注意+, -单目运算符; 另外目前leetcode使用的python为2.7.5, 除法不是精确的除法, 两个整数相除是地板除, 浮点数除是精确的除法; 注意负数的判断, 使用isdigit是判断不了的;

 1 class Solution:
 2     # @param tokens, a list of string
 3     # @return an integer
 4     def evalRPN(self, tokens):
 5         stack = list()
 6 
 7         for token in tokens:
 8             try:
 9                 tmp = int(token)
10             except ValueError: #operator
11                 if token == +: #may be a unary operator
12                     if len(stack) > 1:
13                         o1 = stack.pop()
14                         o2 = stack.pop()
15 
16                         stack.append(o2 + o1)
17                 elif token == -:
18                     if len(stack) > 1:
19                         o1 = stack.pop()
20                         o2 = stack.pop()
21 
22                         stack.append(o2 - o1)
23                     else:
24                         o1 = stack.pop()
25                         stack.append(-o1)
26 
27                 elif token == *:
28                     o1 = stack.pop()
29                     o2 = stack.pop()
30 
31                     stack.append(o2 * o1)
32                 else:
33                     o1 = stack.pop()
34                     o2 = stack.pop()
35 
36                     stack.append(int(float(o2) / o1))
37 
38             else: #number
39                 stack.append(tmp)
40 
41             
42         return stack[0]

 

Evaluate Reverse Polish Notation,布布扣,bubuko.com

Evaluate Reverse Polish Notation

标签:style   blog   http   color   使用   io   for   ar   

原文地址:http://www.cnblogs.com/hzhesi/p/3928910.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!