A friendly Guide for writing Recursive Functions with Python | by Eugenia Anello | Towards Data Science

At first, recursion can seem impossible to learn if it is explained very badly. I still remember how I found it challenging the first time I have met it. To understand it deeply, I needed to do many exercises.
It was hard since my mind instinctively solved the problems using iterations, like for loop and while. But with some effort, I was able to understand the basics of recursive function while doing many exercises.
In this post, I want to introduce you to what recursion is and show examples of recursive functions with illustrations, that can surely help in understanding the topic in a more efficient way.
As you can intuit from the word “recursive”, a function is recursive when it recalls itself. So, the same function is called one or more times. Before writing any recursive function, you need to take into account two cases:
Base Case is the most simple case that needs to be considered when solving a problem. It also leads to the end of the recursion.Recursive Case includes the general solution to solve the problem, using the recursive function.
Base Case is the most simple case that needs to be considered when solving a problem. It also leads to the end of the recursion.
Recursive Case includes the general solution to solve the problem, using the recursive function.
For example, let’s try to calculate the factorial of a positive number:
In this case, we can identify the two different cases:
Base Case: if the number is equal to 0 or 1, the function returns 1
Recursive Case: We consider the remaining cases, where the number is greater than 1.
For example, when we calculate 3!, there are some steps to solve this simple problem:
call fact(3)fact(3) returns 3*fact(2) , where the new function to call is fact(2)fact(2) returns 2*fact(1) , where the new function to call is fact(1)fact(1) returns 1the problem is solved from step 4 back to the first step
call fact(3)
fact(3) returns 3*fact(2) , where the new function to call is fact(2)
fact(2) returns 2*fact(1) , where the new function to call is fact(1)
fact(1) returns 1
the problem is solved from step 4 back to the first step
Let’s try the other three examples to understand if you really understood how the recursive function works.
Write a recursive function that returns True if and only if the number is even
Write a recursive function that returns True if and only if the number is even
We need to identify again the two cases:
Base Case: if the number is equal to 0, the number is even
Recursive Case: We consider all the cases, except for n=0. For example, when n=4.
2. Write a recursive function that sums the elements of a list, which needs to have at least one element
The two distinct cases are:
Base Case: if there is only one element in the list, the function returns the first element of the list
Recursive Case: in the remaining cases, we use the recursive function. Each time, the first of the list is removed.
The recursive call can be explained by showing the following steps:
sum_list([1,2,3,4])        #1st call with [1,2,3,4] 1 + sum_list([2,3,4])      #2nd call with [2,3,4]1 + 2 + sum_list([3,4])    #3rd call with [3,4]1 + 2 + 3 + sum_list([4])  #4th call with [4]1 + 2 + 3 + 4              #return from 4th call with                            sum_list([4])=41 + 2 + 7                  #return from 3rd call 1 + 9                      #return from 2nd call 10                         #return from 1st call
3. Given a list (with at least one element), write a recursive function that returns only the even elements
This time, we can find that:
Base Case: if there is only one element, we return the list if the element is even, otherwise we return [].
Recursive Case: in the remaining case, the recursive function is applied. As before, we remove an element from the list each time in the recursive function.
Again, we can show that the recursive call is split into different steps:
even_elements([0,1,2,3])       #1st call with [0,1,2,3][0]+even_elements([1,2,3])     #2nd call with [1,2,3] [0]+[]+even_elements([2,3])    #3rd call with [2,3][0]+[]+[2]+even_elements([3])  #4th call with [3][0]+[]+[2]+[]                  #return from 4th call with                                even_elements([3])=[][0]+[]+[2]                     #return from 3rd call[0]+[2]                        #return from 2nd call[0,2]                          #return from 1st call   
This overview of the recursive functions is finally ended. Now, you should have a better idea of what recursion is and how to write a recursive function. It can provide some advantages. First, recursion splits a complex task into simplex sub-tasks. Moreover, it’s suitable to deal with Python data structures, like stacks, queues and linked lists. But you should also know that this type of solution is not convenient for every problem. Each recursive call waits for a subsequent recursive call and, then, it can take more times sometimes of the iteration. You should compare the time with iteration and the time with the recursive function to be sure. Anyway, there are well-known applications of recursive functions in the data science field, such as recurrent neural networks, decision trees, random trees and isolation trees, where the recursion is essential to make them work. I hope you found useful this tutorial. Thanks for reading. Have a nice day!
Did you appreciate the article? Become a member and get unlimited access to new data science posts every day!