一直试图打印由以下字典定义的图形的所有路径
graph = {
"a": [
{"child": "b", "cost": 5},
{"child": "e", "cost": 8}
],
"b": [
{"child": "c", "cost": 7},
{"child": "f", "cost": 2}
],
"d": [
{"child": "g", "cost": 3},
],
"e": [
{"child": "d", "cost": 3},
{"child": "f", "cost": 6}
],
"f": [
{"child": "c", "cost": 1},
],
"g": [
{"child": "h", "cost": 10}
],
"h": [
{"child": "f", "cost": 4}
]
}
def print_all_child_paths(graph, node_name):
node = graph[node_name]
if len(node) == 0:
print("No children under this node")
else:
x = 1
for child_node in node:
print("Path number " + str(x) + ": ")
print(node_name + " -> ")
current_node = child_node
while current_node["child"] in graph:
print(current_node["child"] + " -> ")
current_node = graph[current_node["child"]]
print("END.")
x += 1
print("End of paths")
print_all_child_paths(graph, "a")
当我运行该函数时print_all_child_paths,我以错误告终list indices must be integers, not str。
编译器指向第 40 行,即 while 循环定义: while current_node["child"] in graph:
我对错误感到困惑,因为循环的条件是检查键是否在字典中。谁能帮我这个?
提前致谢。
米脂
慕无忌1623718
相关分类