python-中缀表达式转前缀表达式
作完了中缀前缀,作一个归纳吧。
https://www.cnblogs.com/unixfy/p/3344550.html
# coding = utf-8 class 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] 16 Process finished with exit code 0
python-中缀表达式转前缀表达式的更多相关文章
- 中缀表达式转换为后缀表达式(python实现)
中缀表示式转换为后缀表达式 需要一个存放操作符的栈op_stack,输出结果的列表output 步骤: 从左到右遍历表达式: 1. 若是数字,直接加入到output 2. 若是操作符,比较该操作符和o ...
- 第四次程序设计作业 C++计算器计算及命令行的使用 前缀表达式方法实现
关键词:前缀中缀后缀表达式 波兰式 命令行 myGithub 一.前言 很有意思的开发和学习经历,从刚刚开始看到作业思考半天到现在的Debug过程,对我来说都或多或少有所提升. 也许这个时候自己挺迷茫 ...
- Java堆栈的应用2----------中缀表达式转为后缀表达式的计算Java实现
1.堆栈-Stack 堆栈(也简称作栈)是一种特殊的线性表,堆栈的数据元素以及数据元素间的逻辑关系和线性表完全相同,其差别是线性表允许在任意位置进行插入和删除操作,而堆栈只允许在固定一端进行插入和删除 ...
- 中缀表达式得到后缀表达式(c++、python实现)
将中缀表达式转换为后缀表达式的算法思想如下: 从左往右开始扫描中缀表达式 遇到数字加入到后缀表达式 遇到运算符时: 1.若为‘(’,入栈 2.若为’)‘,把栈中的运算符依次加入后缀表达式,直到出现'( ...
- ZH奶酪:Python 中缀表达式转换后缀表达式
实现一个可以处理加减乘数运算的中缀表达式转换后缀表达式的程序: 一个输入中缀表达式inOrder 一个输出池pool 一个缓存栈stack 从前至后逐字读取inOrder 首先看一下不包含括号的: ( ...
- 中缀表达式转后缀表达式(Python实现)
中缀表达式转后缀表达式 中缀表达式转后缀表达式的规则: 1.遇到操作数,直接输出: 2.栈为空时,遇到运算符,入栈: 3.遇到左括号,将其入栈: 4.遇到右括号,执行出栈操作,并将出栈的元素输出,直到 ...
- Python与数据结构[1] -> 栈/Stack[1] -> 中缀表达式与后缀表达式的转换和计算
中缀表达式与后缀表达式的转换和计算 目录 中缀表达式转换为后缀表达式 后缀表达式的计算 1 中缀表达式转换为后缀表达式 中缀表达式转换为后缀表达式的实现方式为: 依次获取中缀表达式的元素, 若元素为操 ...
- 利用stack结构,将中缀表达式转换为后缀表达式并求值的算法实现
#!/usr/bin/env python # -*- coding: utf-8 -*- # learn <<Problem Solving with Algorithms and Da ...
- javascript使用栈结构将中缀表达式转换为后缀表达式并计算值
1.概念 你可能听说过表达式,a+b,a+b*c这些,但是前缀表达式,前缀记法,中缀表达式,波兰式,后缀表达式,后缀记法,逆波兰式这些都是也是表达式. a+b,a+b*c这些看上去比较正常的是中缀表达 ...
随机推荐
- QML 从入门到放弃
发现了一个问题: QQuickView only supports loading of root objects that derive from QQuickItem. If your examp ...
- C++ 11 snippets , 1
1->创建7个Thread,跑个非常大的循环.观察CPU void func(string &name) { ;i<0xFFFFFFFF;i++) { //cout << ...
- BIM开发引挈
BIM开发引挈: 0.three.js https://threejs.org/ 1. 陕西葛兰岱尔网络科技有限公司 www.glendale.com.cn 基于WebGL BIM轻 ...
- 查看局域网中连接的主机名和对应的IP地址
1.查看局域网中的所有主机名 2.通过主机名解析IP地址:-4选项 3.通过IP地址解析主机名:-a选项
- VIsual Studio编译OpenCV:无法打开python27_d.lib(python36_d.lib)的问题
原文地址:http://blog.csdn.net/Chris_zhangrx/article/details/78947526 在用 VS2015 编译 Debug 版的 openCV 源码时,最后 ...
- URLConnection和HttpURLConnection
URLConnection和HttpURLConnection使用的都是java.net中的类,属于标准的java接口. HttpURLConnection继承自URLConnection,差别在与H ...
- 003_crlf注入漏洞
一. (1) 线上收到一个crlf 注入的漏洞. 同时启用80和443才会暴露,配置如下: server { listen 80; listen 443 ssl; server_name www.jy ...
- node.js总结
1.NPM安装报错:no such file or directory, open 'C:\Users\HP\package.json' npm WARN saveError ENOENT: no s ...
- 【原创】Linux基础之chkconfig systemd
CentOS6服务用chkconfig控制,CentOS7改为systemd控制 1 systemd systemd is a suite of basic building blocks for a ...
- cocos2dx-lua 延迟调用函数和定时器
下面是cocos官方的方法. function performWithDelay(node, callback, delay) local delay = cc.DelayTime:create(de ...