[Solved] Trying to solve recursion in Python


tl;dr; The method defined is recursive, you can call it enough times to force an Exception of type Recursion Error because it adds to the stack every time it calls itself. Doesn’t mean it’s the best approach though.

By definition a recursive function is one that is meant to solve a problem by a finite amount of statements while making that problem smaller each time, until you get to your base cases (which is when you return from that recursiveness). It also implies the function calling itself within the code.

If we crudely put this in a bullet list style, a recursive function can be described by:

  • Base cases, where returns happen in a function
  • Function calls itself and passes the same data, but modified, “smaller”

So far, the code you have pasted does one of these two. It calls itself within the function (although it doesn’t simplify the problem or pass data along). The function doesn’t have base cases to solve the problem with, it has but one case.

The code pasted in the question seems to want to be an iterative forever loop but the way to achieve this has been done through recursive calls:

When you execute the file that contains the provided code, the call outside of the definition will be executed once, but then inside the function, it calls itself again as long as the user doesn’t type quit. While it seems like it’s a fancy forever loop, this can be classified as a recursive method because it’s calling itself inside the function definition. Now, it’s a terrible recursive function, because you don’t need it to be recursive to work as intended. You never return anything, and every time you call the function str_replace_interface() you are adding to the Stack, which if you call it enough times you can cause a RecursionError. Let’s do just that to see it in action. To achieve, I will remove the code that lets the user quit, and also remove the input, so I don’t have to type a million times a word.

def str_replace_interface():   
        str_replace_interface()


str_replace_interface() 

When I executed, as expected I got the following:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    str_replace_interface()
  File "main.py", line 5, in str_replace_interface
    str_replace_interface()
  File "main.py", line 5, in str_replace_interface
    str_replace_interface()
  File "main.py", line 5, in str_replace_interface
    str_replace_interface()
  [Previous line repeated 992 more times]
  File "main.py", line 4, in str_replace_interface
RecursionError: maximum recursion depth exceeded while calling a Python object

Why? Because the function never actually returns anything, that’s why I mentioned that making a forever loop recursively is terrible. You can achieve the same thing iteratively, as follows:

def str_replace_interface():   
        word = input("Enter a word: ")
        if word != 'quit':
            substring = input("Please enter the substring you wish to find: ")
            new_entry = input("Please enter a string to replace the given substring: ")
            new_word = word.replace(substring, new_entry)
            print("Your new string is: " + new_word)
            return True
        return False    

while str_replace_interface():
  pass

Here, the power of the forever loop happens based on the returned value after executing the function. You are not adding to the stack with every call because the function actually returns. Now what happens if we force a continuous call over and over like we did for the recursive one? Well, the answer is nothing. You’ll have a forever loop…well, forever. But you won’t get a Recursive Error because the function executes and returns before calling it again. Give it a try:

def str_replace_interface():   
        return True

while str_replace_interface():
  pass 

See how it doesn’t raise an Exception? it just stays there hanging. You’ll have to forcefully kill the execution to make it stop, but an exception won’t happen.

I hope that helps you clear it up.

2

solved Trying to solve recursion in Python