def sum_list(L):
if isinstance(L, list):
return sum([sum_list(x) for x in L])
else: # L is an int
return L
Consider this method, we find that this method re-can use itself (see 'return sum([sum_list(x) for x in L]) ', here it re-uses the sum_list method), and because of this, when some of the elements are a list of numbers, the method can split this list into numbers and then calculate the sum of the list. Therefore, we can get the sum of the entire list.
Recursion is special because it can change different type of things into the same type of things by re-using the method. When we look at the body of the def, we can find that the use of 'else' and 'sum_list(x) for x in L' is to change different type of elements into the same type of elements, and the 'return sum' part is actually the part that can help us get the final answer. So when we want to use recursion to solve problems, we first need to think about how to transform those elements into one same type, and then once we finish the first step, we can think about how to get the final answer.
In conclusion, recursion is ingenious but complex, we still need to have a lot of practice on recursion so that we can be skilled in using recursion.
没有评论:
发表评论