简体   繁体   English

python - 从自身内部调用函数

[英]python - calling a function from within itself

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.是的,这是一种称为recursion的基本编程技术,它经常用于您描述的那种解析场景。

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.只要确保你有一个基本情况,这样递归就会在你到达底层时结束,并且你不会无限地调用自己。

(Also note the easter egg when you Google recursion: "Did you mean recursion?") (还要注意谷歌递归时的复活节彩蛋:“你的意思是递归吗?”)

Yes, as @Daniel Roseman said, this is a fundamental programming technique called recursion.是的,正如@Daniel Roseman 所说,这是一种称为递归的基本编程技术。

Recursion should be used instead of iteration when you want to produce a cleaner solution compared to an iterative version.与迭代版本相比,当您想要生成更清晰的解决方案时,应使用递归而不是迭代。 However, recursion is generally more expensive than iteration because it requires winding, or pushing new stack frames onto the call stack each time a recursive function is invoked -- these operations take up time and stack space, which can lead to an error called stack overflow if the stack frames consume all of the memory allocated for the call stack.然而,递归通常比迭代更昂贵,因为它需要在每次调用递归函数时进行缠绕或将新的堆栈帧推送到调用堆栈上——这些操作会占用时间和堆栈空间,这会导致称为堆栈溢出的错误如果堆栈帧消耗了为调用堆栈分配的所有内存。

Here is an example of it in Python这是 Python 中的一个示例

def recur_factorial(n):
   """Function to return the factorial of a number using recursion""" 
   if n == 1:
      return n
   else:
      return n*recur_factorial(n-1) 

For more detail, visit the github gist that was used for this answer 有关更多详细信息,请访问用于此答案的 github gist

是的,在“python递归”中是可能的,最好的描述是:“一个物理世界的例子是将两个平行的镜子相互面对。它们之间的任何物体都会被递归反射”

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

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