摘自<learning python 5th>
- Handling Arbitrary Structures
On the other hand, recursion—or equivalent explicit stack-based algorithms we’ll meet
shortly—can be required to traverse arbitrarily shaped structures. As a simple example
of recursion’s role in this context, consider the task of computing the sum of all the
numbers in a nested sublists structure like this:
[1, [2, [3, 4], 5], 6, [7, 8]] # Arbitrarily nested sublists
Simple looping statements won’t work here because this is not a linear iteration. Nested
looping statements do not suffice either, because the sublists may be nested to arbitrary
depth and in an arbitrary shape—there’s no way to know how many nested loops to
code to handle all cases. Instead, the following code accommodates such general nestingby using recursion to visit sublists along the way:
def sumtree(L): tot = 0 for x in L: # For each item at this level if not isinstance(x, list): tot += x # Add numbers directly else: tot += sumtree(x) # Recur for sublists return tot
- Recursion versus queues and stacks
It sometimes helps to understand that internally, Python implements recursion by
pushing information on a call stack at each recursive call, so it remembers where it must
return and continue later. In fact, it’s generally possible to implement recursive-style
procedures without recursive calls, by using an explicit stack or queue of your own to
keep track of remaining steps.
For instance, the following computes the same sums as the prior example, but uses an
explicit list to schedule when it will visit items in the subject, instead of issuing recursive
calls; the item at the front of the list is always the next to be processed and summed:
def sumtree(L): # Breadth-first, explicit queue tot = 0 items = list(L) # Start with copy of top level while items: front = items.pop(0) # Fetch/delete front item if not isinstance(front, list): tot += front # Add numbers directly else: items.extend(front) # <== Append all in nested list return tot
Technically, this code traverses the list in breadth-firstfashion by levels, because it adds
nested lists’ contents to the end of the list, forming a first-in-first-out queue. To emulate
the traversal of the recursive call version more closely, we can change it to perform
depth-firsttraversal simply by adding the content of nested lists to the front of the list,
forming a last-in-first-out stack:
def sumtree(L): # Depth-first, explicit stack tot = 0 items = list(L) # Start with copy of top level while items: front = items.pop(0) # Fetch/delete front item if not isinstance(front, list): tot += front # Add numbers directly else: items[:0] = front # <== Prepend all in nested list return tot