且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

利用stack结构,将中缀表达式转换为后缀表达式并求值的算法实现

更新时间:2022-08-16 17:16:23

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# learn <<Problem Solving with Algorithms and Data Structures>>
# Release 3.0
# chengang882 @ 2016-12-20
# 它可以将常见的中缀表达式转换成后缀表达式,并计算这个表达示的值
# Completed implementation of a stack ADT


#数据结构
class Stack(object):
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

# 实现中缀表达式转换为后缀表达式
def infix_to_postfix(infix_expr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1

    op_stack = Stack()
    postfix_list = []
    # 一定要有空格切割,显得不完美
    token_list = infix_expr.split()

    for token in token_list:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfix_list.append(token)
        elif token == "(":
            op_stack.push(token)
        elif token == ")":
            top_token = op_stack.pop()
            while top_token != "(":
                postfix_list.append(top_token)
                top_token = op_stack.pop()
        else:
            while (not op_stack.is_empty()) and \
                  (prec[op_stack.peek()] >= prec[token]):
                postfix_list.append(op_stack.pop())
            op_stack.push(token)
    while not op_stack.is_empty():
        postfix_list.append(op_stack.pop())
    print(" ".join(postfix_list))
    return " ".join(postfix_list)


# 计算后缀表达式的值
def postfix_eval(postfix_expr):
    operand_stack = Stack()
    token_list = postfix_expr.split()

    for token in token_list:
        if token in "0123456789":
            operand_stack.push(int(token))
        else:
            operand2 = operand_stack.pop()
            operand1 = operand_stack.pop()
            # 还是将后缀换成中缀再计算
            result = do_math(token, operand1, operand2)
            operand_stack.push(result)
    return operand_stack.pop()


def do_math(op, op1, op2):
    if op == "*":
        return op1 * op2
    elif op == "/":
        return op1 / op2
    elif op == "+":
        return op1 + op2
    elif op == "-":
        return op1 - op2
    else:
        raise("ERROR")
    
if __name__ == "__main__":
    print(postfix_eval(infix_to_postfix("5 * 8 + 2 * 3")))
    infix_to_postfix("( A + B ) * C - ( D - E ) * ( F + G )")
    print(postfix_eval('7 8 + 3 2 + /'))

 输出:

>>> 
5 8 * 2 3 * +
46
A B + C * D E - F G + * -
3
>>>