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

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-中缀表达式转前缀表达式的更多相关文章

  1. 中缀表达式转换为后缀表达式(python实现)

    中缀表示式转换为后缀表达式 需要一个存放操作符的栈op_stack,输出结果的列表output 步骤: 从左到右遍历表达式: 1. 若是数字,直接加入到output 2. 若是操作符,比较该操作符和o ...

  2. 第四次程序设计作业 C++计算器计算及命令行的使用 前缀表达式方法实现

    关键词:前缀中缀后缀表达式 波兰式 命令行 myGithub 一.前言 很有意思的开发和学习经历,从刚刚开始看到作业思考半天到现在的Debug过程,对我来说都或多或少有所提升. 也许这个时候自己挺迷茫 ...

  3. Java堆栈的应用2----------中缀表达式转为后缀表达式的计算Java实现

    1.堆栈-Stack 堆栈(也简称作栈)是一种特殊的线性表,堆栈的数据元素以及数据元素间的逻辑关系和线性表完全相同,其差别是线性表允许在任意位置进行插入和删除操作,而堆栈只允许在固定一端进行插入和删除 ...

  4. 中缀表达式得到后缀表达式(c++、python实现)

    将中缀表达式转换为后缀表达式的算法思想如下: 从左往右开始扫描中缀表达式 遇到数字加入到后缀表达式 遇到运算符时: 1.若为‘(’,入栈 2.若为’)‘,把栈中的运算符依次加入后缀表达式,直到出现'( ...

  5. ZH奶酪:Python 中缀表达式转换后缀表达式

    实现一个可以处理加减乘数运算的中缀表达式转换后缀表达式的程序: 一个输入中缀表达式inOrder 一个输出池pool 一个缓存栈stack 从前至后逐字读取inOrder 首先看一下不包含括号的: ( ...

  6. 中缀表达式转后缀表达式(Python实现)

    中缀表达式转后缀表达式 中缀表达式转后缀表达式的规则: 1.遇到操作数,直接输出: 2.栈为空时,遇到运算符,入栈: 3.遇到左括号,将其入栈: 4.遇到右括号,执行出栈操作,并将出栈的元素输出,直到 ...

  7. Python与数据结构[1] -> 栈/Stack[1] -> 中缀表达式与后缀表达式的转换和计算

    中缀表达式与后缀表达式的转换和计算 目录 中缀表达式转换为后缀表达式 后缀表达式的计算 1 中缀表达式转换为后缀表达式 中缀表达式转换为后缀表达式的实现方式为: 依次获取中缀表达式的元素, 若元素为操 ...

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

    #!/usr/bin/env python # -*- coding: utf-8 -*- # learn <<Problem Solving with Algorithms and Da ...

  9. javascript使用栈结构将中缀表达式转换为后缀表达式并计算值

    1.概念 你可能听说过表达式,a+b,a+b*c这些,但是前缀表达式,前缀记法,中缀表达式,波兰式,后缀表达式,后缀记法,逆波兰式这些都是也是表达式. a+b,a+b*c这些看上去比较正常的是中缀表达 ...

随机推荐

  1. Linux 指定运行时动态库路径【转】

    转自:http://www.cnblogs.com/cute/archive/2011/02/24/1963957.html 众所周知, Linux 动态库的默认搜索路径是 /lib 和 /usr/l ...

  2. strstr()函数的使用

    strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串.如果是,则该函数返回str2在str1中首次出现的地址:否则,返回NULL. 实例: /** *Descriptio ...

  3. openwrt页面显示问题修改

    页面显示错误如下: 在不应该的位置显示了这个,查看配置文件: config igmpproxy        option quickleave '1' config phyint         o ...

  4. zabbix3监控php-fpm的状态

    php-fpm和nginx一样内建了一个状态页,对于想了解php-fpm的状态以及监控php-fpm非常有帮助 . 启用php-fpm状态功能 [root@node1:~]# vim /usr/loc ...

  5. 【算法】二分查找法&大O表示法

    二分查找 基本概念 二分查找是一种算法,其输入是一个有序的元素列表.如果要查找的元素包含在列表中,二分查找返回其位置:否则返回null. 使用二分查找时,每次都排除一半的数字 对于包含n个元素的列表, ...

  6. 前端 ----jQuery的属性操作

    04-jQuery的属性操作   jquery的属性操作模块分为四个部分:html属性操作,dom属性操作,类样式操作和值操作 html属性操作:是对html文档中的属性进行读取,设置和移除操作.比如 ...

  7. 深度解析SpringMvc实现原理手写SpringMvc框架

    http://www.toutiao.com/a6340568603607171329/?tt_from=mobile_qq&utm_campaign=client_share&app ...

  8. input错误提示,点击提交,提示有未填项,屏幕滑到input未填项的位置

    function errorInfo(parm) { //获取文本框值 var $val = parm.val(); if ($val==""||undefined||null){ ...

  9. Hbase理论&&hbase shell&&python操作hbase&&python通过mapreduce操作hbase

    一.Hbase搭建: 二.理论知识介绍: 1Hbase介绍: Hbase是分布式.面向列的开源数据库(其实准确的说是面向列族).HDFS为Hbase提供可靠的底层数据存储服务,MapReduce为Hb ...

  10. tensorflow中文教程

    飞机票--->走你~~~ 飞机票 http://blog.csdn.net/lenbow/article/details/52152766