For the past couple of weeks, Danny has taught us how to use recursion. It has been one of the most useful methods of programming that I have learned so far in this entire course. Recursion can be used in most of my programming code to solve my problems. It's is useful when it comes to Trees, Linked Lists, and re-iterating over certain loops.When given data of nested lists, dictionaries or tuples, recursion allows us to recall the same function to go into the nest of data to grab the information that we need. For example, in week 4 we were given the following code:
def rec_max(L):
"""
Return the maximum number in L, a possibly nested list of numbers.
>>> rec_max([17, 21, 0])
21
>>> rec_max([17, [21, 24], 0])
24
"""
return max( # the maximum of
# list of maximums of sublists or plain numbers in L
[rec_max(x) if isinstance(x, list) else x for x in L])
This code during the lecture allowed us to the find the maximum element within the list of nested lists. Without recursion, it would be difficult to implement the code for this function. With recursion, by recalling the same function and re-iterating over the list every time an item in the main list is a list, we can append each item within the nested lists to one big list. Once we have the one big list of all the items without the nest lists, we can find the maximum element with ease.
Furthermore, by utilizing the recursion method combined with list comprehension, I am now able to write code for complicated functions within one line. Without the combination of these two methods, writing code for my functions would be extremely difficult and long to do. In conclusion, by using recursion, I can recall the same function to preform the same function over a series of data to collect the information that I need with ease. Without recursion, coding things like Trees and Linked Lists would be incredibly difficult.