def sum_list(L):
""" (int or arbitrarily nested list of int) -> int Return the sum of all ints in L. >>> sum_list([1, [2, 3], [4, 5, [6, 7], 8]]) 36 """ if isinstance(L, list): return sum([sum_list(x) for x in L]) else: return L
To understand recursion, we need to be able to know how it works. As the above illustrates, when the function runs, it will first check if L is the type of list; so the function will call itself to check the terms in the list. Therefore, after a few steps, L will be converted to the following:
sum(1, sum([2, 3]), sum([4, 5, sum([6, 7]), 8))
Therefore, the function will return the result "36".
Tracing recursive function help me a lot on understanding the concept, it also teaches me how to analyze each step of the recursion.
Citation:
"18. Recursion." 18. Recursion — How to Think Like a Computer Scientist: Learning with Python 3. N.p., n.d. Web. 04 Mar. 2015.
No comments:
Post a Comment