python-从自身内部调用函数 [英] python - calling a function from within itself

查看:87
本文介绍了python-从自身内部调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经拥有的代码适用于接收数学表达式并对其进行计算的机器人.现在,我要进行乘法,除法,减法和加法运算.问题是我想建立对括号和括号内括号的支持.为此,我需要先为括号内的表达式运行不带括号的表达式代码.我要检查(" ,并将其中的表达式附加到列表中,直到到达)" ,除非它到达另一个(" ,在这种情况下,我先在列表中创建一个列表,然后将它们相减,相乘和相除,然后将剩下的数字加在一起.

The code I already have is for a bot that receives a mathematical expression and calculates it. Right now I have it doing multiply, divide, subtract and add. The problem though is I want to build support for parentheses and parentheses inside parentheses. For that to happen, I need to run the code I wrote for the expressions without parentheses for the expression inside the parentheses first. I was going to check for "(" and append the expression inside it to a list until it reaches a ")" unless it reaches another "(" first in which case I would create a list inside a list. I would subtract, multiply and divide and then the numbers that are left I just add together.

那么可以从自身内部调用定义/函数吗?

So is it possible to call a definition/function from within itself?

推荐答案

是的,这是一种称为递归,通常用于您描述的那种解析方案中.

Yes, this is a fundamental programming technique called recursion, and it is often used in exactly the kind of parsing scenarios you describe.

请确保您有一个基本情况,以便递归到达底端时就结束了,并且您不会最终无限地称呼自己.

Just be sure you have a base case, so that the recursion ends when you reach the bottom layer and you don't end up calling yourself infinitely.

(还要注意Google递归时的复活节彩蛋:您是说递归吗?")

(Also note the easter egg when you Google recursion: "Did you mean recursion?")

这篇关于python-从自身内部调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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