Train Your Mind to Think Recursively in 5 Steps | by Sara A. Metwalli | Towards Data Science

Along the way on your programming journey, there are a few milestones that you need to conquer to advance ahead. For example, getting comfortable with classes, understanding pointers, master the art of functionalizing your code, and so on. One of the trickest programming concepts to learn for newcomers and master for those who have been programming for a while is recursion.
When I first started to code — almost a decade ago — I struggled a bit in wrapping my head around recursion. While some people can naturally think recursively, others — myself included — can’t.
But,
Thinking recursively is something you can train your brain to do and master, even if you’re not born with this ability.
Back in 2012, I came across a pretty cool book called “Think Like a Programmer.” This book taught me to develop a thinking process that helped me tackle various programming problems throughout the years. It gave me the foundation of the correct thinking process a programmer needs to develop to excel in their career.
Over the years, I expanded on those techniques proposed in the book to get comfortable with various programming concepts.
In this article, I will walk you through the different steps I used to solve any recursive problem. Although I will use Python to demonstrate the steps, these steps can be applied to any programming language. Their logic is not language-specific.
Let’s — let's, let's, let’s — get to it!
To demonstrate the process, let’s take a simple problem. Assume we need to sum up the digits of any given number. For example, the sum of 123 is 6, for 57190 is 22, and so on.
So, I need to write a code that solves this problem for me using recursion. Before you say it, I know there are other ways to solve this problem — that arguably are better and easier to recursion. But, for the sake of this article, let’s consider the recursive solution.
This step is relatively simple for most people. We have a number and want to sum its digits using loops. Basically, we need to know how to count how many digits in the number and then sum them up one by one.
One way to do that is to cast the variable containing the number to str to make it easier to iterate over.
num = 123 #The variable containing the number we want to sum its digitsnum = str(num) #Casting the number to a strs = 0 #Initialize a varible to accumulate the sum#Loop over the digits and add them upfor i in range(len(num)):  s += int(num[i])
Solving the problem using loops will help us understand the answer and figure out all the non-recursive aspects of it. Now that we have the answer, we can dissect it and extract the information we need to move on.
At this point, we need to ask ourselves a question, if I were to write this in a function form, what will the function parameters be?
The answer to this question depends on the programming language you are using. For Python, we can say that we only need one parameter, which is the variable num.
def sumOfDigitsIter(num):    num = str(num)    s = 0    for i in range(len(num)):        s += int(num[i])    return s
Once we get the function parameters, we are going to give them a deeper look. In our case, we only have one parameter that is num.
What we need to do now is find the minimal problem instance based on its parameters. To recall, our purpose was to sum the digits of a given number. The easiest instance of this problem is if the number only has one digit.
For example, if num = 3, then the answer will be equal to the variable itself since there are no more digits to add.
Let’s look again at the function we just wrote:
def sumOfDigitsIter(num):    num = str(num)    s = 0    for i in range(len(num)):        s += int(num[i])    return s
Following this function's logic, if the parameter num is only one digit, the loop will still be executed. To avoid that, we can add a conditional statement that only executes if the number of digits in the input number is one.
def SumOfDigitsIter(num):    num = str(num)    if len(num) == 1:      return num    else:      s = 0      for i in range(len(num)):          s += int(num[i])      return s
This is the step where recursion happens. Up until now, we didn’t care much about recursion; we were solving the problem logically. That’s the best approach to start with recursion, think about it logically, and then convert into a recursive solution.
Now, let’s consider the else section of our function.
else:      s = 0      for i in range(len(num)):          s += int(num[i])      return s
You can think of recursion as unrolling a problem instance and then rolling it again. We can look at this problem from another angle, we can say that the sum of 123 is 1 + the sum of 23, and the sum of 23 is 2 + sum 3 — which is 3.
So, rolling back this becomes the sume of 123 = 1 +2 +3 =6.
Let’s convert that into code. We already have the last part written, which handles one-digit numbers. What we need to do is break the rest of the num variables into one-digit numbers.
That’s recursion.
def SumOfDigits2(num): num = str(num) if len(num) == 1:   return num else:   return num[0] + sumOfDigits(num[1:])
So, every time, I call the same function but with a smaller input. Once I reach the last digit, I will end up with something like 1 + 2 + 3, which will eventually add up to 6.
And, voila, I got myself a recursive function.
Let’s consider another example, say we want to get the sum of the absolute differences between two lists of integers of the same length. For example if we have [15,-4,56,10,-23] and [14,-9,56,14,-23], that answer will be 10.
Step 1: Solve with loops
    assert len(arr1) == len(arr2)    diffSum = 0    for i in range(len(arr1)):        diffSum += abs(arr1[i]-arr2[i])
Step 2: Extract parameters
parameter list = [arr1, arr2].
Step 3: Deduct minimal instance
The minimal instance of this problem is when the two lists are empty; in this case, there’s no difference, so that the answer will be 0.
Step 4: Solve minimal instance.
if len(arr1) == 0:  return 0
Now you might say, why didn’t you make sure that len(arr2) == 0 as well? The assert statement already ensured that both lists have the same length, which means if I want to check if they are empty, I only need to check the length of one of them.
Step 5: Recurse
Like the digits sum example, if I want to sum the absolute difference between two lists, I can get the difference between the first two elements, and then the second and then the third, and so on, until I run out of elements.
def recDiff(arr1,arr2):    assert len(arr1) == len(arr2)    if len(arr1) == 0:        return 0    else:         return abs(arr1[0]-arr2[0]) + recDiff(arr1[1:],arr2[1:])
Recursion is considered one of the advanced techniques that a programmer needs to go through along their journey to becoming a “good programmer.” However, it can be quite tricky to wrap one’s head around initially, and many find it difficult to master.
Following simple, concise five steps, you can tackle any recursion problem with ease:
Solve the problem using loops first.From that, extract the possible inputs if you would turn this into a function.Deduct the simplest version of the problem.Write a function that solves the simplest instance of that problem.Use that function to write a new recursive function.
Solve the problem using loops first.
From that, extract the possible inputs if you would turn this into a function.
Deduct the simplest version of the problem.
Write a function that solves the simplest instance of that problem.
Use that function to write a new recursive function.
Although I proposed 5 steps, you will not need to go through all 5 steps explicitly as you get better with precision. With time and practice, you will be able to perform some of these steps in your mind without explicitly writing them down.
I will leave you with this, recursive is one of the challenging programming concepts to master. So, just stick with it, be patient, and practice a lot; that’s the only way you can truly get the hang of it.