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

     

  • 相关阅读:
    sql连接查询中的分类
    HTML之页面镶嵌体验
    JavaScript之搜索框
    (转)Android之常用功能方法大集合
    JAVA之执行cmd命令
    Html之网页分屏浏览
    Javascript之三种按钮点击事件
    用JavaScript做一个小小设计
    JavaBean之简单应用JSP页面
    计算器
  • 原文地址:https://www.cnblogs.com/lpgit/p/9461525.html
Copyright © 2011-2022 走看看