#Leet Code# Evaluate Reverse Polish Notation
描述:计算逆波兰表达法的结果
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的更多相关文章
- 【leetcode】Evaluate Reverse Polish Notation
Evaluate Reverse Polish Notation 题目描述: Evaluate the value of an arithmetic expression in Reverse Pol ...
- [LintCode] Evaluate Reverse Polish Notation 计算逆波兰表达式
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...
- 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 ...
- 【LeetCode练习题】Evaluate Reverse Polish Notation
Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish No ...
- leetcode - [2]Evaluate Reverse Polish Notation
Evaluate Reverse Polish Notation Total Accepted: 24595 Total Submissions: 123794My Submissions Evalu ...
- 【LeetCode】150. Evaluate Reverse Polish Notation
Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish No ...
- LeetCode: Evaluate Reverse Polish Notation 解题报告
Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish No ...
- LeetCode 150. 逆波兰表达式求值(Evaluate Reverse Polish Notation) 24
150. 逆波兰表达式求值 150. Evaluate Reverse Polish Notation 题目描述 根据逆波兰表示法,求表达式的值. 有效的运算符包括 +, -, *, /.每个运算对象 ...
- 【LeetCode】150. Evaluate Reverse Polish Notation 解题报告(Python)
[LeetCode]150. Evaluate Reverse Polish Notation 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/ ...
随机推荐
- index of rmvb mp3 rm突破站点入口下载
首先打开Google,在关键词输入框中输入"index of/"inurl:lib(双引號为英文状态下) ,选择“搜索中文简体网页”选项,回车搜索,得到了一些网页,不要以为这是一些 ...
- UVA 110 Meta-Loopless Sorts(输出挺麻烦的。。。)
Meta-Loopless Sorts Background Sorting holds an important place in computer science. Analyzing and ...
- 【VBA研究】变量定义的类型和实际赋值类型
作者:iamlaosong VBA中变量能够先定义后使用,也能够不定义直接使用.假设模块前面加了Option Explicit语句,则变量必须先定义后使用. 只是.实验发现.VBA对变量类型没有进行严 ...
- 69 Spring Interview Questions and Answers – The ULTIMATE List--reference
This is a summary of some of the most important questions concerning the Spring Framework, that you ...
- 安卓蓝牙技术Bluetooth使用流程(Bluetooth详解)
一:蓝牙设备之间的通讯首要包含了四个进程 设置蓝牙设备 寻觅局域网内也许或许匹配的设备 衔接设备 设备之间的数据传输 二:详细编程完结 1. 发动蓝牙功用 首要经过调用静态办法getDefaultAd ...
- iOS之KVO和KVC
概述 由于ObjC主要基于Smalltalk进行设计,因此它有很多类似于Ruby.Python的动态特性,例如动态类型.动态加载.动态绑定等.今天我们着重介绍ObjC中的键值编码(KVC).键值监听( ...
- iOS 网络编程:XML解析
1 XML文档结构 1.1 简介 XML 指可扩展标记语言(eXtensible Markup Language).XML 被设计用来传输和存储数据.其非常像HTML的标记语言,但与之不同的是,XML ...
- Linux基础(二)
二.Linux 常用命令 一.命令行操作的流程 录入命令(可以使用各种途径来发送命令) 命令被解释器解释并执行 将结果以产品需要的方式显示出来 二.命令提示符 sq@sq-VirtualBox:~$ ...
- JavaScript入门(7)
一.什么是函数 函数:把完成特定功能的代码放到一个函数里,直接调用这个函数,就省去重复输入大量代码的麻烦 函数的作用:写一次代码,然后反复地重用这个代码 Eg: 求多组数的和,不使用函数 { var ...
- 검색엔진의 크롤링과 인덱싱의 차이 (robots.txt 파일과 meta robots 태그의 차이점)
검색엔진의 크롤링과 인덱싱의 차이크롤링 제어는 robots.txt인덱싱 제어는 < meta name="robots" content="noindex& ...