博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python-中缀表达式转前缀表达式
阅读量:4451 次
发布时间:2019-06-07

本文共 2947 字,大约阅读时间需要 9 分钟。

作完了中缀前缀,作一个归纳吧。

https://www.cnblogs.com/unixfy/p/3344550.html

 

# coding = utf-8class Stack:    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_prefix(infix_expr):    prec = dict()    prec[")"] = 4    prec["*"] = 3    prec["/"] = 3    prec["+"] = 2    prec["-"] = 2    prec["("] = 1    prefix_expr = []    s = Stack()    # 从右到左扫描    for item in reversed(infix_expr.split()):        # 如果标记是操作数,将其附加到输出列表的末尾        if item not in prec.keys():            prefix_expr.append(item)        # 如果标记是右括号,将其压到 s 上        elif item == ')':            s.push(item)        # 如果标记是左括号,则弹出 s,直到删除相应的右括号。将每个运算符附加到        # 输出列表的末尾        elif item == '(':            while s.peek() != ')':                prefix_expr.append(s.pop())            s.pop()        # 如果标记是运算符, *,/,+  或  -  ,将其压入 s。但是,首先删除已经在        # s 中具有更高或相等优先级的任何运算符,并将它们加到输出列表中        else:            while (not s.is_empty())\                    and s.peek() != ')'\                    and prec[s.peek()] > prec[item]:                prefix_expr.append(s.pop())                s.push(item)            s.push(item)        print(s.items)    # 当输入表达式被完全处理时,检查 s。仍然在栈上的任何运算符都可以删除并加到    # 输出列表的末尾    while not s.is_empty():        prefix_expr.append(s.pop())    # 反转序列    prefix_expr.reverse()    return ' '.join(prefix_expr)def prefix_eval(prefix_expr):    s = Stack()    for item in reversed(prefix_expr.split()):        # 如果不是运算符号,压栈        if item not in '+-*/':            s.push(item)        else:        # 和后缀相反顺序             op1 = int(s.pop())            op2 = int(s.pop())            print(op1, item, op2)            result = do_match(item, op1, op2)            s.push(result)        print(s.items)    return result# 运行结果def do_match(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 Exception('Error operation!')infix_str = '1 + ( ( 2 + 3 ) * 4 ) - 5'prefix_output = infix_to_prefix(infix_str)print(infix_str)print(prefix_output)prefix_result = prefix_eval(prefix_output)print(prefix_result)

  

输出:

C:\Users\Sahara\.virtualenvs\untitled\Scripts\python.exe D:/test/python_stack.py[]['-']['-', ')']['-', ')']['-', ')', '*']['-', ')', '*', ')']['-', ')', '*', ')']['-', ')', '*', ')', '+']['-', ')', '*', ')', '+']['-', ')', '*']['-']['-', '+']['-', '+']1 + ( ( 2 + 3 ) * 4 ) - 5- + 1 * + 2 3 4 5['5']['5', '4']['5', '4', '3']['5', '4', '3', '2']2 + 3['5', '4', 5]5 * 4['5', 20]['5', 20, '1']1 + 20['5', 21]21 - 5[16]16Process finished with exit code 0

  

转载于:https://www.cnblogs.com/aguncn/p/10656983.html

你可能感兴趣的文章
魅蓝Note有几种颜色 魅蓝Note哪个颜色好看
查看>>
使用PullToRefresh实现下拉刷新和上拉加载
查看>>
透明度百分比与十六进制转换
查看>>
HBase表预分区
查看>>
arcgis desktop 10.1 license manager无法启动问题解决
查看>>
django select_related() 联表查询
查看>>
mysql 常用,使用经验
查看>>
NSBundle,UIImage,UIButton的使用
查看>>
vue-cli3 中console.log报错
查看>>
GridView 中Item项居中显示
查看>>
UML类图五种关系与代码的对应关系
查看>>
如何理解作用域
查看>>
从无到满意offer,你需要知道的那些事
查看>>
P1516 青蛙的约会 洛谷
查看>>
SDOI2011 染色
查看>>
HTTP协议详解
查看>>
JQuery EasyUI combobox动态添加option
查看>>
面向连接的TCP概述
查看>>
前端快捷方式 [记录]
查看>>
亲测可用,解决端口被占用的指令!!
查看>>