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

Sample:

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

使用stack实现:

 def is_op(c):
return c in ['+', '-', '*', '/'] def divide(x, y):
if (x * y) < 0:
return -1 * ((-x)/y)
return x/y class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
opDict = {'+': lambda x,y: x+y,
'-': lambda x,y: x-y,
'*': lambda x,y: x*y,
'/': divide}
record = [] for item in tokens:
if is_op(item):
second = record.pop()
first = record.pop()
record.append(opDict[item](first, second))
else:
record.append(int(item))
return record[0]

使用树实现:

 def is_op(c):
return c in ['+', '-', '*', '/'] def divide(x, y):
if (x * y) < 0:
return -1 * ((-x)/y)
return x/y class Tree:
def __init__(self, data):
self.data = data
self.parent = None
self.left = None
self.right = None class Solution:
# @param tokens, a list of string
# @return an integer
def __init__(self):
self.opDict = {'+': lambda x,y: x+y,
'-': lambda x,y: x-y,
'*': lambda x,y: x*y,
'/': divide} def builtTree(self, tokens):
if not is_op(tokens[-1]):
return int(tokens[-1]) # if element is an operator
cur_tree = Tree(tokens[-1])
top_tree = cur_tree for item in tokens[-2::-1]:
if cur_tree.right is None:
if is_op(item):
cur_tree.right = Tree(item)
cur_tree.right.parent = cur_tree
cur_tree = cur_tree.right
else:
cur_tree.right = int(item) if cur_tree.right and cur_tree.left:
cur_tree = self.getUpperNode(cur_tree)
continue if cur_tree.left is None:
if is_op(item):
cur_tree.left = Tree(item)
cur_tree.left.parent = cur_tree
cur_tree = cur_tree.left
else:
cur_tree.left = int(item) if cur_tree.right is not None and cur_tree.left is not None:
cur_tree = self.getUpperNode(cur_tree) return top_tree # Move to upper node if cur node if full. If top_node return.
def getUpperNode(self, node):
while node.right is not None and node.left is not None:
if node.parent is None:
return node node = node.parent return node def getValue(self, node):
if type(node) is type(1):
return node
else:
return self.getResult(node) def getResult(self, treeNode):
leftValue = self.getValue(treeNode.left)
rightValue = self.getValue(treeNode.right) result = self.opDict[treeNode.data](leftValue, rightValue) return result def evalRPN(self, tokens):
topNode = self.builtTree(tokens) if type(topNode) is type(1):
return topNode
else:
resultNum = self.getResult(topNode)
return resultNum

备注-1:if cur_node.right is None 不能用 if cur_node.right 因为cur_node.right 如果是数字0的话会有问题 当然 不转成int的话直接存string等到运算时再转int应该就可以这样写了

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

结论:

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

#Leet Code# Evaluate Reverse Polish Notation的更多相关文章

  1. 【leetcode】Evaluate Reverse Polish Notation

    Evaluate Reverse Polish Notation 题目描述: Evaluate the value of an arithmetic expression in Reverse Pol ...

  2. [LintCode] Evaluate Reverse Polish Notation 计算逆波兰表达式

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...

  3. LeetCode: Reverse Words in a String:Evaluate Reverse Polish Notation

    LeetCode: Reverse Words in a String:Evaluate Reverse Polish Notation Evaluate the value of an arithm ...

  4. 【LeetCode练习题】Evaluate Reverse Polish Notation

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

  5. leetcode - [2]Evaluate Reverse Polish Notation

    Evaluate Reverse Polish Notation Total Accepted: 24595 Total Submissions: 123794My Submissions Evalu ...

  6. 【LeetCode】150. Evaluate Reverse Polish Notation

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

  7. LeetCode: Evaluate Reverse Polish Notation 解题报告

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

  8. LeetCode 150. 逆波兰表达式求值(Evaluate Reverse Polish Notation) 24

    150. 逆波兰表达式求值 150. Evaluate Reverse Polish Notation 题目描述 根据逆波兰表示法,求表达式的值. 有效的运算符包括 +, -, *, /.每个运算对象 ...

  9. 【LeetCode】150. Evaluate Reverse Polish Notation 解题报告(Python)

    [LeetCode]150. Evaluate Reverse Polish Notation 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/ ...

随机推荐

  1. play wav sound

    播放 WAV文件             string s = @"D:\Administrator\安装文件\完美世界国际版\patcher\skin\sounds\click.wav&q ...

  2. java 5 线程池

    import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Thr ...

  3. 【OpenCV-Python】Python Extension Packages for Windows

    下载相关Python的扩展包,请点击这里: This page provides 32- and 64-bit Windows binaries of many scientific open-sou ...

  4. xml配置和基于java类的bean配置搭配使用

    如果同时使用了xml配置,和java类的bean配置(当然估计项目中一般不会这样), 在初始化容器指定资源文件的时候可能会比较麻烦 此时我们可以把基于java类的bean配置整合到xml中,或xml的 ...

  5. 有关Color和Drawable你所不知道的那些内容

    Android开发中,我们经常会用到Color或Drawable,有时他们是可以混用的,有时却有严格的区别. Drawable 体系结构 Drawable是可绘制物件的一般抽象.与View不同,Dra ...

  6. python--class test

    # !usr/bin/env  python3#-*- coding:utf-8 -*- 'a test class'class Student(object):    def __init__(se ...

  7. c#实现几种排序方法

    插入排序 1.简介 插入排序(Insertion Sort)的算法描述是一种简单直观的排序算法.它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入.插入排序 ...

  8. Java并发——使用Condition线程间通信

    线程间通信 线程之间除了同步互斥,还要考虑通信.在Java5之前我们的通信方式为:wait 和 notify.Condition的优势是支持多路等待,即可以定义多个Condition,每个condit ...

  9. centos 下安装ati显卡驱动方法

    1)到ati的官网(http://support.amd.com/us/gpudownload/Pages/index.aspx)下载相应的驱动,一定要注意 radeon系列和mobility rad ...

  10. Verilog-1995 VS Verilog-2001

    http://www.cnblogs.com/tshell/p/3236476.html 2001年3月IEEE正式批准了Verilog‐2001标准(IEEE1364‐2001),与Verilog‐ ...