简体   繁体   English

解析括号

[英]Parsing a parenthesis

I'm trying to make a calculator in Python 3 (just to learn). 我正在尝试用Python 3制作一个计算器(仅供学习)。 I want to be able to evaluate (just as an example) "5 * ( 2 + 1 )^2" from an input(). 我希望能够从input()评估(仅作为示例)“ 5 *(2 + 1)^ 2”。 I would like to be able to detect if parenthesis are closed or contain another set of parenthesis. 我希望能够检测括号是否已关闭或包含另一组括号。 I also need to be able to isolate the information within so I can evaluate it in the proper order. 我还需要能够隔离其中的信息,以便可以按正确的顺序对其进行评估。

I realize that this could be a significant chunk of code, so if you could point me in the right direction I would be very grateful. 我意识到这可能是一大段代码,因此,如果您能指出正确的方向,我将不胜感激。 I'm looking for links to documentation, function names, and any hints you could provide to help me. 我正在寻找指向文档,函数名称以及您可以提供的任何提示的链接。

A stack based calculator is what you are looking for ! 您正在寻找基于堆栈的计算器!

http://en.wikipedia.org/wiki/Reverse_Polish_notation http://en.wikipedia.org/wiki/Reverse_Polish_notation

This is a classic stack data structure practice problem. 这是经典的堆栈数据结构实践问题。 There are two approaches you can use, one being converting from infix to post/prefix notation which is considerably easier to process but still require the additional step of converting, or you can go and directly evaluate the expression. 您可以使用两种方法,一种是从中缀转换为后缀/前缀表示法,这虽然很容易处理,但仍然需要额外的转换步骤,或者您可以直接对表达式求值。

Here is a good starting point on the subject, a basic implementation of a stack and some more in-depth information about your subject. 是该主题的一个很好的起点,是堆栈的基本实现以及有关该主题的一些更深入的信息。 Starting from there, you should easily find your way, otherwise give me a comment and I'll try to help you out. 从这里开始,您应该轻松找到自己的出路,否则请给我评论,我将尽力帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM