数学表达式评估

编程入门 行业动态 更新时间:2024-10-18 12:22:19
本文介绍了数学表达式评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

实现python程序的最佳方法是什么,该程序将采用字符串并根据运算符优先级输出其结果(例如:"4 + 3 * 5"将输出19).我已经搜寻了解决此问题的方法,但是它们都太复杂了,我正在寻找一种(相对)简单的方法.

What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.

说明:我需要比eval()更高级的东西-我希望能够添加其他运算符(例如,最大运算符-4 $ 2 = 4),或者,我对此在学术上比对专业更感兴趣-我想知道如何做到这一点.

clarification: I need something slightly more advanced than eval() - I want to be able to add other operators (for example a maximum operator - 4$2 = 4) or, also I am more interested in this academically than professionaly - I want to know how to do this.

推荐答案

如果您对学术感兴趣",则想了解如何编写具有运算符优先级的解析器.

If you're "academically interested", you want to learn about how to write a parser with operator precedence.

使用Python进行简单的自上而下解析是一篇不错的文章,构建一个示例解析器来精确执行您想做的事情:评估数学表达式.

Simple Top-Down Parsing in Python is a nice article that builds an example parser to do exactly what you want to do: Evaluate mathematical expressions.

我强烈建议您尝试编写自己的第一个解析器-这就是那些啊,那是工作原理"的时刻之一!

I can highly recommend having a go at writing your own first parser -- it's one of those "ah, that's how that works" moments!

更多推荐

数学表达式评估

本文发布于:2023-11-10 16:16:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575859.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   数学

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!