首页 > 其他 > 详细

递归和迭代之间的转换简单例子

时间:2014-02-24 08:28:55      阅读:436      评论:0      收藏:0      [点我收藏+]

摘自<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:

bubuko.com,布布扣
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
bubuko.com,布布扣

 

  • 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:

bubuko.com,布布扣
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
bubuko.com,布布扣

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:

bubuko.com,布布扣
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
bubuko.com,布布扣

 

 

递归和迭代之间的转换简单例子

原文:http://www.cnblogs.com/xiangnan/p/3561985.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!