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

#Leet Code# Evaluate Reverse Polish Notation

时间:2014-07-26 00:13:26      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   数据   io   for   re   

描述:计算逆波兰表达法的结果

Sample:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

使用stack实现:

 1 def is_op(c):
 2     return c in [+, -, *, /]
 3 
 4 def divide(x, y):
 5     if (x * y) < 0:
 6         return -1 * ((-x)/y)
 7     return x/y
 8 
 9 class Solution:
10     # @param tokens, a list of string
11     # @return an integer
12     def evalRPN(self, tokens):
13         opDict = {+: lambda x,y: x+y,
14                   -: lambda x,y: x-y,
15                   *: lambda x,y: x*y,
16                   /: divide}
17         record = []
18 
19         for item in tokens:
20             if is_op(item):
21                 second = record.pop()
22                 first = record.pop()
23                 record.append(opDict[item](first, second))
24             else:
25                 record.append(int(item))
26         return record[0]

使用树实现:

Todo

备注:python的除法跟c++不太一样 3/-5 = -1

结论:

根据问题的具体特性,选择合适的数据结构解决问题会差别很大

#Leet Code# Evaluate Reverse Polish Notation,布布扣,bubuko.com

#Leet Code# Evaluate Reverse Polish Notation

标签:style   blog   color   使用   数据   io   for   re   

原文地址:http://www.cnblogs.com/mess4u/p/3868449.html

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