Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 853
Omar Saad Avatar asked Mar 16 '15 09:03

Omar Saad


2 Answers

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.

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

like image 58
Daniel Roseman Avatar answered Oct 05 '22 04:10

Daniel Roseman


Yes, as @Daniel Roseman said, this is a fundamental programming technique called recursion.

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

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

like image 39
Jameel Grand Avatar answered Oct 05 '22 03:10

Jameel Grand