前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >实现栈的表达式的转化

实现栈的表达式的转化

作者头像
算法与编程之美
发布2023-08-22 14:26:36
1190
发布2023-08-22 14:26:36
举报
文章被收录于专栏:算法与编程之美

1 问题

利用python实现栈的中缀表达式和后缀表达式的转变,可以解决简单的数学问题。

2 方法

使用def定义函数和类函数,循环函数等和一些基本的逻辑思维可以解决该问题。

代码清单 1

from stack_set import Stackdef infixToPostfix(infixpr): pre={} pre['*'],pre['/']=3,3 pre['+'],pre['-']=2,2 pre['(']=1 charlist=[chr(i) for i in range(65,91)] numlist=[i for i in range(10)] opstack=Stack() postfixlist=[] items=infixpr.split() for item in items: if item in charlist or item in numlist: postfixlist.append(item) elif item=="(": opstack.push(item) elif item==')': tokentop=opstack.pop() while tokentop!="(": postfixlist.append(tokentop) tokentop=opstack.pop() else: while(not opstack.isEmpty()) and (pre[item]<=pre[opstack.peek()]): postfixlist.append(opstack.pop()) opstack.push(item) print("stack:{},postlist:{}".format(opstack.items,postfixlist)) while not opstack.isEmpty(): postfixlist.append(opstack.pop()) return "".join(postfixlist)if __name__ == '__main__': infix="A + ( B * C )" postfix=infixToPostfix(infix) print("其对应的后缀表达式:{}".format(postfix))

3 结语

针对利用python来解决数学问题,提出循环定义等方法,通过实践,证明该方法是有效的。此方法结合并熟练的运用所学的简单知识和简单的逻辑关系,当然方法还有不足或考虑不周的地方,还有待继续研究。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-07-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 算法与编程之美 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档