python实现逆波兰计算表达式的代码

如下资料是关于python实现逆波兰计算表达式的代码。

symbol_priority = {}
symbol_priority[0] = [‘#‘]
symbol_priority[1] = [‘(‘]
symbol_priority[2] = [‘+‘, ‘-‘]
symbol_priority[4] = [‘)‘]

def comparePriority(symbol, RPN_stack, symbol_stack):
    ‘‘‘Compare priority between two symbols‘‘‘

    global symbol_priority
    if len(symbol_stack) > 0:
        symbol_pop = symbol_stack.pop()
    else:
        return

    for list in symbol_priority.values():
        if (symbol in list) and (symbol_pop in list):
            ‘‘‘same priority‘‘‘
            symbol_stack.append(symbol_pop)
            symbol_stack.append(symbol)
            return
        elif symbol in list:
            ‘‘‘symbol is smaller‘‘‘
            RPN_stack.append(symbol_pop)
            #recusion call
            comparePriority(symbol, RPN_stack, symbol_stack)
            return
        elif symbol_pop in list:
            ‘‘‘symbol is bigger‘‘‘
            symbol_stack.append(symbol_pop)
            symbol_stack.append(symbol)
            return
        else:
            continue

        symbol_stack.append(symbol_pop)
        return

def scanEveryone(input_string, RPN_stack, symbol_stack):
    for ch in input_string:
        if ch.isdigit():
            RPN_stack.append(ch)
        else:
            if len(symbol_stack) > 0:
                if ch == ‘(‘:
                    symbol_stack.append(ch)
                elif ch == ‘)‘:
                    while True:
                        symbol_pop = symbol_stack.pop()
                        if symbol_pop == ‘(‘:
                            break
                        else:
                            RPN_stack.append(symbol_pop)
                else:
                    comparePriority(ch, RPN_stack, symbol_stack)
            else:
                symbol_stack.append(ch)

def scanInput(RPN_stack, symbol_stack):
    input_string = raw_input()
    input_string += ‘#‘
    scanEveryone(input_string, RPN_stack, symbol_stack)

def calRPN(RPN_stack):
    value_stack = []
    RPN_stack.append(‘#‘)

    for value in RPN_stack:
        if value == ‘#‘:
            return value_stack.pop()
            break
        if value.isdigit():
            value_stack.append(value)
        else:
            right_value = value_stack.pop()
            left_value = value_stack.pop()
            cal_string = left_value + value + right_value
            value_stack.append(str(eval(cal_string)))

def main():
    RPN_stack = []
    symbol_stack = []

    scanInput(RPN_stack, symbol_stack)
    print calRPN(RPN_stack)

if __name__ == ‘__main__‘:
    main()

calRPN.py

symbol_priority = {}
symbol_priority[0] = [‘#‘]
symbol_priority[1] = [‘(‘]
symbol_priority[2] = [‘+‘, ‘-‘]
symbol_priority[4] = [‘)‘]

def comparePriority(symbol, RPN_stack, symbol_stack):
    ‘‘‘Compare priority between two symbols‘‘‘

    global symbol_priority
    if len(symbol_stack) > 0:
        symbol_pop = symbol_stack.pop()
    else:
        return

    for list in symbol_priority.values():
        if (symbol in list) and (symbol_pop in list):
            ‘‘‘same priority‘‘‘
            symbol_stack.append(symbol_pop)
            symbol_stack.append(symbol)
            return
        elif symbol in list:
            ‘‘‘symbol is smaller‘‘‘
            RPN_stack.append(symbol_pop)
            #recusion call
            comparePriority(symbol, RPN_stack, symbol_stack)
            return
        elif symbol_pop in list:
            ‘‘‘symbol is bigger‘‘‘
            symbol_stack.append(symbol_pop)
            symbol_stack.append(symbol)
            return
        else:
            continue

        symbol_stack.append(symbol_pop)
        return

def scanEveryone(input_string, RPN_stack, symbol_stack):
    for ch in input_string:
        if ch.isdigit():
            RPN_stack.append(ch)
        else:
            if len(symbol_stack) > 0:
                if ch == ‘(‘:
                    symbol_stack.append(ch)
                elif ch == ‘)‘:
                    while True:
                        symbol_pop = symbol_stack.pop()
                        if symbol_pop == ‘(‘:
                            break
                        else:
                            RPN_stack.append(symbol_pop)
                else:
                    comparePriority(ch, RPN_stack, symbol_stack)
            else:
                symbol_stack.append(ch)

def scanInput(RPN_stack, symbol_stack):
    input_string = raw_input()
    input_string += ‘#‘
    scanEveryone(input_string, RPN_stack, symbol_stack)

def calRPN(RPN_stack):
    value_stack = []
    RPN_stack.append(‘#‘)

    for value in RPN_stack:
        if value == ‘#‘:
            return value_stack.pop()
            break
        if value.isdigit():
            value_stack.append(value)
        else:
            right_value = value_stack.pop()
            left_value = value_stack.pop()
            cal_string = left_value + value + right_value
            value_stack.append(str(eval(cal_string)))

def main():
    RPN_stack = []
    symbol_stack = []

    scanInput(RPN_stack, symbol_stack)
    print calRPN(RPN_stack)

if __name__ == ‘__main__‘:
    main()

原文地址:https://blog.51cto.com/14317453/2428259

时间: 2024-11-03 16:17:19

python实现逆波兰计算表达式的代码的相关文章

栈应用——逆波兰式表达式的值

问题描述: 计算给定的逆波兰表达式(即后缀表达式)的值. 事实上,二元运算的前提下,中缀表达式可以对应一棵二叉树:逆波兰式即该二叉树后序遍历的结果. 分析思路: 如果当前是操作数,则直接入栈: 如果当前是操作符,则栈顶的两个元素弹出,然后与当前操作符运算后入栈. Code: /** * 给出一个逆波兰式,计算该表达式的值 * @param s * @return */ public int getTheValueOfRPN(String s) { char[] ch = s.toCharArra

js实现 - 逆波兰式

没有任何方法,除非你才华横溢. --艾略特 js实现 - 逆波兰式 2019-05-26 by 文科生 最近编译原理实验有涉及到逆波兰式,而且听闻有人在前端面试过程中被问到逆波兰式算法的实现,之前的离散数学课程中也有涉及到逆波兰式,作为一名前端人员,终于按耐不住想用js去实现求逆波兰式的算法.我查阅了大量的资料,发现有的算法虽然基本实现了对应的功能,但在细节处理方面略显不妥:而有的算法写的过于庞杂,想要完全读懂则代价昂贵,而且代码的臃肿不是因为算法本身复杂,而是加入了一些算符,这对理解算法本质是

12.7.3 使用计算表达式进行重构

在前一章,我们讨论过重构函数式程序的方法,最后一个主题是延迟性,它变改代码的执行方式,而不影响程序的结果.从某种意义上讲,添加延迟性也可看作是一种重构技术:计算表达式的类似之处在于,增加额外的代码,但不改变核心意思. 提示 在计算表达式和延迟性之间有密切的关系,使用 Lazy<'T> 计算类型,创建能够把代码转换成延迟计算的计算表达式,是有可能的.我们可以尝试实现自定义的计算,唯一的难度在于写 Bind 成员.在这里,我们不进行讨论,在本书的网站上可以找到其他的信息. 重要性在于,把标准的 F

[Leetcode] 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", "*"] -> (

逆波兰式(后缀表达式)的计算

输入 :后缀表达式(可带浮点数) 输出:double型的计算结果 代码: #include <stdio.h> #include <stdlib.h> #include <malloc.h> #define ElemType double #define Stack_Init_Size 100 #define Increase_Size 10 #define MaxBuffer 10 typedef struct sqStack { ElemType *top; Ele

栈的操作实现逆波兰表达式的计算

代码如下: #include <stdio.h> #include <stdlib.h> #include <ctype.h> #define STACK_INIT_SIZE 20 #define STACKINCREMENT 10 #define MAXBUFFER 10 typedef double ElemType; typedef struct { ElemType *base; ElemType *top; int StackSize; }sqStack; v

C++实现 逆波兰表达式计算问题

C++实现 逆波兰表达式计算问题 #include <iostream> #include <string> using namespace std; class Stack { private: int size; int top; float *listArray; public: Stack(int sz=20); ~Stack(); bool push(float it);//入栈 bool pop(float& it);//出栈 bool isEmpty();//

续前篇-关于逆波兰表达式的计算

相对于逆波兰表达式的转换,逆波兰表达的计算可谓简单不少. 具体计算方法参考:http://www.cnblogs.com/vpoet/p/4659546.html 这里也大致梳理一下: 1.新建一个栈将逆波兰表达式的数字依次压入栈中 2.当遇到运算符时,出栈两个数同时将运算结果压栈 3.重复步骤2直到计算计算,栈中的元素即为逆波兰表达式的计算结果. 实现如下: 1 #include <iostream> 2 #include <stack> 3 using namespace st

【LeetCode刷题Java版】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", "*"] -&g