[英]Recursive function on mutable object
I am trying to build all paths recursively in a class.我试图在一个类中递归地构建所有路径。 Here is what I have so far:
这是我到目前为止所拥有的:
def get_paths(self, component=None, current_path=None, all_paths=None):
# set defaults
if component is None:
component = self._ground;
current_path = [component,]
##### [START] RECURSIVE PART #####
# get parents of component
parents = component.parents()
# if no parents (an endpoint/leaf), add the current_path
if not parents:
all_paths.append(current_path)
# if parents ==> recurse
# note: because we're starting from the ground and getting all parents
# we insert the parent before the current path (not after, like if we
# were recursively getting files in a directory)
else:
for parent in parents:
self.get_paths(parent, [parent,] + current_path), all_paths)
##### [END] RECURSIVE PART #####
# Note that the recursion doesn't 'return' anything, it only modifies
# the list. We still have to return the list by the method at the end.
return all_paths
What this does is it starts at the 'ground' and then recurses up until the element does not have any parents.它的作用是从“基础”开始,然后递归直到元素没有任何父元素。 My question is whether this is a common way to do recursion -- to not actually return anything in the 'recursive part' but just to modify the mutable element (the list here) and then return the result later.
我的问题是这是否是一种常见的递归方式——实际上不在“递归部分”中返回任何内容,而只是修改可变元素(此处为列表),然后稍后返回结果。
If the above isn't ideal, what would be an example of how it can be improved?如果上述内容不理想,那么如何改进它的示例是什么? Or, what are other ways in which to return a list of paths (the above is very similar to what the
$ find ./
would do getting a list of paths).或者,返回路径列表的其他方法是什么(上面与
$ find ./
获取路径列表的方法非常相似)。
A simple way to do it would be to have a public "interface" method that calls a private recursive method.一个简单的方法是拥有一个调用私有递归方法的公共“接口”方法。
Something along these lines:沿着这些路线的东西:
class Klass:
_ground = 'ground'
# Public method.
def get_paths(self, component=None, current_path=None):
all_paths = []
self._get_paths(all_paths, component, current_path) # Call private method.
return all_paths
# Private method.
def _get_paths(self, all_paths, component=None, current_path=None):
# Modifies all_paths - executed for that side-effect.
# set defaults
if component is None:
component = self._ground;
current_path = [component,]
# get parents of component
parents = component.parents()
# if no parents (an endpoint/leaf), add the current_path
if not parents:
all_paths.append(current_path)
else:
for parent in parents:
self._get_paths(parent, [parent,] + current_path), all_paths)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.