Lets say, for example, we were supposed to find the sum of all of the elements of a list.
1) [1, 2 ,3] (How would you solve it?)
- By intuition (and probably habit), we would probably use a for loop and accumulate each individual value. If you were able to remember what the python function 'sum' does then you could also use that.
Now lets say your friend comes in and messes with your examples and data (because that's what friends do right?)
2) [[1, 2], [3, 4]] (How about this?)
- Well, why not use nested loops? One for the outer list, and one for the smaller lists? (or again, call 'sum' for the inner lists)
3) [1, [2, 3]] (But what happens with something like this?)
- We can't use the nested loop method so easily with an example like this since we can't iterate over 1. For this to work, we'd need extra code to check if the element in the list is a list or not.
4) [1, [2, [3, 4], 5], 6, [7, 8]] (At this point, you should reconsider who your friends are.)
- With so many lists within lists, and stand-alone numbers, how are you supposed to code this? How many loops will you need?
This is where recursion comes in. Lets break down this list first. What would be the first step in solving this problem?
(Step 1) First, we inspect each element of the outer list to see if it is a list or not.
(Step 2) If an element is not a list, just return it, but if it is a list, we want to go into THAT list to see if there are any more lists or non-lists. If there are even MORE lists in THAT list, then we do it again.
(Step ?) After you stress-fully gone through every single list, you probably want to break those lists to make it easier for you. To do that, why not use function 'sum' to get a number that we can use?
(Step ? + 1) After you broke that list, you're still stuck in a list with no final answer, so, why not call sum on this list then? But hey, I'm still in a list, so, call it again!
(But wait...) Do you see where the 'recursion' of this is now? We're just doing the same thing over and over and over again until we finally get an answer. What you're trying to achieve is:
sum([1, sum([2, sum([3, 4]), 5]), 6, sum([7, 8])]) => sum([1. sum([2, 7, 5]), 6, 15])
=> sum([1, 14, 6, 15]) => 36
I know what you're thinking of right now: "But wait, person who writes this blog, I can just do this with nested loops!" Yes, you could but what if you had no idea what the data looked like or your friend comes back and changes it even more, then you would need to adjust the coding for each situation, and lets be frank, us programmers, we don't want to rewrite code over and over again. It's tiring!
Here is a recursive function that can do everything your nested loops can do:
def total(L):
""" -insert proper docstring here- """
if isinstance(L, list): # if it is a list....
return sum(total(i) for i in L) # call sum on the entire list, while calling total(i) on every
# item in L, then calling total(i) again on any more inner lists
# and so on....
else: # if L is not a list, return the value
return L
This here is a recursive function. As you can see, this function does everything! It checks if elements are lists, and if they are, call sum on them, then do the same for all inner lists. If they aren't, just return the value. If you have any doubts, just try it yourself.
This is the power of recursion, but only one example to express it. Recursion can do a lot more, for example: A function that returns the depth of a list (How many layers of inner lists do you have to go through) (or, a quantifiable number to show how badly your friend wants to mess with you). a function to return the longest list, and lots more. It even covers things like ADTs which I won't get into until a later date.
I hope you've learned something today about recursion, and remember:
To understand recursion, you must first understand recursion!
No comments:
Post a Comment