This week's topic is chosen among three assigned topic. And I chose recursion because I was surprised by its beauty and efficiency, along with difficulty of implementing. In this slog, I will try to demonstrate some recursive structure and how it is different from looping structure.
It is my very first time to notice recursive structure when I read the structure with self inside. At that time, it was a function about nest list. Before learning recursion, I always wondered how to reach the element in a nest list with different 'depth', let's say [1, 2, 3, 4, [5, [6, 7]]], I can surely point out there are seven elements in this nested list. However, for computer, it is a list with five elements in it, and it is not true that every element is a list with elements in it. So, my first impression is we need a if statement and an else statement to differentiate these situations. At that time, I thought the code would be like this:
i = 0
if #element is a list:
#count the element in this list
for num in element:
i += 1
elif #element is not a list:
#i += 1
But later on, I find that it only works with list of 'depth' 2, if we have a complicated list such as [1, 2, 3, [4, 5, [6, [7]]]]. Then the situation is the num in the function is a list as well. So, obviously, using a loop might enable us to solve the problems with knowing how deep the list is. The problem, however, can be very sophisticated and we may not be able to always find the depth of 'target list'.
At that time, it was about week 4, Danny introduced us the solution to nested list, a recursive function. It is to sum up all numbers in a nested list. What surprised me is code, it is quite concise and tidy. The code is like:
def sum_list(L):
'''
# omited
'''
if isinstance(L, list):
return sum([sum_list(x) for x in L])
else:
return L
At that time, I didn't know list comprehension, so I cannot figure out what this code really does. There is only one place where sum() shows, that is if L is a list, but why there appears else, and if we need a else statement, In what kind of situation do we need to use it? I have so many question. In the following weeks, Danny let us to trace recursion, first example was always pretty simple, which is base case that wouldn't use recursive part. When it comes more complicated part, I feels like can understand why code is like that, but cannot write out this code by myself.
没有评论:
发表评论