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 + /'))
    计算后缀表达式的结果

     

  • 相关阅读:
    realsense SDK debug
    网络
    JVM基础系列第11讲:JVM参数之堆栈空间配置
    图片一句话木马简单制作方法
    RocketMQ(四):生产者消息数据写入实现细节
    RocketMQ(三):broker启动逻辑
    发现一个新的技术网站 https://dotnet9.com/
    【最新】解决Github网页上图片显示失败的问题
    c++入门
    Newtonsoft.Json json.net 可以丢弃了,微软发布了 System.Text.Json 适用于.net 4.6.1 +,后悔了,建议.net5+项目使用
  • 原文地址:https://www.cnblogs.com/lpgit/p/9461525.html
Copyright © 2011-2022 走看看