
Recursions is one of the most interesting topics I've learned in computer science so far. The topic is so fascinating and somewhat confusing to follow. The concept of a function calling itself is really amazing.Recursions depth can go infinitely deep, yet the code is a finite statement.
What exactly is recursion?
Well this is an example of recursion function.
def sum_list(L):
’’’ (list or int) -> int
Return L if it’s an int, or sum of the numbers in possibly nested list L
>>> sum_list(17)
17
>>> sum_list([1, 2, 3])
6
>>> sum_list([1, [2, 3, [4]], 5])
15
’’’
# reuse: isinstance, sum, sum_list !
if isinstance(L, list):
return sum([sum_list(x) for x in L])
else: # L is an int
return L
Basically if the item is an int, it will return the int number. If the item is a list, the function calls itself to check if there is nested lists or if there are more int within the list. Recursion helps the problem of determining how many nested lists are within the list. Recursion keeps calling the function as many times as the depth of the list. This can go on infinitely deep.
How would you trace the lists or int?
Take the example sum_list([1, [2, 3, [4]], 5]). Since L is a list, it will call the function sum_list again, and it will take the sum for every int in that list. Then, it will further check for nested lists within the list until it finds the last nested list in the list. Then, the all the int will be added up to the sum of 15. Keeping track and tracing recursions can be a little tricky and confusing at first. However, with more practice, you will be able to get the hang of it and trace recursive functions of higher complexity.