zoukankan      html  css  js  c++  java
  • problem-solving-with-algorithms-and-data-structure-usingpython(使用python解决算法和数据结构) -- 基本数据结构(二)

    中缀、前缀和后缀表达式

      1. 前缀表达式符号要求所有运算符在它们处理的两个操作数之前。

      2. 后缀表达式要求其操作符在相应的操作数之后。

    考虑表达式 A + B * C , A B C * + 是等价的后缀表达式。操作数 A,B 和 C 保持在它们的相对位置,只有操作符改变位置。
    
    原始表达式中的运算符的顺序在生成的后缀表达式中相反。由于这种顺序的反转,考虑使用栈来保存运算符

    当我们处理表达式时,操作符必须保存在某处,因为它们相应的右操作数还没有看到。

    from pythonds.basic.stack import Stack
    
    def infixToPostfix(infixexpr):
        prec = {}
        prec['*'] = 3       # 定义运算符的优先顺序
        prec['/'] = 3
        prec['+'] = 2
        prec['-'] = 2
        prec['('] = 1
        opStack = Stack()   # 创建一个空栈
        postfixList = []
        tokenList = infixexpr.split()
    
        for token in tokenList:
            if token in 'ABCDEFGHIJKLMNOPQISTUVWXYZ' or token in '0123456789':
                postfixList.append(token)
            elif token == '(':
                opStack.push(token)
            elif token == ')':
                topToken = opStack.pop()
                while topToken != '(':
                    postfixList.append(topToken)
                    topToken = opStack.pop()
            else:
                while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]):
                    postfixList.append(opStack.pop())
                opStack.push(token)
        while not opStack.isEmpty():
                postfixList.append(opStack.pop())
        return ''.join(postfixList)
    
    print(infixToPostfix("A * B + C * D"))
    print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )"))
    中缀转换成后缀
    from pythonds.basic.stack import Stack
    
    def postfixEval(postfixExpr):
        operandStack = Stack()
        tokenList = postfixExpr.split()
    
        for token in tokenList:
            if token in '0123456789':
                operandStack.push(int(token))
            else:
                operand2 = operandStack.pop()
                operand1 = operandStack.pop()
                result = doMath(token, operand1, operand2)
                operandStack.push(result)
        return operandStack.pop()
    
    def doMath(op, op1, op2):
        if op == '*':
            return op1 * op2
        if op == '/':
            return op1 / op2
        if op == '+':
            return op1 + op2
        if op == '-':
            return op1 - op2
    
    print(postfixEval('7 8 + 3 2 + /'))
    计算后缀表达式的结果

     

  • 相关阅读:
    漫谈设计模式(三):桥接(Bridge)模式 —— 将类功能、结构两层次分离
    深入理解spring中的AOP原理 —— 实现MethodInterceptor接口,自已动手写一个AOP
    Python面向对象之什么是类(1)
    Python常用模块之logging模块
    Python常用模块之xml模块
    Python常用模块之hashlib
    linux基础命令(一)
    DateTime字段控件值显示短格式的做法
    .net中除去IList中的多余项
    jquery点击按钮显示和隐藏DIv
  • 原文地址:https://www.cnblogs.com/lpgit/p/9461525.html
Copyright © 2011-2022 走看看