在python中,超过了最大递归深度?

时间:2016-05-22 15:11:40

标签: python dictionary recursion

我正在尝试找到起始节点的每个节点距离,节点之间的连接是在字典中给出的

我的代码适用于像这个例子的小字典,但是有超过20个节点的字典的问题我得到了一个错误

    if child != parent and child not in my_list:
RecursionError: maximum recursion depth exceeded in comparison

我被困在这里,任何人都可以帮助我吗? enter image description here

我的代码

def compute_distance(node, dic, node_distance, count, parent, my_list):
    children = dic[node]
    node_distance[node].append(count)
    for child in children:
        if child != parent and child not in my_list:
            compute_distance(child, dic, node_distance, count + 1, node, children)
    node_distance_dic = {}
    node_distance_dic = {k: min(v) for k, v in node_distance.items()}
    return node_distance_dic

if __name__ == '__main__':
    starting_node = 9
    dic = {0: [1, 3], 1: [0, 3, 4], 2: [3, 5],
                3: [0, 1, 2, 4, 5, 6], 4: [1, 3, 6, 7],
                5: [2, 3, 6], 6: [3, 4, 5, 7, 8],
                7: [4, 6, 8, 9], 8: [6, 7, 9], 9: [7, 8]}  
    print(compute_distance(starting_node, dic, defaultdict(list), 0, 0, []))

输出(键=节点,值=距离)

{0: 4, 1: 3, 2: 4, 3: 3, 4: 2, 5: 3, 6: 2, 7: 1, 8: 1, 9: 0}

2 个答案:

答案 0 :(得分:1)

我猜\2就是为了跟踪已经访问过的节点,但是你永远不会更新它。因此,您应该添加正在处理的节点,以便不在您已经通过的节点上调用递归。目前,只要图中有一个循环,您的代码就会进入无限循环。另外,不要忘记将它传递到下一个级别:

a

但是,此方法不计算从起始节点到其他节点的最短路径,它只是对图形进行简单遍历(基础算法是DFS)。

为了实现你想要的东西,即从源到每个其他节点的最小距离,你应该研究广度优先搜索(通常称为BFS)。

它将在线性时间内解决您的问题。

答案 1 :(得分:0)

与图表大小没有任何关系。即使对于这个小图,你已经有了无限递归:

dic = {0: [1, 3], 1: [2, 0], 2: [3, 1], 3: [0, 2]}
compute_distance(0, dic, defaultdict(list), 0, 0, [])