【问题标题】:How to store values from a recursive graph function?如何存储递归图函数中的值?
【发布时间】:2025-12-30 21:55:06
【问题描述】:

我有以下递归函数 - 该函数可以很好地打印出树/图的所有路径。但是尝试将ROUTES 添加为全局变量并附加到它会导致一堆空的嵌套列表: [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],...等

我正在寻找使用全局变量的更好解决方案和存储路径的更好解决方案,这就是我的功能:

 def printAllPathsUtil(self, u, d, visited, path):
        # Mark the current node as visited and store in path
        visited[u] = True
        path.append(u)
        # If current vertex is same as destination, then print
        # current path[]
        if u == d:
            print(path)
            ROUTES.append(path)
        else:
            # If current vertex is not destination
            # Recur for all the vertices adjacent to this vertex
            for i in self.graph[u]:
                if visited[i] == False:
                    self.printAllPathsUtil(i, d, visited, path)
                    # Remove current vertex from path[] and mark it as unvisited

        path.pop()
        visited[u] = False

【问题讨论】:

  • ROUTES.append(i for i in path) 好像输出[<generator object Graph.printAllPathsUtil.<locals>.<genexpr> at 0x03B27F30>, <generator object Graph.printAllPathsUtil.<locals>.<genexpr> at 0x03B27F70>, <generator object Graph.printAllPathsUtil.<locals>.

标签: python python-3.x list recursion


【解决方案1】:

问题的根源在于您添加到 ROUTES 的路径变量是对您用来控制遍历的同一对象的引用。每次找到目的地时都会添加相同的对象,因此,当过程结束(并且路径再次为空)时,您的 ROUTE 列表包含对(现在为空的)路径对象的多个引用。

您的更正ROUTES.append([i for i in path]) 创建了路径变量的新实例以存储在 ROUTES 列表中。这就是它起作用的原因。

在 Python 中,将列表存储在变量中是一个常见的错误,假设您持有一个副本,而实际上它只是一个参考,并且内容可能会被程序的其他部分修改,从而更改原始内容。

请注意,您也可以使用 ROUTES.append(path.copy())ROUTES.append(list(path))ROUTES.append([*path])

【讨论】: