逆波兰式 (2018-10-31)

原文(https://blog.csdn.net/zhangla1220/article/details/39060421)

题目:

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

代码:

def caculate(oper, x, y):
    if oper== '+' :
            return x+y
    if oper== '-' :
            return x-y
    if oper== '*' :
            return x*y
    if oper== '/' :
            return x/y
   
def evalRPN(tokens):
    if (len(tokens) == 0):
        return 0;
    tokens_s = []
    result = 0
    i = 0;
    x = 0
    y = 0
    for i in range(0,len(tokens)):
        element = tokens[i] 
        if ((element== "+") or (element== "-") or (element== "*") or (element== "/")):
            y = tokens_s.pop()
            x = tokens_s.pop()
            tokens_s.append(int(caculate(element,int(x),int(y))))
        else:
            tokens_s.append(int(element))
    return (int)(tokens_s.pop())
tokens =  []#test
print(evalRPN(tokens))
tokens =  ["2", "1", "+", "3", "*"]#test
print(evalRPN(tokens))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 10,014评论 0 13
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,341评论 0 38
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 2,207评论 0 2
  • [TOC] PS.发布了才发现简书不支持TOC,给差评 基础知识 这里我就不废话什么是Git了,程序猿用的东西,不...
    onlycj阅读 1,151评论 1 55
  • 大学时光真快,三年一下子就过去了,自己在学校学的专业是汽车技术服务与营销,说白了就是一买车的,很多人感觉这工作根本...
    Immortals丶QJ阅读 199评论 0 0

友情链接更多精彩内容