python - 如何确定递归中的最后一个堆栈空间

标签 python algorithm recursion graph graph-traversal

我正在通过递归实现众所周知的深度优先搜索。我想知道是否有办法知道最后一个堆栈空间中的代码。我需要的原因是我不想在输出末尾放置 -> 字符。如果可能,只需在最后一步中使用 '\n'

def DFS(self, vertex=None, visited=None):
    if vertex is None:
        vertex = self.root
    if visited is None:
        visited = []
        print(f"{vertex} -> ", end='')

    visited.append(vertex)
    for neighbor in self.getNeighbors(vertex):
        if neighbor not in visited:
            visited.append(neighbor)
            print(f"{neighbor} -> ", end='')
            self.DFS(neighbor, visited)

例如,它产生 1 -> 2 -> 4 -> 5 ->

有没有办法在同一个方法中做?此外,我可以编写一个辅助函数来删除最后一个 -> 字符。

@Edit:我根据@Carcigenicate 的评论所做的如下

return visited # last line in DFS method
-- in main --
dfs = graph.DFS()
path = " -> ".join(str(vertex) for vertex in dfs)
print(path)

最佳答案

与其尝试对最后一个顶点进行特殊处理,不如对第一个顶点进行特殊处理。也就是说,不要试图弄清楚什么时候不附加“->”,只是不要对第一个顶点这样做:

def DFS(self, vertex=None, visited=None):
    if vertex is None:
        vertex = self.root
    else:
        # Not the first vertex, so need to add the separator.
        print(f" ->", end='')

    if visited is None:
        visited = []

    print(f"{vertex}", end='')

    visited.append(vertex)
    for neighbor in self.getNeighbors(vertex):
        if neighbor not in visited:
            # no need to append here, because it will be done in the recursive call.
            # and the vertex will be printed in the recursive call, too.
            # visited.append(neighbor)
            # print(f"{neighbor} -> ", end='')
            self.DFS(neighbor, visited)

这假设您的初始调用将始终是 DFS(root, None, visited)。我认为这是一个合理的假设。

转念一想,也许使用visited参数作为条件是个更好的主意:

    if vertex is None:
        vertex = self.root

    if visited is None:
        visited = []
    else:
        # Not the first vertex, so need to add the separator.
        print(f" ->", end='')

    print(f"{vertex}", end='')

重点是第一项比最后一项更容易特殊化。

关于python - 如何确定递归中的最后一个堆栈空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53658738/

相关文章:

python - 如何查看用户是否不是多对多关系?

java - 使用 IDDFS 和 GreedyBFS 的食人者和传教士

java - 递归划分数组

javascript - 当异步递归方法完全准备好时如何创建回调

python - 条形图 - 在一列 pandas 上绘制多行

python - Google App Engine 上的 Golang App 调用 Python 脚本

python - 如何使用 FastCGI 部署 django 1.5

algorithm - 寻找区间图中两个节点之间的最有效路径

c++ - 在线段树中查询

java - 编写递归方法来计算具有 n 个元素和 k 个组的组数