Python逆波兰表达式

1.先创建ExpressClass类

  1. 创建init构造函数
  2. 创建get_post_exp函数,获取后缀表达式
  3. 创建trans函数,中缀表达式转后缀表达式
  4. 创建get_value,获取后缀表达式的值
from SqStack import SqStack


class ExpressClass:
    def __init__(self, str):
        self.exp = str  # 中缀表达式存放位置
        self.post_exp = []  # 后缀表达式存放位置

    def print_info(self):
        return self.exp

    def get_post_exp(self):  # 返回后缀表达式
        return self.post_exp

    def trans(self):  # 中缀转后缀
        opor = SqStack()  # 创建空栈
        i = 0  # 栈下标
        while i < len(self.exp):
            ch = self.exp[i]  # 取出栈元素
            if ch == "(":  # 遇到左括号,入符号栈
                opor.push(ch)
            elif ch == ")":  # 遇到右括号,需要取出符号栈元素,追加到后缀表达式栈中
                while not opor.empty() and opor.get_top():
                    print()
            elif ch == "+" or ch == "-":  # 入符号栈
                # 先取出符号栈的栈顶元素,判断是否是(,如果不是,则把符号栈的符号取出来入后缀表达式栈
                while not opor.empty() and opor.get_top() != "(":
                    e = opor.pop()
                    self.post_exp.append(e)
                
                # 如果符号栈是(,则直接入栈
                opor.push(ch)
            elif ch == "*" or ch == "/":  # 入符号栈
                print()
            else:  # 就是数字,入后缀表达式栈
                d = ""  # 保存数字
                # 判断是否是数字
                while "0" <= ch <= "9":  # 判断是否为数字,如果是,则一直取出所有数字
                    d += ch
                    i += 1
                    if i < len(self.exp):  # 如果当前项为最后一项,因为先加1,则会超出索引,所以要先判断,超出最后一项,则结束所有循环,也就是break
                        ch = self.exp[i]  # 取出当前下标的元素
                    break
                i -= 1  # 循环完毕则退格,减1只适合最大2位数的数字运算
                self.post_exp.append(int(d))  # 后缀表达式入
            i += 1

    def get_value(self):
        print()

文档还在更新中... 

你可能感兴趣的:(笔记,数据结构,Python,python,数据结构)