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
This is a recursion exercise in class. From the example we trace the list and to see how python works and caculate their sum.
You may find that recursion is useful when a function calls itself. We could not type it again and give it to be sloved by python itself.
Based on this we define insert method which use recursion :
def insert_after(L, n1, n2):
"""
(list, int, int) -> NoneType
After each occurrence of n1 in L, insert n2.
>>> L = [5, 1, 2, 1, 6]
>>> insert_after(L, 1, 99)
>>> L
[5, 1, 99, 2, 1, 99, 6]
"""
i = 0
while i < len(L):
if L[i] == n1:
L.insert(i+1, n2)
i += 1
i += 1
if __name__ == "__main__":
import doctest
doctest.testmod()
So far, we are not how to write these recursion code, but from trace them and exercises in handout we could be more familiar with them.
Recursion mind is really helpful when writing code. It reduces a lot steps which gives us a new view to look codes.
没有评论:
发表评论