gpt4 book ai didi

python - 在python中比较超过最大递归深度?

转载 作者:太空宇宙 更新时间:2023-11-04 05:30:04 25 4
gpt4 key购买 nike

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

我的代码在像这个例子这样的小字典上运行良好,但在有超过 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}

最佳答案

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

def compute_distance(node, dic, node_distance, count, parent, my_list):
my_list.append(node)
...
compute_distance(child, dic, node_distance, count + 1, node, my_list)
...

但是,这种方法并没有计算从起始节点到每个其他节点的最短路径,它只是对图进行简单的遍历(底层算法是DFS)。

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

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

关于python - 在python中比较超过最大递归深度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37376026/

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