数学表达式评估 [英] Math Expression Evaluation

查看:99
本文介绍了数学表达式评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现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!

这篇关于数学表达式评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆