Python 可变对象上的递归函数
我试图在一个类中递归地构建所有路径。以下是我到目前为止的情况:Python 可变对象上的递归函数,python,python-3.x,recursion,Python,Python 3.x,Recursion,我试图在一个类中递归地构建所有路径。以下是我到目前为止的情况: 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
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
它从“地面”开始,然后递归,直到元素没有任何父元素。我的问题是,这是否是执行递归的一种常见方法——实际上不返回“递归部分”中的任何内容,而只是修改可变元素(此处的列表),然后稍后返回结果
如果上述情况不理想,那么可以举什么例子来说明如何改进?或者,返回路径列表的其他方法有哪些(上述方法与
$find./
获取路径列表的方法非常相似)。一种简单的方法是使用一个调用私有递归方法的公共“接口”方法
大致如下:
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)
切勿将列表(或其他可变值)用作默认参数<定义函数时,将定义一次代码>所有路径,然后对函数的后续调用将修改该列表。实际上,您只能调用该函数一次。您需要将其设置为
None
,然后检查它,并在函数体中将结果设置为[]
。@Boris感谢您指出这一点。我了解到,当它传递[]
而不是无
时,尝试调试它的困难之处在于。非常感谢。另外,我用这个更改更新了这个问题,因为我正在寻找修改元素的一般结构/功能的答案。如果我们知道要传递给它什么,为什么不删除方法中的默认参数?@David542:对于私有方法可能可以这样做。