递归和迭代之间的转换简单例子
2014-02-23 15:25
323 查看
摘自<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:
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:
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:
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
相关文章推荐
- 对python dataframe ,list 之间的循环,迭代,还有转换的运用的自己的小例子
- 总结下简单的递归和迭代的例子
- 简单谈谈Resource,Drawable和Bitmap之间的转换
- 日期类型和字符转类型之间的最简单转换方法
- 自定义隐式转换和显式转换c#简单例子
- 递归和迭代之间的差
- 使用反射,实现简单的JSON与Bean之间的转换
- JAVA开发之 21-原码、反码、补码之间的转换和简单运算
- 我K,才发现ANSI和UNICODE之间的转换居然如此简单!!!
- [LeetCode系列]爬梯问题的递归解法转换为迭代解法
- 简单算法--迭代/递归
- 递归和迭代之间的差
- PHP数组与对象之间使用递归实现转换的方法
- 迭代与递归(及异同点的简单分析)以及Fibonacci数列的两种实现
- jct 模板通过json 从java 之间得到值的一个简单例子
- 简单的stringstream实例--实现字符串与数字之间相互转换
- 简单递归例子
- Java学习札记14:一个比较String、StringBuffer和StringBuilder之间效率差别的简单例子
- 数组与集合之间简单的相互转换
- SQL2000 存储过程中实现递归的一个简单例子