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


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

     

  • 相关阅读:
    【STL】各容器成员对比表
    windows笔记页文件支持的内存映射文件
    windows笔记【内核对象线程同步】线程同步对象速查表
    windows笔记虚拟内存
    windows笔记使用内存映射文件在进程之间共享数据
    svn个人服务端
    解决安装Visual Studio .NET 2003 时FrontPage 2000 WEB 扩展客户端 安装失败
    vc6.0转vs2008连接错误
    Sublime Text插件推荐
    末日了,说出你的梦想、愿望还有遗憾吧。
  • 原文地址:https://www.cnblogs.com/xiangnan/p/3561985.html
Copyright © 2020-2023  润新知