gpt4 book ai didi

python - 可变对象上的递归函数

转载 作者:行者123 更新时间:2023-12-01 06:23:17 24 4
gpt4 key购买 nike

我正在尝试在类中递归构建所有路径。这是我到目前为止所拥有的:

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 ./ 获取路径列表的方式非常相似)。

最佳答案

一个简单的方法是使用一个调用私有(private)递归方法的公共(public)“接口(interface)”方法。

大致如下:

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)

关于python - 可变对象上的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60272356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com