Recursion, in short, means use the definition itself to define the definition. It has certain pattern:
def mm(L):
"""
(int or arbitrarily nested list of int) -> int
Mystery method. Exactly the same as sum_list,
except for the last line
"""
if isinstance(L, list):
return sum( [count(x) for x in L] )
else:
return 0
Here the isinstance(X, type) is always there because we need to decide whether to recurs L or end L. By this way we peel the L like an onion until it becomes the very basic element. In the example above L may originally be a list, and after recurs L again and again, the lists would be broken and separated into small elements.
没有评论:
发表评论