【发布时间】:2016-09-19 10:49:00
【问题描述】:
我正在尝试查找每个节点与起始节点的距离,并且节点之间的连接在字典中给出
我的代码适用于像这个例子这样的小字典,但是超过 20 个节点的字典的问题我得到了一个错误
if child != parent and child not in my_list:
RecursionError: maximum recursion depth exceeded in comparison
我的代码
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}
【问题讨论】:
-
这是因为您的递归堆栈呈指数增长。尝试使用迭代算法或某种形式的记忆。虽然通过增加堆栈深度,这种算法对于 20 个节点等少量节点应该是可以的,但对于更大或更密集的图来说,它不会有效。
-
对不起,我编辑了我的帖子
-
我改成node_distance
标签: python dictionary recursion